Exemplo n.º 1
0
        public void LogMessage(LogLevel logLevel, string message)
        {
            switch (logLevel)
            {
            case LogLevel.Critical:
                _logger.Fatal(message);
                LogReceived?.Invoke(LogEventLevel.Fatal, _logger, message, _application);
                break;

            case LogLevel.Debug:
                _logger.Debug(message);
                LogReceived?.Invoke(LogEventLevel.Debug, _logger, message, _application);
                break;

            case LogLevel.Information:
                _logger.Information(message);
                LogReceived?.Invoke(LogEventLevel.Information, _logger, message, _application);
                break;

            case LogLevel.Warning:
                _logger.Warning(message);
                LogReceived?.Invoke(LogEventLevel.Warning, _logger, message, _application);
                break;

            case LogLevel.Error:
                _logger.Error(message);
                LogReceived?.Invoke(LogEventLevel.Error, _logger, message, _application);
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null);
            }
        }
Exemplo n.º 2
0
        private static async void ExicuteQueWork(object sender, ElapsedEventArgs e)
        {
            bool didGoCompleteJobb = false;

            try
            {
                didGoCompleteJobb = Ping();
            }
            catch (Exception ex)
            {
                didGoCompleteJobb = true;
                log.Fatal(ex, $"failed - try catch");
            }
            finally
            {
                //Start timer again to trigger jobb
                jobbTimer.Interval = didGoCompleteJobb ? timerSchedule : 10;
                jobbTimer.Start();
            }
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            try
            {
                _logger.Information(string.Format("Starting Application {0} ...", AppName));

                MainActivity main = new MainActivity();
                main.Run();
            }
            catch (Exception ex)
            {
                _logger.Fatal(ex, string.Format("An Error Occurred! Message: {0}", ex.Message));
            }
            finally
            {
                stopwatch.Stop();
                _logger.Information(string.Format("Application {0} completed in {1}", AppName, Utils.ElapsedTime(stopwatch.Elapsed)));
            }
        }
Exemplo n.º 4
0
        /// <summary>
        /// Asynchronous part of the main method of the app.
        /// </summary>
        public async static Task MainAsync(string[] args)
        {
            Logger = new LoggerConfiguration()
                     .WriteTo.Console()
                     .MinimumLevel.Debug()
                     .CreateLogger();

            Logger.Information($"OPC Publisher node configuration tool");

            // command line options
            bool   showHelp = false;
            string iotHubConnectionString    = string.Empty;
            string iotHubPublisherDeviceName = string.Empty;
            string iotHubPublisherModuleName = string.Empty;

            Mono.Options.OptionSet options = new Mono.Options.OptionSet {
                { "h|help", "show this message and exit", h => showHelp = h != null },

                { "ic|iotHubConnectionString=", "IoTHub owner or service connectionstring", (string s) => iotHubConnectionString = s },
                { "id|iothubdevicename=", "IoTHub device name of the OPC Publisher", (string s) => iotHubPublisherDeviceName = s },
                { "im|iothubmodulename=", "IoT Edge module name of the OPC Publisher which runs in the IoT Edge device specified by id/iothubdevicename", (string s) => iotHubPublisherModuleName = s },

                { "pc|purgeconfig", "remove all configured nodes before pushing new ones", b => _purgeConfig = b != null },
                { "bf|backupfile=", $"the filename to store the existing node configuration of OPC Publisher\nDefault: './{_backupFileName}'", (string l) => _backupFileName = l },
                { "nc|nodeconfigfile=", $"the filename of the new node configuration to be set", (string l) => _nodeConfigFileName = l },

                { "lf|logfile=", $"the filename of the logfile to use\nDefault: './{_logFileName}'", (string l) => _logFileName = l },
                { "ll|loglevel=", $"the loglevel to use (allowed: fatal, error, warn, info, debug, verbose).\nDefault: info", (string l) => {
                      List <string> logLevels = new List <string> {
                          "fatal", "error", "warn", "info", "debug", "verbose"
                      };
                      if (logLevels.Contains(l.ToLowerInvariant()))
                      {
                          _logLevel = l.ToLowerInvariant();
                      }
                      else
                      {
                          throw new OptionException("The loglevel must be one of: fatal, error, warn, info, debug, verbose", "loglevel");
                      }
                  } }
            };

            IList <string> extraArgs = null;

            try
            {
                extraArgs = options.Parse(args);
            }
            catch (OptionException e)
            {
                // initialize logging
                InitLogging();

                // show message
                Logger.Fatal(e, "Error in command line options");

                // show usage
                Usage(options, args);
                return;
            }

            // initialize logging
            InitLogging();

            // show usage if requested
            if (showHelp)
            {
                Usage(options);
                return;
            }

            // no extra options
            if (extraArgs.Count > 0)
            {
                for (int i = 1; i < extraArgs.Count; i++)
                {
                    Logger.Error("Error: Unknown option: {0}", extraArgs[i]);
                }
                Usage(options, args);
                return;
            }

            // sanity check parameters
            if (string.IsNullOrEmpty(iotHubConnectionString) || string.IsNullOrEmpty(iotHubPublisherDeviceName))
            {
                Logger.Fatal("For IoTHub communication an IoTHub connection string and the publisher devicename (and modulename) must be specified.");
                return;
            }
            Logger.Information($"IoTHub connectionstring: {iotHubConnectionString}");
            if (string.IsNullOrEmpty(iotHubPublisherModuleName))
            {
                Logger.Information($"OPC Publisher not running in IoT Edge.");
                Logger.Information($"IoTHub OPC Publisher device name: {iotHubPublisherDeviceName}");
            }
            else
            {
                Logger.Information($"OPC Publisher running as IoT Edge module.");
                Logger.Information($"IoT Edge device name: {iotHubPublisherDeviceName}");
                Logger.Information($"OPC Publisher module name: {iotHubPublisherModuleName}");
            }
            CancellationTokenSource cts = new CancellationTokenSource();
            CancellationToken       ct  = cts.Token;

            // read new configuration
            if (!string.IsNullOrEmpty(_nodeConfigFileName))
            {
                try
                {
                    _configurationFileEntries = JsonConvert.DeserializeObject <List <PublisherConfigurationFileEntryLegacyModel> >(File.ReadAllText(_nodeConfigFileName));
                }
                catch (Exception e)
                {
                    Logger.Fatal(e, $"Error reading configuration file. Exiting...");
                    return;
                }
                Logger.Information($"The configuration file '{_nodeConfigFileName}' to be applied contains {_configurationFileEntries.Count} entries.");
            }

            // instantiate OPC Publisher interface
            Publisher publisher = new Publisher(iotHubConnectionString, iotHubPublisherDeviceName, iotHubPublisherModuleName, MAX_SHORT_WAIT_SEC, MAX_LONG_WAIT_SEC, ct);

            // read existing configuration
            List <PublisherConfigurationFileEntryModel> currentConfiguration = new List <PublisherConfigurationFileEntryModel>();
            List <string> configuredEndpoints = publisher.GetConfiguredEndpoints(ct);

            if (configuredEndpoints.Count > 0)
            {
                Logger.Information($"OPC Publisher has the following node configuration:");
            }
            else
            {
                Logger.Information($"OPC Publisher is not publishing any data.");
            }
            foreach (var configuredEndpoint in configuredEndpoints)
            {
                List <NodeModel> configuredNodesOnEndpoint       = publisher.GetConfiguredNodesOnEndpoint(configuredEndpoint, ct);
                PublisherConfigurationFileEntryModel configEntry = new PublisherConfigurationFileEntryModel();
                configEntry.EndpointUrl = new Uri(configuredEndpoint);
                List <OpcNodeOnEndpointModel> nodesOnEndpoint = new List <OpcNodeOnEndpointModel>();
                Logger.Information($"For endpoint '{configuredEndpoint}' there are {configuredNodesOnEndpoint.Count} nodes configured.");
                foreach (var configuredNode in configuredNodesOnEndpoint)
                {
                    Logger.Debug($"Id '{configuredNode.Id}', " +
                                 $"OpcPublishingInterval: {(configuredNode.OpcPublishingInterval == null ? "default" : configuredNode.OpcPublishingInterval.ToString())}, " +
                                 $"OpcSamplingInterval: {(configuredNode.OpcSamplingInterval == null ? "default" : configuredNode.OpcSamplingInterval.ToString())}");
                    OpcNodeOnEndpointModel opcNodeOnEndpoint = new OpcNodeOnEndpointModel();
                    opcNodeOnEndpoint.Id = configuredNode.Id;
                    opcNodeOnEndpoint.OpcSamplingInterval   = configuredNode.OpcSamplingInterval;
                    opcNodeOnEndpoint.OpcPublishingInterval = configuredNode.OpcPublishingInterval;
                    nodesOnEndpoint.Add(opcNodeOnEndpoint);
                }
                configEntry.OpcNodes = nodesOnEndpoint;
                currentConfiguration.Add(configEntry);
            }

            // save it on request
            if (!string.IsNullOrEmpty(_backupFileName) && currentConfiguration.Count > 0)
            {
                await File.WriteAllTextAsync(_backupFileName, JsonConvert.SerializeObject(currentConfiguration, Formatting.Indented));

                Logger.Information($"The existing OPC Publisher node configuration was saved in '{_backupFileName}'");
            }

            // remove existing configuration on request
            if (_purgeConfig)
            {
                publisher.UnpublishAllConfiguredNodes(ct);
                Logger.Information($"The existing node configuration was purged. OPC Publisher should no longer publish any data.");
            }

            // push new configuration, if required
            if (_configurationFileEntries != null)
            {
                var uniqueEndpoints = _configurationFileEntries.Select(e => e.EndpointUrl).Distinct();
                Logger.Information($"The new node configuration will now be set in OPC Publisher.");
                foreach (var uniqueEndpoint in uniqueEndpoints)
                {
                    var endpointConfigurationfileEntries       = _configurationFileEntries.Where(e => e.EndpointUrl == uniqueEndpoint);
                    List <NodeIdInfo> configurationNodeIdInfos = new List <NodeIdInfo>();
                    foreach (var endpointConfigurationFileEntry in endpointConfigurationfileEntries)
                    {
                        foreach (var opcNode in endpointConfigurationFileEntry.OpcNodes)
                        {
                            Logger.Debug($"Id '{opcNode.Id}', " +
                                         $"OpcPublishingInterval: {(opcNode.OpcPublishingInterval == null ? "default" : opcNode.OpcPublishingInterval.ToString())}, " +
                                         $"OpcSamplingInterval: {(opcNode.OpcSamplingInterval == null ? "default" : opcNode.OpcSamplingInterval.ToString())}");
                            NodeIdInfo nodeIdInfo = new NodeIdInfo(opcNode.Id);
                            configurationNodeIdInfos.Add(nodeIdInfo);
                        }
                    }
                    if (!publisher.PublishNodes(configurationNodeIdInfos, ct, uniqueEndpoint.AbsoluteUri))
                    {
                        Logger.Error($"Not able to send the new node configuration to OPC Publisher.");
                    }
                }
            }

            // done
            Logger.Information($"Done. Exiting....");
            return;
        }
Exemplo n.º 5
0
        /// <summary>
        /// Asynchronous part of the main method of the app.
        /// </summary>
        public static async Task MainAsync(string[] args)
        {
            Mono.Options.OptionSet options = InitCommandLineOptions();

            InitAppLocation();

            InitLogging();

            List <string> extraArgs;

            try
            {
                // parse the command line
                extraArgs = options.Parse(args);
            }
            catch (OptionException e)
            {
                // show message
                Logger.Fatal(e, "Error in command line options");
                Logger.Error($"Command line arguments: {string.Join(" ", args)}");
                // show usage
                Usage(options);
                return;
            }

            // show usage if requested
            if (ShowHelp)
            {
                Usage(options);
                return;
            }

            // validate and parse extra arguments
            if (extraArgs.Count > 0)
            {
                Logger.Error("Error in command line options");
                Logger.Error($"Command line arguments: {string.Join(" ", args)}");
                Usage(options);
                return;
            }

            //show version
            var fileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);

            Logger.Information($"{ProgramName} V{fileVersion.ProductMajorPart}.{fileVersion.ProductMinorPart}.{fileVersion.ProductBuildPart} starting up...");
            Logger.Debug($"Informational version: V{(Attribute.GetCustomAttribute(Assembly.GetEntryAssembly(), typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute)?.InformationalVersion}");

            using var host = CreateHostBuilder(args);
            if (ShowPublisherConfigJsonIp || ShowPublisherConfigJsonPh)
            {
                StartWebServer(host);
            }

            try
            {
                await ConsoleServerAsync(args).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex, "OPC UA server failed unexpectedly.");
            }

            Logger.Information("OPC UA server exiting...");
        }
        /// <summary>
        /// Asynchronous part of the main method of the app.
        /// </summary>
        public async static Task MainAsync(string[] args)
        {
            var shouldShowHelp = false;

            // command line options
            Mono.Options.OptionSet options = new Mono.Options.OptionSet {
                // opc server configuration options
                { "lf|logfile=", $"the filename of the logfile to use.\nDefault: '{_logFileName}'", (string l) => _logFileName = l },
                { "ll|loglevel=", "the loglevel to use (allowed: fatal, error, warn, info, debug, verbose).\nDefault: info", (string l) => {
                      List <string> logLevels = new List <string> {
                          "fatal", "error", "warn", "info", "debug", "verbose"
                      };
                      if (logLevels.Contains(l.ToLowerInvariant()))
                      {
                          _logLevel = l.ToLowerInvariant();
                      }
                      else
                      {
                          throw new OptionException("The loglevel must be one of: fatal, error, warn, info, debug, verbose", "loglevel");
                      }
                  } },
                { "pn|portnum=", $"the server port of the OPC server endpoint.\nDefault: {ServerPort}", (ushort p) => ServerPort = p },
                { "op|path=", $"the enpoint URL path part of the OPC server endpoint.\nDefault: '{ServerPath}'", (string a) => ServerPath = a },
                { "ga|generatealerts", $"the station should generate alerts.\nDefault: {GenerateAlerts}", g => GenerateAlerts = g != null },
                { "pc|powerconsumption=", $"the stations average power consumption in kW\nDefault:  {PowerConsumption} kW", (double d) => PowerConsumption = d },
                { "ct|cycletime=", $"the stations cycle time in seconds\nDefault:  {IdealCycleTimeDefault} sec", (ulong ul) => IdealCycleTimeDefault = ul * 1000 },
                { "lr|ldsreginterval=", $"the LDS(-ME) registration interval in ms. If 0, then the registration is disabled.\nDefault: {LdsRegistrationInterval}", (int i) => {
                      if (i >= 0)
                      {
                          LdsRegistrationInterval = i;
                      }
                      else
                      {
                          throw new OptionException("The ldsreginterval must be larger or equal 0.", "ldsreginterval");
                      }
                  } },
                { "aa|autoacceptcerts", $"all certs are trusted when a connection is established.\nDefault: {AutoAcceptCerts}", a => AutoAcceptCerts = a != null },

                { "to|trustowncert", $"the cfstation certificate is put into the trusted certificate store automatically.\nDefault: {TrustMyself}", t => TrustMyself = t != null },

                // cert store options
                { "at|appcertstoretype=", $"the own application cert store type. \n(allowed values: Directory, X509Store)\nDefault: '{OpcOwnCertStoreType}'", (string s) => {
                      if (s.Equals(X509Store, StringComparison.OrdinalIgnoreCase) || s.Equals(CertificateStoreType.Directory, StringComparison.OrdinalIgnoreCase))
                      {
                          OpcOwnCertStoreType = s.Equals(X509Store, StringComparison.OrdinalIgnoreCase) ? X509Store : CertificateStoreType.Directory;
                          OpcOwnCertStorePath = s.Equals(X509Store, StringComparison.OrdinalIgnoreCase) ? OpcOwnCertX509StorePathDefault : OpcOwnCertDirectoryStorePathDefault;
                      }
                      else
                      {
                          throw new OptionException();
                      }
                  } },
                { "ap|appcertstorepath=", "the path where the own application cert should be stored\nDefault (depends on store type):\n" +
                  $"X509Store: '{OpcOwnCertX509StorePathDefault}'\n" +
                  $"Directory: '{OpcOwnCertDirectoryStorePathDefault}'", (string s) => OpcOwnCertStorePath = s },

                { "tp|trustedcertstorepath=", $"the path of the trusted cert store\nDefault: '{OpcTrustedCertDirectoryStorePathDefault}'", (string s) => OpcTrustedCertStorePath = s },

                { "rp|rejectedcertstorepath=", $"the path of the rejected cert store\nDefault '{OpcRejectedCertDirectoryStorePathDefault}'", (string s) => OpcRejectedCertStorePath = s },

                { "ip|issuercertstorepath=", $"the path of the trusted issuer cert store\nDefault '{OpcIssuerCertDirectoryStorePathDefault}'", (string s) => OpcIssuerCertStorePath = s },

                { "csr", $"show data to create a certificate signing request\nDefault '{ShowCreateSigningRequestInfo}'", c => ShowCreateSigningRequestInfo = c != null },

                { "ab|applicationcertbase64=", "update/set this applications certificate with the certificate passed in as bas64 string", (string s) => NewCertificateBase64String = s },
                { "af|applicationcertfile=", "update/set this applications certificate with the certificate file specified", (string s) =>
                  {
                      if (File.Exists(s))
                      {
                          NewCertificateFileName = s;
                      }
                      else
                      {
                          throw new OptionException("The file '{s}' does not exist.", "applicationcertfile");
                      }
                  } },

                { "pb|privatekeybase64=", "initial provisioning of the application certificate (with a PEM or PFX fomat) requires a private key passed in as base64 string", (string s) => PrivateKeyBase64String = s },
                { "pk|privatekeyfile=", "initial provisioning of the application certificate (with a PEM or PFX fomat) requires a private key passed in as file", (string s) =>
                  {
                      if (File.Exists(s))
                      {
                          PrivateKeyFileName = s;
                      }
                      else
                      {
                          throw new OptionException("The file '{s}' does not exist.", "privatekeyfile");
                      }
                  } },

                { "cp|certpassword="******"the optional password for the PEM or PFX or the installed application certificate", (string s) => CertificatePassword = s },

                { "tb|addtrustedcertbase64=", "adds the certificate to the applications trusted cert store passed in as base64 string (multiple strings supported)", (string s) => TrustedCertificateBase64Strings.AddRange(ParseListOfStrings(s)) },
                { "tf|addtrustedcertfile=", "adds the certificate file(s) to the applications trusted cert store passed in as base64 string (multiple filenames supported)", (string s) => TrustedCertificateFileNames.AddRange(ParseListOfFileNames(s, "addtrustedcertfile")) },

                { "ib|addissuercertbase64=", "adds the specified issuer certificate to the applications trusted issuer cert store passed in as base64 string (multiple strings supported)", (string s) => IssuerCertificateBase64Strings.AddRange(ParseListOfStrings(s)) },
                { "if|addissuercertfile=", "adds the specified issuer certificate file(s) to the applications trusted issuer cert store (multiple filenames supported)", (string s) => IssuerCertificateFileNames.AddRange(ParseListOfFileNames(s, "addissuercertfile")) },

                { "rb|updatecrlbase64=", "update the CRL passed in as base64 string to the corresponding cert store (trusted or trusted issuer)", (string s) => CrlBase64String = s },
                { "uc|updatecrlfile=", "update the CRL passed in as file to the corresponding cert store (trusted or trusted issuer)", (string s) =>
                  {
                      if (File.Exists(s))
                      {
                          CrlFileName = s;
                      }
                      else
                      {
                          throw new OptionException("The file '{s}' does not exist.", "updatecrlfile");
                      }
                  } },

                { "rc|removecert=", "remove cert(s) with the given thumbprint(s) (multiple thumbprints supported)", (string s) => ThumbprintsToRemove.AddRange(ParseListOfStrings(s)) },

                // misc
                { "h|help", "show this message and exit", h => shouldShowHelp = h != null },
            };

            List <string> extraArgs = new List <string>();

            try
            {
                // parse the command line
                extraArgs = options.Parse(args);
            }
            catch (OptionException e)
            {
                // initialize logging
                InitLogging();

                // show message
                Logger.Fatal(e, "Error in command line options");
                // show usage
                Usage(options);
                return;
            }

            // initialize logging
            InitLogging();

            // check args
            if (extraArgs.Count != 0 || shouldShowHelp)
            {
                // show usage
                Usage(options);
                return;
            }

            try
            {
                await ConsoleServerAsync().ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex, "OPC UA server failed unexpectedly.");
            }
            Logger.Information("OPC UA server exiting...");
        }
Exemplo n.º 7
0
 public void Exception(Exception exception)
 {
     log.Fatal(exception,
               $"DEADBEAF: an exception was thrown. Current WindowsIdentity: {Environment.UserName}");
 }
 public static void Fatal(string message)
 {
     _logger.Fatal(message);
 }
Exemplo n.º 9
0
 /// <inheritdoc />
 public void Fatal(string messageTemplate)
 {
     _log.Fatal(messageTemplate);
 }
Exemplo n.º 10
0
        /// <summary>
        /// Asynchronous part of the main method of the app.
        /// </summary>
        public static async Task MainAsync(string[] args)
        {
            bool shouldShowHelp = false;

            // command line options
            var options = new Mono.Options.OptionSet {
                // log configuration
                { "lf|logfile=", $"the filename of the logfile to use.\nDefault: './{_logFileName}'", (string l) => _logFileName = l },
                { "lt|logflushtimespan=", $"the timespan in seconds when the logfile should be flushed.\nDefault: {_logFileFlushTimeSpanSec} sec", (int s) => {
                      if (s > 0)
                      {
                          _logFileFlushTimeSpanSec = TimeSpan.FromSeconds(s);
                      }
                      else
                      {
                          throw new OptionException("The logflushtimespan must be a positive number.", "logflushtimespan");
                      }
                  } },
                { "ll|loglevel=", "the loglevel to use (allowed: fatal, error, warn, info, debug, verbose).\nDefault: info", (string l) => {
                      var logLevels = new List <string> {
                          "fatal", "error", "warn", "info", "debug", "verbose"
                      };
                      if (logLevels.Contains(l.ToLowerInvariant()))
                      {
                          _logLevel = l.ToLowerInvariant();
                      }
                      else
                      {
                          throw new OptionException("The loglevel must be one of: fatal, error, warn, info, debug, verbose", "loglevel");
                      }
                  } },

                // simulation configuration
                { "sc|simulationcyclecount=", $"count of cycles in one simulation phase\nDefault:  {SimulationCycleCount} cycles", (int i) => SimulationCycleCount = i },
                { "ct|cycletime=", $"length of one cycle time in milliseconds\nDefault:  {SimulationCycleLength} msec", (int i) => SimulationCycleLength = i },
                { "ns|nospikes", $"do not generate spike data\nDefault: {!GenerateSpikes}", a => GenerateSpikes = a == null },
                { "nd|nodips", $"do not generate dip data\nDefault: {!GenerateDips}", a => GenerateDips = a == null },
                { "np|nopostrend", $"do not generate positive trend data\nDefault: {!GeneratePosTrend}", a => GeneratePosTrend = a == null },
                { "nn|nonegtrend", $"do not generate negative trend data\nDefault: {!GenerateNegTrend}", a => GenerateNegTrend = a == null },
                { "nv|nodatavalues", $"do not generate data values\nDefault: {!GenerateData}", a => GenerateData = a == null },

                // Slow and fast nodes.
                { "sn|slownodes=", $"number of slow nodes\nDefault: {SlowNodeCount}", (uint i) => SlowNodeCount = i },
                { "sr|slowrate=", $"rate in seconds to change slow nodes\nDefault: {SlowNodeRate}", (uint i) => SlowNodeRate = i },
                { "st|slowtype=", $"data type of slow nodes ({string.Join("|", Enum.GetNames(typeof(NodeType)))})\nDefault: {SlowNodeType}", a => SlowNodeType = ParseNodeType(a) },
                { "ssi|slownodesamplinginterval=", $"rate in milliseconds to sample slow nodes\nDefault: {SlowNodeSamplingInterval}", (uint i) => SlowNodeSamplingInterval = i },
                { "fn|fastnodes=", $"number of fast nodes\nDefault: {FastNodeCount}", (uint i) => FastNodeCount = i },
                { "fr|fastrate=", $"rate in seconds to change fast nodes\nDefault: {FastNodeRate}", (uint i) => FastNodeRate = i },
                { "ft|fasttype=", $"data type of fast nodes ({string.Join("|", Enum.GetNames(typeof(NodeType)))})\nDefault: {FastNodeType}", a => FastNodeType = ParseNodeType(a) },
                { "fsi|fastnodesamplinginterval=", $"rate in milliseconds to sample fast nodes\nDefault: {FastNodeSamplingInterval}", (uint i) => FastNodeSamplingInterval = i },

                // user defined nodes configuration
                { "nf|nodesfile=", "the filename which contains the list of nodes to be created in the OPC UA address space.", (string l) => NodesFileName = l },

                // opc configuration
                { "pn|portnum=", $"the server port of the OPC server endpoint.\nDefault: {ServerPort}", (ushort p) => ServerPort = p },
                { "op|path=", $"the enpoint URL path part of the OPC server endpoint.\nDefault: '{ServerPath}'", (string a) => ServerPath = a },
                { "ph|plchostname=", $"the fullqualified hostname of the plc.\nDefault: {Hostname}", (string a) => Hostname = a },
                { "ol|opcmaxstringlen=", $"the max length of a string opc can transmit/receive.\nDefault: {OpcMaxStringLength}", (int i) => {
                      if (i > 0)
                      {
                          OpcMaxStringLength = i;
                      }
                      else
                      {
                          throw new OptionException("The max opc string length must be larger than 0.", "opcmaxstringlen");
                      }
                  } },
                { "lr|ldsreginterval=", $"the LDS(-ME) registration interval in ms. If 0, then the registration is disabled.\nDefault: {LdsRegistrationInterval}", (int i) => {
                      if (i >= 0)
                      {
                          LdsRegistrationInterval = i;
                      }
                      else
                      {
                          throw new OptionException("The ldsreginterval must be larger or equal 0.", "ldsreginterval");
                      }
                  } },
                { "aa|autoaccept", $"all certs are trusted when a connection is established.\nDefault: {AutoAcceptCerts}", a => AutoAcceptCerts = a != null },

                { "ut|unsecuretransport", $"enables the unsecured transport.\nDefault: {EnableUnsecureTransport}", u => EnableUnsecureTransport = u != null },

                { "to|trustowncert", $"the own certificate is put into the trusted certificate store automatically.\nDefault: {TrustMyself}", t => TrustMyself = t != null },

                // cert store options
                { "at|appcertstoretype=", $"the own application cert store type. \n(allowed values: Directory, X509Store)\nDefault: '{OpcOwnCertStoreType}'", (string s) => {
                      if (s.Equals(CertificateStoreType.X509Store, StringComparison.OrdinalIgnoreCase) || s.Equals(CertificateStoreType.Directory, StringComparison.OrdinalIgnoreCase))
                      {
                          OpcOwnCertStoreType = s.Equals(CertificateStoreType.X509Store, StringComparison.OrdinalIgnoreCase) ? CertificateStoreType.X509Store : CertificateStoreType.Directory;
                          OpcOwnCertStorePath = s.Equals(CertificateStoreType.X509Store, StringComparison.OrdinalIgnoreCase) ? OpcOwnCertX509StorePathDefault : OpcOwnCertDirectoryStorePathDefault;
                      }
                      else
                      {
                          throw new OptionException();
                      }
                  } },

                { "ap|appcertstorepath=", "the path where the own application cert should be stored\nDefault (depends on store type):\n" +
                  $"X509Store: '{OpcOwnCertX509StorePathDefault}'\n" +
                  $"Directory: '{OpcOwnCertDirectoryStorePathDefault}'", (string s) => OpcOwnCertStorePath = s },

                { "tp|trustedcertstorepath=", $"the path of the trusted cert store\nDefault '{OpcTrustedCertDirectoryStorePathDefault}'", (string s) => OpcTrustedCertStorePath = s },

                { "rp|rejectedcertstorepath=", $"the path of the rejected cert store\nDefault '{OpcRejectedCertDirectoryStorePathDefault}'", (string s) => OpcRejectedCertStorePath = s },

                { "ip|issuercertstorepath=", $"the path of the trusted issuer cert store\nDefault '{OpcIssuerCertDirectoryStorePathDefault}'", (string s) => OpcIssuerCertStorePath = s },

                { "csr", $"show data to create a certificate signing request\nDefault '{ShowCreateSigningRequestInfo}'", c => ShowCreateSigningRequestInfo = c != null },

                { "ab|applicationcertbase64=", "update/set this applications certificate with the certificate passed in as bas64 string", (string s) => NewCertificateBase64String = s },
                { "af|applicationcertfile=", "update/set this applications certificate with the certificate file specified", (string s) =>
                  {
                      if (File.Exists(s))
                      {
                          NewCertificateFileName = s;
                      }
                      else
                      {
                          throw new OptionException("The file '{s}' does not exist.", "applicationcertfile");
                      }
                  } },

                { "pb|privatekeybase64=", "initial provisioning of the application certificate (with a PEM or PFX fomat) requires a private key passed in as base64 string", (string s) => PrivateKeyBase64String = s },
                { "pk|privatekeyfile=", "initial provisioning of the application certificate (with a PEM or PFX fomat) requires a private key passed in as file", (string s) =>
                  {
                      if (File.Exists(s))
                      {
                          PrivateKeyFileName = s;
                      }
                      else
                      {
                          throw new OptionException("The file '{s}' does not exist.", "privatekeyfile");
                      }
                  } },

                { "cp|certpassword="******"the optional password for the PEM or PFX or the installed application certificate", (string s) => CertificatePassword = s },

                { "tb|addtrustedcertbase64=", "adds the certificate to the applications trusted cert store passed in as base64 string (multiple strings supported)", (string s) => TrustedCertificateBase64Strings = ParseListOfStrings(s) },
                { "tf|addtrustedcertfile=", "adds the certificate file(s) to the applications trusted cert store passed in as base64 string (multiple filenames supported)", (string s) => TrustedCertificateFileNames = ParseListOfFileNames(s, "addtrustedcertfile") },

                { "ib|addissuercertbase64=", "adds the specified issuer certificate to the applications trusted issuer cert store passed in as base64 string (multiple strings supported)", (string s) => IssuerCertificateBase64Strings = ParseListOfStrings(s) },
                { "if|addissuercertfile=", "adds the specified issuer certificate file(s) to the applications trusted issuer cert store (multiple filenames supported)", (string s) => IssuerCertificateFileNames = ParseListOfFileNames(s, "addissuercertfile") },

                { "rb|updatecrlbase64=", "update the CRL passed in as base64 string to the corresponding cert store (trusted or trusted issuer)", (string s) => CrlBase64String = s },
                { "uc|updatecrlfile=", "update the CRL passed in as file to the corresponding cert store (trusted or trusted issuer)", (string s) =>
                  {
                      if (File.Exists(s))
                      {
                          CrlFileName = s;
                      }
                      else
                      {
                          throw new OptionException("The file '{s}' does not exist.", "updatecrlfile");
                      }
                  } },

                { "rc|removecert=", "remove cert(s) with the given thumbprint(s) (multiple thumbprints supported)", (string s) => ThumbprintsToRemove = ParseListOfStrings(s) },

                { "daa|disableanonymousauth", $"flag to disable anonymous authentication. \nDefault: {DisableAnonymousAuth}", d => DisableAnonymousAuth = d != null },
                { "dua|disableusernamepasswordauth", $"flag to disable username/password authentication. \nDefault: {DisableUsernamePasswordAuth}", d => DisableUsernamePasswordAuth = d != null },
                { "dca|disablecertauth", $"flag to disable certificate authentication. \nDefault: {DisableCertAuth}", d => DisableCertAuth = d != null },

                // user management
                { "au|adminuser="******"the username of the admin user.\nDefault: {AdminUser}", (string p) => AdminUser = p ?? AdminUser },
                { "ac|adminpassword="******"the password of the administrator.\nDefault: {AdminPassword}", (string p) => AdminPassword = p ?? AdminPassword },
                { "du|defaultuser="******"the username of the default user.\nDefault: {DefaultUser}", (string p) => DefaultUser = p ?? DefaultUser },
                { "dc|defaultpassword="******"the password of the default user.\nDefault: {DefaultPassword}", (string p) => DefaultPassword = p ?? DefaultPassword },

                // misc
                { "sp|showpnjson", $"show OPC Publisher configuration file using IP address as EndpointUrl.\nDefault: {ShowPublisherConfigJsonIp}", h => ShowPublisherConfigJsonIp = h != null },
                { "sph|showpnjsonph", $"show OPC Publisher configuration file using plchostname as EndpointUrl.\nDefault: {ShowPublisherConfigJsonPh}", h => ShowPublisherConfigJsonPh = h != null },
                { "spf|showpnfname=", $"filename of the OPC Publisher configuration file to write when using options sp/sph.\nDefault: {PnJson}", (string f) => PnJson = f },
                { "ctb|complextypeboiler", $"add complex type (boiler) to address space.\nDefault: {AddComplexTypeBoiler}", h => AddComplexTypeBoiler = h != null },
                { "wp|webport=", $"web server port for hosting OPC Publisher configuration file.\nDefault: {WebServerPort}", (uint i) => WebServerPort = i },
                { "h|help", "show this message and exit", h => shouldShowHelp = h != null },
            };

            // Init app location
            InitAppFolder();

            // Init logging
            InitLogging();

            var extraArgs = new List <string>();

            try
            {
                // parse the command line
                extraArgs = options.Parse(args);
            }
            catch (OptionException e)
            {
                // show message
                Logger.Fatal(e, "Error in command line options");
                Logger.Error($"Command line arguments: {string.Join(" ", args)}");
                // show usage
                Usage(options);
                return;
            }

            // show usage if requested
            if (shouldShowHelp)
            {
                Usage(options);
                return;
            }

            // validate and parse extra arguments
            if (extraArgs.Count > 0)
            {
                Logger.Error("Error in command line options");
                Logger.Error($"Command line arguments: {string.Join(" ", args)}");
                Usage(options);
                return;
            }

            //show version
            var fileVersion = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location);

            Logger.Information($"{ProgramName} V{fileVersion.ProductMajorPart}.{fileVersion.ProductMinorPart}.{fileVersion.ProductBuildPart} starting up...");
            Logger.Debug($"Informational version: V{(Attribute.GetCustomAttribute(Assembly.GetEntryAssembly(), typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute)?.InformationalVersion}");

            using var host = CreateHostBuilder(args);
            if (ShowPublisherConfigJsonIp || ShowPublisherConfigJsonPh)
            {
                StartWebServer(host);
            }

            try
            {
                await ConsoleServerAsync(args).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex, "OPC UA server failed unexpectedly.");
            }
            Logger.Information("OPC UA server exiting...");
        }
Exemplo n.º 11
0
 public void Fatal(string message, params object[] propertyValues)
 {
     Log.Fatal(message, propertyValues);
 }
Exemplo n.º 12
0
 public void Fatal()
 {
     internalLogger.Fatal(string.Empty);
 }
        /// <summary>
        /// Asynchronous part of the main method of the app.
        /// </summary>
        public async static Task MainAsync(string[] args)
        {
            var shouldShowHelp = false;

            // command line options
            Mono.Options.OptionSet options = new Mono.Options.OptionSet {
                // opc server configuration options
                { "lf|logfile=", $"the filename of the logfile to use.\nDefault: '{_logFileName}'", (string l) => _logFileName = l },
                { "ll|loglevel=", $"the loglevel to use (allowed: fatal, error, warn, info, debug, verbose).\nDefault: info", (string l) => {
                      List <string> logLevels = new List <string> {
                          "fatal", "error", "warn", "info", "debug", "verbose"
                      };
                      if (logLevels.Contains(l.ToLowerInvariant()))
                      {
                          _logLevel = l.ToLowerInvariant();
                      }
                      else
                      {
                          throw new OptionException("The loglevel must be one of: fatal, error, warn, info, debug, verbose", "loglevel");
                      }
                  } },
                { "pn|portnum=", $"the server port of the OPC server endpoint.\nDefault: {ServerPort}", (ushort p) => ServerPort = p },
                { "op|path=", $"the enpoint URL path part of the OPC server endpoint.\nDefault: '{ServerPath}'", (string a) => ServerPath = a },
                { "sh|stationhostname=", $"the fullqualified hostname of the station.\nDefault: {StationHostname}", (string a) => StationHostname = a },
                { "ga|generatealerts", $"the station should generate alerts.\nDefault: {GenerateAlerts}", g => GenerateAlerts = g != null },
                { "pc|powerconsumption=", $"the stations average power consumption in kW\nDefault:  {PowerConsumption} kW", (double d) => PowerConsumption = d },
                { "ct|cycletime=", $"the stations cycle time in seconds\nDefault:  {IdealCycleTimeDefault} sec", (ulong ul) => IdealCycleTimeDefault = ul * 1000 },
                { "lr|ldsreginterval=", $"the LDS(-ME) registration interval in ms. If 0, then the registration is disabled.\nDefault: {LdsRegistrationInterval}", (int i) => {
                      if (i >= 0)
                      {
                          LdsRegistrationInterval = i;
                      }
                      else
                      {
                          throw new OptionException("The ldsreginterval must be larger or equal 0.", "ldsreginterval");
                      }
                  } },
                { "aa|autoacceptcerts", $"all certs are trusted when a connection is established.\nDefault: {AutoAcceptCerts}", a => AutoAcceptCerts = a != null },

                { "to|trustowncert", $"the cfstation certificate is put into the trusted certificate store automatically.\nDefault: {TrustMyself}", t => TrustMyself = t != null },

                { "ap|appcertstorepath=", $"the path where the own application cert should be stored\nDefault '{OpcOwnCertX509StorePathDefault}'", (string s) => OpcOwnCertStorePath = s },

                { "tp|trustedcertstorepath=", $"the path of the trusted cert store\nDefault '{OpcTrustedCertDirectoryStorePathDefault}'", (string s) => OpcTrustedCertStorePath = s },

                { "rp|rejectedcertstorepath=", $"the path of the rejected cert store\nDefault '{OpcRejectedCertDirectoryStorePathDefault}'", (string s) => OpcRejectedCertStorePath = s },

                { "ip|issuercertstorepath=", $"the path of the trusted issuer cert store\nDefault '{OpcIssuerCertDirectoryStorePathDefault}'", (string s) => OpcIssuerCertStorePath = s },

                // misc
                { "h|help", "show this message and exit", h => shouldShowHelp = h != null },
            };

            List <string> extraArgs = new List <string>();

            try
            {
                // parse the command line
                extraArgs = options.Parse(args);
            }
            catch (OptionException e)
            {
                // initialize logging
                InitLogging();

                // show message
                Logger.Fatal(e, "Error in command line options");
                // show usage
                Usage(options);
                return;
            }

            // initialize logging
            InitLogging();

            // check args
            if (extraArgs.Count != 0 || shouldShowHelp)
            {
                // show usage
                Usage(options);
                return;
            }

            try
            {
                await ConsoleServerAsync(args);
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex, "OPC UA server failed unexpectedly.");
            }
            Logger.Information("OPC UA server exiting...");
        }
Exemplo n.º 14
0
 public void Fatal(LogModel logModel)
 {
     _serilogLogger.Fatal(JsonConvert.SerializeObject(logModel));
 }
Exemplo n.º 15
0
        static void Main(string[] args)
        {
            int nsecs = 1000;

            try
            {
                var configuration = new ConfigurationBuilder()
                                    .SetBasePath(Directory.GetCurrentDirectory())
                                    .AddJsonFile("appsettings.json")
                                    .Build();
                config = configuration;

                //var configuration = builder.Build();
                // config = new ConfigurationBuilder()
                //     .AddJsonFile("appsettings.json", true, true)
                //     .Build();
//Serilog.Debugging.SelfLog.Enable(msg => Debug.WriteLine(msg));
//Serilog.Debugging.SelfLog.Enable(Console.Error);

// File logger

/*
 *          var Log = new LoggerConfiguration()
 *              //.MinimumLevel.Information()
 *              //.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
 *              .Enrich.FromLogContext()
 *              //.WriteTo.Console()
 *              //.WriteTo.RollingFile("log-{Date}.txt") //, fileSizeLimitBytes: 123)
 *              .ReadFrom.Configuration(configuration)
 *              //.ReadFrom.Configuration(config)
 *              //.Enrich.FromLogContext()
 *              .CreateLogger();
 */
/*
 *         var Log = new LoggerConfiguration()
 *         .WriteTo.SumoLogic("https://endpoint4.collection.us2.sumologic.com/receiver/v1/http/ZaVnC4dhaV1OJMaHi0tURR0qnAZ2G4CmmLdC4MdjYUbmtlFDnp5jAd9h4z0AbkVsIYNHswsCLX87SsDb9hZsW_aY6umdGIQOjPoNMeoUflRQlGL4q6LYVQ==")
 *             //.WriteTo.SumoLogic("http://localhost", textFormatter: new MessageTemplateTextFormatter("FOOBAR", null))
 *             .WriteTo.MongoDBCapped()
 *             .CreateLogger();
 */
                // From appsettings.json

                Log = new LoggerConfiguration()
                      .ReadFrom.Configuration(configuration)
                      .CreateLogger();

                /**
                 * var Log = new LoggerConfiguration()
                 * //.WriteTo.MongoDB("mongodb://mymongodb/logs")
                 * .WriteTo.MongoDB("mongodb://localhost:27017/logs")
                 * //.WriteTo.MongoDBCapped("mongodb://localhost:27017/logs", cappedMaxSizeMb: 50, cappedMaxDocuments: 7)
                 * .MinimumLevel.Verbose()
                 * //.MinimumLevel.Fatal()
                 * .CreateLogger();
                 **/

                //Console.WriteLine("The current time is " + DateTime.Now);
                showVitals();

                listStudents();
                ListCollectionAsync().Wait();

                //Console.ReadLine();
                Log.Verbose("VVVVVVVV Verbose");

                Console.WriteLine($"'waiting {nsecs} milli secs."); Task.Delay(nsecs).Wait(); // Wait 2 seconds with blocking
                Log.Debug("DDDDDDDD Debug");
                Console.WriteLine($"'waiting {nsecs} milli secs."); Task.Delay(nsecs).Wait(); // Wait 2 seconds with blocking
                Log.Information("IIIIIIII Information");
                Console.WriteLine($"'waiting {nsecs} milli secs."); Task.Delay(nsecs).Wait(); // Wait 2 seconds with blocking
                Log.Warning("WWWWWWWW Warning");
                Log.Fatal("FFFFFFFF Fatal terminated unexpectedly");
                Log.Error("EEEEEEEE Error");
                Log.Verbose("VVVVVVVV Error");


                Log.Information("Host IIIIIIIIIIII");
                nsecs = 6000;
                Console.WriteLine($"'waiting {nsecs} milli secs. The end is near."); Task.Delay(nsecs).Wait(); // Wait 2 seconds with blocking
            }
            catch (Exception ex)
            {
                Console.WriteLine($"\n\n catch catch\n{ex}");
                if (Log != null)
                {
                    Log.Fatal($"catch catch\n {ex}");
                }
                //return;
            }
            finally
            {
                if (Log != null)
                {
                    Log.Information("Fulsh");
                }
                //Log.Information("Fulsh");
                //Log.CloseAndFlush();
            }

            Console.WriteLine($"'waiting {nsecs} milli secs. The end is near."); Task.Delay(nsecs).Wait(); // Wait 2 seconds with blocking
        }
Exemplo n.º 16
0
        /// <summary>
        /// Asynchronous part of the main method of the app.
        /// </summary>
        public async static Task MainAsync(string[] args)
        {
            var shouldShowHelp = false;

            // command line options
            Mono.Options.OptionSet options = new Mono.Options.OptionSet {
                // log configuration
                { "lf|logfile=", $"the filename of the logfile to use.\nDefault: './{_logFileName}'", (string l) => _logFileName = l },
                { "lt|logflushtimespan=", $"the timespan in seconds when the logfile should be flushed.\nDefault: {_logFileFlushTimeSpanSec} sec", (int s) => {
                      if (s > 0)
                      {
                          _logFileFlushTimeSpanSec = TimeSpan.FromSeconds(s);
                      }
                      else
                      {
                          throw new Mono.Options.OptionException("The logflushtimespan must be a positive number.", "logflushtimespan");
                      }
                  } },
                { "ll|loglevel=", $"the loglevel to use (allowed: fatal, error, warn, info, debug, verbose).\nDefault: info", (string l) => {
                      List <string> logLevels = new List <string> {
                          "fatal", "error", "warn", "info", "debug", "verbose"
                      };
                      if (logLevels.Contains(l.ToLowerInvariant()))
                      {
                          _logLevel = l.ToLowerInvariant();
                      }
                      else
                      {
                          throw new OptionException("The loglevel must be one of: fatal, error, warn, info, debug, verbose", "loglevel");
                      }
                  } },

                // simulation configuration
                { "sc|simulationcyclecount=", $"count of cycles in one simulation phase\nDefault:  {SimulationCycleCount} cycles", (int i) => SimulationCycleCount = i },
                { "ct|cycletime=", $"length of one cycle time in milliseconds\nDefault:  {SimulationCycleLength} msec", (int i) => SimulationCycleLength = i },
                { "ns|nospikes", $"do not generate spike data\nDefault: {!GenerateSpikes}", a => GenerateSpikes = a == null },
                { "nd|nodips", $"do not generate dip data\nDefault: {!GenerateDips}", a => GenerateDips = a == null },
                { "np|nopostrend", $"do not generate positive trend data\nDefault: {!GeneratePosTrend}", a => GeneratePosTrend = a == null },
                { "nn|nonegtrend", $"do not generate negative trend data\nDefault: {!GenerateNegTrend}", a => GenerateNegTrend = a == null },
                { "nv|nodatavalues", $"do not generate data values\nDefault: {!GenerateData}", a => GenerateData = a == null },

                // opc configuration
                { "pn|portnum=", $"the server port of the OPC server endpoint.\nDefault: {ServerPort}", (ushort p) => ServerPort = p },
                { "op|path=", $"the enpoint URL path part of the OPC server endpoint.\nDefault: '{ServerPath}'", (string a) => ServerPath = a },
                { "ph|plchostname=", $"the fullqualified hostname of the plc.\nDefault: {Hostname}", (string a) => Hostname = a },
                { "ol|opcmaxstringlen=", $"the max length of a string opc can transmit/receive.\nDefault: {OpcMaxStringLength}", (int i) => {
                      if (i > 0)
                      {
                          OpcMaxStringLength = i;
                      }
                      else
                      {
                          throw new OptionException("The max opc string length must be larger than 0.", "opcmaxstringlen");
                      }
                  } },
                { "lr|ldsreginterval=", $"the LDS(-ME) registration interval in ms. If 0, then the registration is disabled.\nDefault: {LdsRegistrationInterval}", (int i) => {
                      if (i >= 0)
                      {
                          LdsRegistrationInterval = i;
                      }
                      else
                      {
                          throw new OptionException("The ldsreginterval must be larger or equal 0.", "ldsreginterval");
                      }
                  } },
                { "aa|autoaccept", $"all certs are trusted when a connection is established.\nDefault: {AutoAcceptCerts}", a => AutoAcceptCerts = a != null },

                { "ut|unsecuretransport", $"enables the unsecured transport.\nDefault: {EnableUnsecureTransport}", u => EnableUnsecureTransport = u != null },

                { "to|trustowncert", $"the own certificate is put into the trusted certificate store automatically.\nDefault: {TrustMyself}", t => TrustMyself = t != null },

                // cert store options
                { "at|appcertstoretype=", $"the own application cert store type. \n(allowed values: Directory, X509Store)\nDefault: '{OpcOwnCertStoreType}'", (string s) => {
                      if (s.Equals(CertificateStoreType.X509Store, StringComparison.OrdinalIgnoreCase) || s.Equals(CertificateStoreType.Directory, StringComparison.OrdinalIgnoreCase))
                      {
                          OpcOwnCertStoreType = s.Equals(CertificateStoreType.X509Store, StringComparison.OrdinalIgnoreCase) ? CertificateStoreType.X509Store : CertificateStoreType.Directory;
                          OpcOwnCertStorePath = s.Equals(CertificateStoreType.X509Store, StringComparison.OrdinalIgnoreCase) ? OpcOwnCertX509StorePathDefault : OpcOwnCertDirectoryStorePathDefault;
                      }
                      else
                      {
                          throw new OptionException();
                      }
                  } },

                { "ap|appcertstorepath=", $"the path where the own application cert should be stored\nDefault (depends on store type):\n" +
                  $"X509Store: '{OpcOwnCertX509StorePathDefault}'\n" +
                  $"Directory: '{OpcOwnCertDirectoryStorePathDefault}'", (string s) => OpcOwnCertStorePath = s },

                { "tp|trustedcertstorepath=", $"the path of the trusted cert store\nDefault '{OpcTrustedCertDirectoryStorePathDefault}'", (string s) => OpcTrustedCertStorePath = s },

                { "rp|rejectedcertstorepath=", $"the path of the rejected cert store\nDefault '{OpcRejectedCertDirectoryStorePathDefault}'", (string s) => OpcRejectedCertStorePath = s },

                { "ip|issuercertstorepath=", $"the path of the trusted issuer cert store\nDefault '{OpcIssuerCertDirectoryStorePathDefault}'", (string s) => OpcIssuerCertStorePath = s },

                { "csr", $"show data to create a certificate signing request\nDefault '{ShowCreateSigningRequestInfo}'", c => ShowCreateSigningRequestInfo = c != null },

                { "ab|applicationcertbase64=", $"update/set this applications certificate with the certificate passed in as bas64 string", (string s) =>
                  {
                      NewCertificateBase64String = s;
                  } },
                { "af|applicationcertfile=", $"update/set this applications certificate with the certificate file specified", (string s) =>
                  {
                      if (File.Exists(s))
                      {
                          NewCertificateFileName = s;
                      }
                      else
                      {
                          throw new OptionException("The file '{s}' does not exist.", "applicationcertfile");
                      }
                  } },

                { "pb|privatekeybase64=", $"initial provisioning of the application certificate (with a PEM or PFX fomat) requires a private key passed in as base64 string", (string s) =>
                  {
                      PrivateKeyBase64String = s;
                  } },
                { "pk|privatekeyfile=", $"initial provisioning of the application certificate (with a PEM or PFX fomat) requires a private key passed in as file", (string s) =>
                  {
                      if (File.Exists(s))
                      {
                          PrivateKeyFileName = s;
                      }
                      else
                      {
                          throw new OptionException("The file '{s}' does not exist.", "privatekeyfile");
                      }
                  } },

                { "cp|certpassword="******"the optional password for the PEM or PFX or the installed application certificate", (string s) =>
                  {
                      CertificatePassword = s;
                  } },

                { "tb|addtrustedcertbase64=", $"adds the certificate to the applications trusted cert store passed in as base64 string (multiple strings supported)", (string s) =>
                  {
                      TrustedCertificateBase64Strings = ParseListOfStrings(s);
                  } },
                { "tf|addtrustedcertfile=", $"adds the certificate file(s) to the applications trusted cert store passed in as base64 string (multiple filenames supported)", (string s) =>
                  {
                      TrustedCertificateFileNames = ParseListOfFileNames(s, "addtrustedcertfile");
                  } },

                { "ib|addissuercertbase64=", $"adds the specified issuer certificate to the applications trusted issuer cert store passed in as base64 string (multiple strings supported)", (string s) =>
                  {
                      IssuerCertificateBase64Strings = ParseListOfStrings(s);
                  } },
                { "if|addissuercertfile=", $"adds the specified issuer certificate file(s) to the applications trusted issuer cert store (multiple filenames supported)", (string s) =>
                  {
                      IssuerCertificateFileNames = ParseListOfFileNames(s, "addissuercertfile");
                  } },

                { "rb|updatecrlbase64=", $"update the CRL passed in as base64 string to the corresponding cert store (trusted or trusted issuer)", (string s) =>
                  {
                      CrlBase64String = s;
                  } },
                { "uc|updatecrlfile=", $"update the CRL passed in as file to the corresponding cert store (trusted or trusted issuer)", (string s) =>
                  {
                      if (File.Exists(s))
                      {
                          CrlFileName = s;
                      }
                      else
                      {
                          throw new OptionException("The file '{s}' does not exist.", "updatecrlfile");
                      }
                  } },

                { "rc|removecert=", $"remove cert(s) with the given thumbprint(s) (multiple thumbprints supported)", (string s) =>
                  {
                      ThumbprintsToRemove = ParseListOfStrings(s);
                  } },

                // misc
                { "h|help", "show this message and exit", h => shouldShowHelp = h != null },
            };

            List <string> extraArgs = new List <string>();

            try
            {
                // parse the command line
                extraArgs = options.Parse(args);
            }
            catch (OptionException e)
            {
                // initialize logging
                InitLogging();

                // show message
                Logger.Fatal(e, "Error in command line options");
                Logger.Error($"Command line arguments: {String.Join(" ", args)}");
                // show usage
                Usage(options);
                return;
            }

            // initialize logging
            InitLogging();

            // show usage if requested
            if (shouldShowHelp)
            {
                Usage(options);
                return;
            }

            // validate and parse extra arguments
            if (extraArgs.Count > 0)
            {
                Logger.Error("Error in command line options");
                Logger.Error($"Command line arguments: {String.Join(" ", args)}");
                Usage(options);
                return;
            }

            //show version
            Logger.Information($"{ProgramName} V{FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion} starting up...");
            Logger.Debug($"Informational version: V{(Attribute.GetCustomAttribute(Assembly.GetEntryAssembly(), typeof(AssemblyInformationalVersionAttribute)) as AssemblyInformationalVersionAttribute).InformationalVersion}");

            try
            {
                await ConsoleServerAsync(args);
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex, "OPC UA server failed unexpectedly.");
            }
            Logger.Information("OPC UA server exiting...");
        }
Exemplo n.º 17
0
 public void Fatal(string message)
 {
     log.Fatal(message);
 }
Exemplo n.º 18
0
 public void Fatal(string log)
 {
     Logger.Fatal(log);
 }