Пример #1
0
 public static void WriteLineKeyIfPresent(this StreamWriter sw, INamedValueSet nvs, string key)
 {
     if (nvs.Contains(key))
     {
         sw.CheckedWriteLine("${0},{1}", key, nvs[key].VC);
     }
 }
Пример #2
0
 public static void ConsoleWriteLineKeyIfPresent(this INamedValueSet nvs, string key)
 {
     if (nvs.Contains(key))
     {
         Console.WriteLine(" {0}".CheckedFormat(nvs[key]));
     }
 }
Пример #3
0
        public static SubstrateRoutingItemBase AttemptToGenerateSubstrateRoutingItem(this IStringParamAction serviceAction)
        {
            string         serviceActionParam = serviceAction.ParamValue;
            INamedValueSet actionNVP          = serviceAction.NamedParamValues;

            return(AttemptToGenerateSubstrateRoutingItem(serviceActionParam, actionNVP));
        }
Пример #4
0
        public SubstrateRoutingManagerDetails(INamedValueSet detailsNVS)
        {
            var nvs = detailsNVS.MapNullToEmpty();

            KnownSubstLocNameList          = nvs["KnownSubstLocNameList"].VC.GetValue <ReadOnlyIList <string> >(rethrow: false).MapNullToEmpty();
            KnownProxySubstLocNameList     = nvs["KnownProxySubstLocNameList"].VC.GetValue <ReadOnlyIList <string> >(rethrow: false).MapNullToEmpty();
            SupportsSwapAtSubstLocNameList = nvs["SupportsSwapAtSubstLocNameList"].VC.GetValue <ReadOnlyIList <string> >(rethrow: false).MapNullToEmpty();
            SupportsSwapAtAllLocations     = nvs["SupportsSwapAtAllLocations"].VC.GetValue <bool>(rethrow: false);
        }
Пример #5
0
 public MetaDataCommonInfoBase(MetaDataCommonInfoBase rhs)
 {
     ItemType  = rhs.ItemType;
     Name      = rhs.Name;
     Comment   = rhs.Comment;
     FileID    = rhs.FileID;
     ClientID  = rhs.ClientID;
     IFC       = rhs.IFC;
     ClientNVS = rhs.ClientNVS;
 }
Пример #6
0
        private void Activate(ProcessTracker pt, int activeSetIdx)
        {
            MDRF.Common.DateTimeStampPair dtPair = MDRF.Common.DateTimeStampPair.Now;

            // if needed - deactivate the previous pt in the given index
            ActiveSetItemTracker activeSetItemTracker = activeSetItemTrackerArray[activeSetIdx];

            ProcessTracker priorPT = activeSetItemTracker.ProcessTracker;

            if (priorPT != null)
            {
                // record the last set of values (and the map) from the old ProcessTracker before replacing them with the new values.
                activeSetItemTracker.GroupInfo.Touched = true;
                activeSetMapGroup.GroupInfo.Touched    = true;
                mdrfWriter.RecordGroups(dtPair: dtPair);

                string         deactivateReason    = "pid:{0} '{1}' is being {2}".CheckedFormat(pt.pid, pt.name, pt.elevationRequestReason.IsNullOrEmpty() ? "activated" : "elevated");
                INamedValueSet extraDeactivatedNVS = new NamedValueSet()
                {
                    { "deactivateReason", deactivateReason }, { "activeSetNum", activeSetIdx + 1 }
                }.MakeReadOnly();

                priorPT.activePTSetIndex = -1;
                RecordProcessEvent("Deactivated", priorPT, extraNVS: extraDeactivatedNVS, includeExtraProcessInfo: false, includeTrackedValues: true, dtPair: dtPair);
            }

            // now move the given pt into the active set at the selected index.

            INamedValueSet extraNVS = (pt.elevationRequestReason.IsNullOrEmpty() ? new NamedValueSet()
            {
                { "activeSetNum", activeSetIdx + 1 }
            } : new NamedValueSet()
            {
                { "elevateReason", pt.elevationRequestReason }, { "activeSetNum", activeSetIdx + 1 }
            }).MakeReadOnly();

            RecordProcessEvent("Activated", pt, extraNVS: extraNVS, includeExtraProcessInfo: false, includeTrackedValues: true, dtPair: dtPair);

            pt.activePTSetIndex = activeSetIdx;
            pt.activationBaselineTrackedValues  = pt.prevTrackedValues;
            activeSetItemTracker.ProcessTracker = pt;
            activeSetItemTracker.UpdateGroupItems();
            activeSetItemTracker.GroupInfo.Touched = true;

            activeSetMapGroup.Update(activeSetIdx, pt.pid, pt.name);

            mdrfWriter.RecordGroups(dtPair: dtPair);
        }
Пример #7
0
        public INamedValueSet GetPayloadAsE005NVS(INamedValueSet fallbackValue = null)
        {
            if ((Flags & BufferHeaderFlags.BufferContainsE005NVS) != 0)
            {
                int            startAtIndex = header.Length;
                string         ec           = null;
                INamedValueSet nvs          = NamedValueSet.Empty.ConvertFromE005Data(byteArray, ref startAtIndex, ref ec);

                if (ec.IsNullOrEmpty() && startAtIndex == byteCount)
                {
                    return(nvs);
                }
            }

            return(fallbackValue);
        }
Пример #8
0
        private void RecordProcessEvent(string eventName, ProcessTracker pt, INamedValueSet extraNVS = null, bool includeExtraProcessInfo = false, bool includeTrackedValues = false, MDRF.Common.DateTimeStampPair dtPair = null)
        {
            if (extraNVS.IsNullOrEmpty())
            {
                Log.Info.Emit("{0} pid:{1} name:{2}", eventName, pt.pid, pt.name);
            }
            else
            {
                Log.Info.Emit("{0} pid:{1} name:{2} {3}", eventName, pt.pid, pt.name, extraNVS);
            }

            INamedValueSet nvs = new NamedValueSet()
            {
                { "eventName", eventName }
            }
            .MergeWith(pt.AsNVS(includeExtraProcessInfo: includeExtraProcessInfo, includeTrackedValues: includeTrackedValues))
            .MergeWith(extraNVS, NamedValueMergeBehavior.AddNewItems)
            .ConvertToReadOnly();

            mdrfWriter.RecordOccurrence(ProcessDeltaOccurrenceInfo, new ValueContainer(nvs), dtPair: dtPair);
        }
Пример #9
0
        public Message Update(INamedValueSet buildPayloadDataFromNVS = null, string buildPayloadDataFromString = null, BufferHeaderFlags?orInFlags = null)
        {
            if (buildPayloadDataFromNVS != null)
            {
                NVS = buildPayloadDataFromNVS;
            }

            if (buildPayloadDataFromString != null)
            {
                String = buildPayloadDataFromString;
            }

            if (orInFlags != null)
            {
                Buffers.Buffer firstBuffer = bufferList.SafeAccess(0);
                if (firstBuffer != null)
                {
                    firstBuffer.Update(orInFlags: orInFlags);
                }
            }

            return(this);
        }
Пример #10
0
        public Buffer Update(PurposeCode?purposeCode = null, BufferHeaderFlags?orInFlags = null, ulong?seqNum = null, int?byteCount = null, ulong?ackSeqNum = null, INamedValueSet buildPayloadDataFromE005NVS = null, bool throwOnException = false, byte[] copyPayloadDataFromByteArray = null, INotifyable notifyOnSetState = null)
        {
            if (purposeCode != null)
            {
                header.PurposeCode = purposeCode ?? PurposeCode.None;
            }

            if (orInFlags != null)
            {
                header.Flags |= orInFlags ?? BufferHeaderFlags.None;
            }

            if (seqNum != null)
            {
                SeqNum = seqNum ?? 0;
            }

            if (byteCount != null)
            {
                this.byteCount = byteCount ?? 0;
            }

            if (ackSeqNum != null)
            {
                header.AckSeqNum = ackSeqNum ?? 0;
            }

            if (buildPayloadDataFromE005NVS != null)
            {
                header.Flags |= BufferHeaderFlags.BufferContainsE005NVS;
                copyPayloadDataFromByteArray = buildPayloadDataFromE005NVS.ConvertToE005Data(throwOnException: throwOnException);
            }

            if (copyPayloadDataFromByteArray != null)
            {
                byteArray.SafeCopyFrom(header.Length, copyPayloadDataFromByteArray);
                this.byteCount = Math.Min(header.Length + copyPayloadDataFromByteArray.Length, byteArraySize);
            }

            if (notifyOnSetState != null)
            {
                NotifyOnSetState = notifyOnSetState;
            }

            return(this);
        }
Пример #11
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;
        }
Пример #12
0
 /// <summary>
 /// Call chainable version of setter for IClientFacet's NamedParamValues property.
 /// If <paramref name="namedParamValues"/> is null and <paramref name="ifNotNull"/> is true then this method makes no change.
 /// </summary>
 public static TClientFacetType SetNamedParamValues <TClientFacetType>(this TClientFacetType action, INamedValueSet namedParamValues, bool ifNotNull = false) where TClientFacetType : IClientFacet
 {
     if (namedParamValues != null || !ifNotNull)
     {
         action.NamedParamValues = namedParamValues;
     }
     return(action);
 }
Пример #13
0
 /// <summary>
 /// Constructor: Accepts provider name, filePath to ini file to read/write, keyPrefix to prefix on all contained keys,
 /// and isReadWrite to indicate if the INI file is writable or not (ie if all of the keys should be IsFixed).
 /// </summary>
 public PersistentJsonDotNetTextFileRingProvider(string name, PersistentObjectFileRingConfig ringConfig, string keyPrefix = "", bool isReadWrite = true, INamedValueSet providerMetaData = null, bool sortKeysOnSave = false)
     : base(name, ringConfig, new DataContractPersistentJsonDotNetTextFileRingStorageAdapter <ConfigKeyStore>(name, ringConfig) { Object = new ConfigKeyStore() }, keyPrefix: keyPrefix, isReadWrite: isReadWrite, providerMetaData: providerMetaData, keysMayBeAddedUsingEnsureExistsOption: isReadWrite, sortKeysOnSave: sortKeysOnSave)
 {
 }
Пример #14
0
        protected override string PerformServiceActionEx(IProviderFacet ipf, string serviceName, INamedValueSet npv)
        {
            switch (serviceName)
            {
            case "Sync":
                return(PerformSync());

            case "SetKey":
            {
                string         key          = npv["key"].VC.GetValue <string>(rethrow: true);
                ValueContainer value        = npv["value"].VC;
                string         comment      = npv["comment"].VC.GetValue <string>(rethrow: false, defaultValue: null).MapNullTo("{0} operation has been performed using the {1} part".CheckedFormat(serviceName, PartID));
                bool?          ensureExists = npv["ensureExists"].VC.GetValue <bool?>(rethrow: false);

                IConfigKeyAccess icka = Config.GetConfigKeyAccess(key, ensureExists: ensureExists, defaultValue: value);

                if (icka == null)
                {
                    return("Internal: GetConfigKeyAccess generated null ICKA for key '{0}'".CheckedFormat(key));
                }

                if (!icka.IsUsable)
                {
                    return("Key lookup for '{0}' gave error: {1}".CheckedFormat(key, icka.ResultCode));
                }

                string ec = icka.SetValue(value, commentStr: comment);

                ServiceBridge();

                return(ec.MapNullTo("[Internal: final ec was null]"));
            }

            case "SetKeys":
            {
                string []         keys    = npv["keys"].VC.GetValue <string []>(rethrow: true);
                ValueContainer [] values  = npv["values"].VC.GetValue <ValueContainer []>(rethrow: true);
                string            comment = npv["comment"].VC.GetValue <string>(rethrow: false, defaultValue: null).MapNullTo("{0} operation has been performed using the {1} part".CheckedFormat(serviceName, PartID));
                bool?ensureExists         = npv["ensureExists"].VC.GetValue <bool?>(rethrow: false);

                if (keys.SafeLength() != values.SafeLength())
                {
                    return("Given keys and values were not the same length");
                }

                if (keys.SafeLength() == 0)
                {
                    return("No keys were given to change");
                }

                IConfigKeyAccess[] ickaArray = keys.Select((key, idx) => Config.GetConfigKeyAccess(key, ensureExists: ensureExists, defaultValue: values[idx])).ToArray();

                if (ickaArray.Any(icka => icka == null))
                {
                    return("Internal: GetConfigKeyAccess generated null ICKA for one or more keys in [{0}]".CheckedFormat(string.Join(",", keys)));
                }

                var notFoundKeys = ickaArray.Where(icka => !icka.IsUsable).Select(icka => icka.Key).ToArray();
                if (!notFoundKeys.IsNullOrEmpty())
                {
                    return("Key lookup for keys '{0}' failed".CheckedFormat(string.Join(",", notFoundKeys)));
                }

                string ec = Config.SetValues(ickaArray.Select((icka, idx) => KVP.Create(icka, values[idx])).ToArray(), comment);

                ServiceBridge();

                return(ec.MapNullTo("[Internal: final ec was null]"));
            }

            default:
                return(base.PerformServiceAction(serviceName));
            }
        }
Пример #15
0
 [AttachedPropertyBrowsableForType(typeof(Control))] public static void SetNPV(Control obj, INamedValueSet value)
 {
     obj.SetValue(NPVProperty, value);
 }
Пример #16
0
 /// <summary>
 /// Basic HandleOnStartup method signature.  Caller provides logBaseName.
 /// Program's command line arguments will be obtained from the given StartupEventArgs value.  These will be used with the (optional) initial setup of Modular.Config.
 /// appLogger will be assigned to a new logger (this is expected to be used by the client in calls to later HandleYYY methods).
 /// <para/>See the description and remarks for the full HandleOnStartup method variant for more details.
 /// </summary>
 public static void HandleOnStartup(StartupEventArgs e, ref Logging.Logger appLogger, INamedValueSet nvs)
 {
     string[] args = (e != null) ? e.Args : null;
     HandleOnStartup(ref args, ref appLogger, nvs: nvs);
 }
Пример #17
0
        private static SubstrateRoutingItemBase AttemptToGenerateSubstrateRoutingItem(string serviceActionParam, INamedValueSet actionNVP)
        {
            switch (serviceActionParam)
            {
            case "Move": return(new MoveSubstrateItem(actionNVP["SubstName"].VC.GetValue <string>(rethrow: false).CreateE090SubstID(), actionNVP["ToSubstLocName"].VC.GetValue <string>(rethrow: false)));

            case "Swap": return(new SwapSubstratesItem(actionNVP["SubstName"].VC.GetValue <string>(rethrow: false).CreateE090SubstID(), actionNVP["SwapWithSubstName"].VC.GetValue <string>(rethrow: false).CreateE090SubstID()));

            default: return(null);
            }
        }
Пример #18
0
        /// <summary>
        /// Full HandleOnStartup method signature.
        /// <paramref name="argsRef"/> line arguments string array will be used with the (optional) initial setup of Modular.Config.
        /// If this parameter is non-null, it will be processed to extract the key=value items it contains, and will be replaced with a new array that has the consumed key=value items removed from it.
        /// <paramref name="appLogger"/> will be assigned to a new logger (this is expected to be used by the client in calls to later HandleYYY methods).
        /// <paramref name="nvs"/> is used to pass all directly caller configurable values that are supported by this method (see remarks section below)
        /// </summary>
        /// <remarks>
        /// logBaseName: optional name used in the default log file names that are generated.  Also used to name the main thread if it has not already been named.
        /// addWPFLMH: no longer supported - ignored
        /// addSetLMH: pass as true to enable creating a set based log message handler.
        /// enableUEH: if true, this method will install an unhandled exception handler, if none has already been established.  Set to false to disable this behavior.
        /// providerSelect: set to StandardProviderSelect value to override the default behavior of StandardProviderSelect.All.  This value will be ignored if there are already any providers registered with Config.Instance when this method is called.  If the given argsRef array value is null then MainArgs will be excluded from this value.
        /// uehFileWritePath: may be used to override the config key value (Config.UnhandledExceptionEventHandler.FilePath), and/or its initial value.  Must be non-empty to enable setting up an UEH.
        /// mainLoggerType: may be used to override the config key value (Config.Logging.MainLogger.Type), and/or its initial value.  When neither this parameter, nor the configuration key are found to give a valid FileRingLogMessageHandlerType value, the static DefaultMainLoggerType is used.
        /// diagTraceLMHSettingFlags, setLMHSettingFlags: may be used to override the corresponding config key values (Config.Logging.DiagnosticTrace/Set), and/or their initial values. (LogMessageHandlerSettingFlags)
        /// setName, setCapacity, setLogGate: may be used to override the corresponding config key values (Config.Logging.Set.Name/Capacity/LogGate), and/or their initial values.
        /// appEventMesgType: may be used to define the MesgType to be used for App Event messages.  When present, this key's value is used to set the AppEventMesgType.
        /// traceLoggingGroupName: may be used to override the config key value (Config.Logging.TraceRing.LGID) and/or its initial value.
        /// traceRingLinkFromDefaultGroup, traceRingLinkToDefaultGroup: when present these boolean values control the corresponding function without regard to the contents of the corresponding modular config values.
        /// </remarks>
        public static void HandleOnStartup(ref string[] argsRef, ref Logging.Logger appLogger, INamedValueSet nvs = null)
        {
            System.Reflection.Assembly callerAssy = CallerAssembly;

            nvs = nvs.MapNullToEmpty();

            string logBaseName = nvs["logBaseName"].VC.GetValue <string>(rethrow: false)
                                 ?? callerAssy.GetAssemblyNameFromFullName();
            bool addWPFLMH = nvs["addWPFLMH"].VC.GetValue <bool?>(rethrow: false) ?? false;
            bool addSetLMH = nvs["addSetLMH"].VC.GetValue <bool?>(rethrow: false) ?? false;
            bool enableUEH = nvs["enableUEH"].VC.GetValue <bool?>(rethrow: false) ?? true;

            System.Diagnostics.Process currentProcess  = System.Diagnostics.Process.GetCurrentProcess();
            System.Threading.Thread    currentThread   = System.Threading.Thread.CurrentThread;
            System.Reflection.Assembly currentExecAssy = System.Reflection.Assembly.GetExecutingAssembly();
            System.Reflection.Assembly mainAssy        = System.Reflection.Assembly.GetEntryAssembly();

            if (currentThread.Name.IsNullOrEmpty())
            {
                currentThread.Name = "{0}.Main".CheckedFormat(logBaseName);
            }

            IConfig config = Config.Instance;

            StandardProviderSelect providerSelect = nvs["providerSelect"].VC.GetValue <StandardProviderSelect>(rethrow: false, defaultValue: StandardProviderSelect.All);

            if (argsRef == null)
            {
                providerSelect &= ~StandardProviderSelect.MainArgs;
            }

            if (providerSelect != StandardProviderSelect.None && config.Providers.IsNullOrEmpty())
            {
                config.AddStandardProviders(ref argsRef, providerSelect: providerSelect);
            }

            if (enableUEH && UnhandledExceptionEventHandler != null)
            {
                uehFileWritePath = nvs["uehFileWritePath"].VC.GetValue <string>(rethrow: false)
                                   ?? config.GetConfigKeyAccessOnce("Config.UnhandledExceptionEventHandler.FilePath", silenceLogging: true).GetValue(uehFileWritePath);

                if (!uehFileWritePath.IsNullOrEmpty())
                {
                    AppDomain currentDomain = AppDomain.CurrentDomain;
                    currentDomain.UnhandledException += UnhandledExceptionEventHandler;
                }
            }

            int ringQueueSize  = 500;
            int traceQueueSize = 1000;

            Logging.ListMesgEmitter issueListEmitter = new Logging.ListMesgEmitter()
            {
                MesgType = Logging.MesgType.Error
            };
            Logging.ListMesgEmitter valuesListEmitter = new Logging.ListMesgEmitter()
            {
                MesgType = Logging.MesgType.Debug
            };

            FileRingLogMessageHandlerType mainLoggerType = nvs["mainLoggerType"].VC.GetValue <FileRingLogMessageHandlerType?>(rethrow: false)
                                                           ?? config.GetConfigKeyAccessOnce("Config.Logging.MainLogger.Type").GetValue <FileRingLogMessageHandlerType?>()
                                                           ?? DefaultMainLoggerType;

            Logging.FileRotationLoggingConfig fileRotationRingConfig = new Logging.FileRotationLoggingConfig(logBaseName.MapNullToEmpty() + "LogFile")
            {
                mesgQueueSize           = ringQueueSize,
                nameUsesDateAndTime     = true,
                fileHeaderLines         = Logging.GenerateDefaultHeaderLines(logBaseName, includeNullForDynamicLines: true, hostingAssembly: callerAssy),
                fileHeaderLinesDelegate = Logging.GenerateDynamicHeaderLines,
                logGate = Logging.LogGate.Debug,
            };

            Logging.Handlers.TextFileDateTreeLogMessageHandler.Config dateTreeDirConfig = new Logging.Handlers.TextFileDateTreeLogMessageHandler.Config(logBaseName.MapNullToEmpty() + "Log", @".\Logs")
            {
                FileHeaderLines         = Logging.GenerateDefaultHeaderLines(logBaseName, includeNullForDynamicLines: true, hostingAssembly: callerAssy),
                FileHeaderLinesDelegate = Logging.GenerateDynamicHeaderLines,
                LogGate = Logging.LogGate.Debug,
            };

            switch (mainLoggerType)
            {
            case FileRingLogMessageHandlerType.TextFileRotationDirectoryLogMessageHandler:
                fileRotationRingConfig.UpdateFromModularConfig("Config.Logging.FileRing.", issueListEmitter, valuesListEmitter, configInstance: config);
                break;

            case  FileRingLogMessageHandlerType.TextFileDateTreeDirectoryLogMessageHandler:
                dateTreeDirConfig.UpdateFromModularConfig("Config.Logging.DateTree.", issueListEmitter, valuesListEmitter, configInstance: config);
                break;

            default:
            case FileRingLogMessageHandlerType.None:
                break;
            }

            Logging.ILogMessageHandler mainLMHnoQ = null;

            int maxQueueSize = 1000;

            switch (mainLoggerType)
            {
            case FileRingLogMessageHandlerType.TextFileRotationDirectoryLogMessageHandler:
                mainLMHnoQ   = new Logging.Handlers.TextFileRotationLogMessageHandler(fileRotationRingConfig);
                maxQueueSize = fileRotationRingConfig.mesgQueueSize;
                break;

            case FileRingLogMessageHandlerType.TextFileDateTreeDirectoryLogMessageHandler:
                mainLMHnoQ   = new Logging.Handlers.TextFileDateTreeLogMessageHandler(dateTreeDirConfig);
                maxQueueSize = dateTreeDirConfig.MesgQueueSize;
                break;

            default:
            case FileRingLogMessageHandlerType.None:
                break;
            }

            LogMessageHandlerSettingFlags diagTraceLMHSettingFlags = nvs["diagTraceLMHSettingFlags"].VC.GetValue <LogMessageHandlerSettingFlags?>(rethrow: false)
                                                                     ?? config.GetConfigKeyAccessOnce("Config.Logging.DiagnosticTrace").GetValue(LogMessageHandlerSettingFlags.IncludeWhenDebuggerAttached);
            LogMessageHandlerSettingFlags setLMHSettingFlags = nvs["setLMHSettingFlags"].VC.GetValue <LogMessageHandlerSettingFlags?>(rethrow: false)
                                                               ?? config.GetConfigKeyAccessOnce("Config.Logging.Set").GetValue(addSetLMH ? LogMessageHandlerSettingFlags.IncludeAlways : LogMessageHandlerSettingFlags.Disabled);

            bool addDiagTraceLMH = diagTraceLMHSettingFlags.IsSet(LogMessageHandlerSettingFlags.IncludeAlways) || diagTraceLMHSettingFlags.IsSet(LogMessageHandlerSettingFlags.IncludeWhenDebuggerAttached) && System.Diagnostics.Debugger.IsAttached;

            addSetLMH = setLMHSettingFlags.IsSet(LogMessageHandlerSettingFlags.IncludeAlways) || setLMHSettingFlags.IsSet(LogMessageHandlerSettingFlags.IncludeWhenDebuggerAttached) && System.Diagnostics.Debugger.IsAttached;

            Logging.ILogMessageHandler diagTraceLMH = addDiagTraceLMH ? Logging.CreateDiagnosticTraceLogMessageHandler(logGate: Logging.LogGate.Debug) : null;

            Logging.ILogMessageHandler setLMH = null;
            if (addSetLMH)
            {
                string          setName     = nvs["setName"].VC.GetValue <string>(rethrow: false) ?? config.GetConfigKeyAccessOnce("Config.Logging.Set.Name").GetValue("LogMessageHistory");
                int             setCapacity = nvs["setCapacity"].VC.GetValue <int?>(rethrow: false) ?? config.GetConfigKeyAccessOnce("Config.Logging.Set.Capacity").GetValue(1000);
                Logging.LogGate setLogGate  = nvs["setLogGate"].VC.GetValue <Logging.LogGate?>(rethrow: false) ?? config.GetConfigKeyAccessOnce("Config.Logging.Set.LogGate").GetValue(Logging.LogGate.Debug);

                if (!setName.IsNullOrEmpty())
                {
                    setLMH = new MosaicLib.Logging.Handlers.SetLogMessageHandler(setName, capacity: setCapacity, logGate: setLogGate);
                }
            }

            // Normally all of the standard lmh objects (main, diag, wpf) share the use of a single message queue.
            List <Logging.ILogMessageHandler> mainLMHList = new List <Logging.ILogMessageHandler>();

            if (mainLMHnoQ != null)
            {
                mainLMHList.Add(mainLMHnoQ);
            }

            if (diagTraceLMH != null)
            {
                if (diagTraceLMHSettingFlags.IsClear(LogMessageHandlerSettingFlags.NonQueued))
                {
                    mainLMHList.Add(diagTraceLMH);
                }
                else
                {
                    Logging.AddLogMessageHandlerToDefaultDistributionGroup(diagTraceLMH);
                }
            }

            if (setLMH != null)
            {
                if (setLMHSettingFlags.IsClear(LogMessageHandlerSettingFlags.NonQueued))
                {
                    mainLMHList.Add(setLMH);
                }
                else
                {
                    Logging.AddLogMessageHandlerToDefaultDistributionGroup(setLMH);
                }
            }

            Logging.ILogMessageHandler mainLMHQueueLMH = new Logging.Handlers.QueueLogMessageHandler("lmhMainSet.q", mainLMHList.ToArray(), maxQueueSize: maxQueueSize);
            Logging.AddLogMessageHandlerToDefaultDistributionGroup(mainLMHQueueLMH);

            string traceLoggingGroupName = nvs["traceLoggingGroupName"].VC.GetValue <string>(rethrow: false) ?? config.GetConfigKeyAccessOnce("Config.Logging.TraceRing.LGID", silenceLogging: true).GetValue("LGID.Trace");
            bool   traceRingEnable       = config.GetConfigKeyAccessOnce("Config.Logging.TraceRing.Enable").GetValue(!traceLoggingGroupName.IsNullOrEmpty());

            if (traceRingEnable)
            {
                // Setup the trace logger.  This logger uses a seperate message queue.
                Logging.FileRotationLoggingConfig traceRingConfig = new Logging.FileRotationLoggingConfig((logBaseName ?? String.Empty) + "TraceRing")
                {
                    mesgQueueSize           = traceQueueSize,
                    nameUsesDateAndTime     = false, // will use 4 digit file names.  Limit of 100 files total
                    includeThreadInfo       = true,
                    fileHeaderLines         = Logging.GenerateDefaultHeaderLines("{0} Trace Output".CheckedFormat(logBaseName), includeNullForDynamicLines: true, hostingAssembly: callerAssy),
                    fileHeaderLinesDelegate = Logging.GenerateDynamicHeaderLines,
                    logGate = Logging.LogGate.All,
                }.UpdateFromModularConfig("Config.Logging.TraceRing.", issueListEmitter, valuesListEmitter, configInstance: config);

                Logging.ILogMessageHandler traceRingLMH = Logging.CreateQueuedTextFileRotationDirectoryLogMessageHandler(traceRingConfig);

                Logging.AddLogMessageHandlerToDistributionGroup(traceLoggingGroupName, traceRingLMH);
                Logging.SetDistributionGroupGate(traceLoggingGroupName, Logging.LogGate.All);

                Logging.MapLoggersToDistributionGroup(Logging.LoggerNameMatchType.Regex, @"(\.Data|\.Trace)", traceLoggingGroupName);

                bool traceRingLinkFromDefaultGroup = nvs["traceRingLinkFromDefaultGroup"].VC.GetValue <bool?>(rethrow: false) ?? config.GetConfigKeyAccessOnce("Config.Logging.TraceRing.LinkFromDefaultGroup").GetValue(true);
                bool traceRingLinkToDefaultGroup   = nvs["traceRingLinkToDefaultGroup"].VC.GetValue <bool?>(rethrow: false) ?? config.GetConfigKeyAccessOnce("Config.Logging.TraceRing.LinkToDefaultGroup", silenceLogging: true).GetValue(false);

                if (traceRingLinkFromDefaultGroup)
                {
                    Logging.UpdateGroupSettings(Logging.DefaultDistributionGroupName, new Logging.GroupSettings()
                    {
                        GroupLinkageBehavior = Logging.GroupLinkageBehavior.IncludeLinkedLMHInstancesInGroupGateEvaluation
                    });
                    Logging.LinkDistributionToGroup(Logging.DefaultDistributionGroupName, traceLoggingGroupName);
                }

                if (traceRingLinkToDefaultGroup)
                {
                    Logging.UpdateGroupSettings(traceLoggingGroupName, new Logging.GroupSettings()
                    {
                        GroupLinkageBehavior = Logging.GroupLinkageBehavior.IncludeLinkedLMHInstancesInGroupGateEvaluation
                    });
                    Logging.LinkDistributionToGroup(traceLoggingGroupName, Logging.DefaultDistributionGroupName);
                }
            }

            if (nvs.Contains("appEventMesgType"))
            {
                AppEventMesgType = nvs["appEventMesgType"].VC.GetValue <Logging.MesgType?>(rethrow: false) ?? Logging.MesgType.None;
            }

            appLogger = new Logging.Logger("AppLogger");
            appLogger.Emitter(AppEventMesgType).EmitWith("App Starting", nvs: new NamedValueSet()
            {
                { "AppEvent", "OnStartup" }
            });

            // emit the config messages obtained above.
            Logging.Logger appLoggerCopy = appLogger;
            issueListEmitter.EmittedItemList.ForEach((item) => appLoggerCopy.Error.Emit(item.MesgStr));
            valuesListEmitter.EmittedItemList.ForEach((item) => appLoggerCopy.Debug.Emit(item.MesgStr));

            if (addWPFLMH)
            {
                appLogger.Warning.Emit("Use of MosaicLib.WPF.Logging is no longer supported.  Please enable use of SetLogMessageHandler (addSetLMH/useSetLMH) and convert to use of set based log display controls");
            }
        }
Пример #19
0
        public MDRFHistogramGroupSource(string groupName, Histogram histogram, ulong fileIndexUserRowFlagBits = 0, INamedValueSet extraClientNVS = null, IEnumerable <PartsLib.Tools.MDRF.Writer.GroupPointInfo> extraGPISet = null)
        {
            GroupInfo = new MDRF.Writer.GroupInfo()
            {
                Name = groupName,
                GroupBehaviorOptions     = MDRF.Writer.GroupBehaviorOptions.UseVCHasBeenSetForTouched | MDRF.Writer.GroupBehaviorOptions.IncrSeqNumOnTouched,
                FileIndexUserRowFlagBits = fileIndexUserRowFlagBits,
                GroupPointInfoArray      = new[] { countGPI, minGPI, maxGPI, avgGPI, sdGPI, medianEstGPI, percentile5EstGPI, percentile95EstGPI, binsGPI }.Concat(extraGPISet ?? emptyGPIArray).ToArray(),
                ClientNVS = new NamedValueSet()
                {
                    { "Histogram" }, { "NumBins", histogram.NumBins }, { "BinBoundaryArray", histogram.BinBoundaryArray }
                }.MergeWith(extraClientNVS ?? NamedValueSet.Empty, NamedValueMergeBehavior.AddNewItems).MakeReadOnly(),
            };

            Histogram         = histogram;
            lastBinCountArray = Histogram.BinCountArray.MakeCopyOf();

            UpdateGroupItems();
            GroupInfo.Touched = true;
        }
Пример #20
0
        /// <summary>
        /// Attempt to find a registered part and then asks it to create a service action with the given initial serviceName parameter value.
        /// If the desired part cannot be found then the method returns null (if throwOnNotFound is false) or it throws a PartIDNotFoundException (if the throwOnNotFound is true).
        /// </summary>
        /// <param name="partID">Gives the part ID on which to create a service action.</param>
        /// <param name="serviceName">Gives the initial value of the service name to be performed, or null, or string.Empty if the name is not already known.</param>
        /// <param name="namedParamValues">Gives the initial value that the created action's NamedParamValues will be set to.</param>
        /// <param name="throwOnNotFound">When true this method will throw a PartIDNotFoundException if the given partID is not found.  When false the method will return null when the given partID is not found.</param>
        /// <exception cref="PartIDNotFoundException">Thrown when the partID is not found and throwOnNotFound is given as true.</exception>
        public IStringParamAction CreateServiceAction(string partID, string serviceName, INamedValueSet namedParamValues, bool throwOnNotFound)
        {
            IActivePartBase part = FindPart(partID, throwOnNotFound);

            if (part == null)
            {
                return(null);
            }

            IStringParamAction action = part.CreateServiceAction(serviceName);

            action.NamedParamValues = namedParamValues;

            return(action);
        }