public void Message_And_Inner_Exception_Constructor()
        {
            Exception inner = new Exception("Inner exception");
            InvalidConfigurationException ex = new InvalidConfigurationException("Custom message.", inner);

            Assert.Equal("Custom message.", ex.Message);
            Assert.Equal(inner, ex.InnerException);
        }
        /// <summary>
        /// Create sdk factory
        /// </summary>
        /// <param name="config"></param>
        /// <param name="broker"></param>
        /// <param name="logger"></param>
        public IoTSdkFactory(IModuleConfig config, IEventSourceBroker broker, ILogger logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            if (broker != null)
            {
                _logHook = broker.Subscribe(IoTSdkLogger.EventSource, new IoTSdkLogger(logger));
            }

            // The runtime injects this as an environment variable
            var deviceId = Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID");
            var moduleId = Environment.GetEnvironmentVariable("IOTEDGE_MODULEID");
            var ehubHost = Environment.GetEnvironmentVariable("IOTEDGE_GATEWAYHOSTNAME");

            try {
                if (!string.IsNullOrEmpty(config.EdgeHubConnectionString))
                {
                    _cs = IotHubConnectionStringBuilder.Create(config.EdgeHubConnectionString);

                    if (string.IsNullOrEmpty(_cs.SharedAccessKey))
                    {
                        throw new InvalidConfigurationException(
                                  "Connection string is missing shared access key.");
                    }
                    if (string.IsNullOrEmpty(_cs.DeviceId))
                    {
                        throw new InvalidConfigurationException(
                                  "Connection string is missing device id.");
                    }

                    deviceId = _cs.DeviceId;
                    moduleId = _cs.ModuleId;
                    ehubHost = _cs.GatewayHostName ?? ehubHost;

                    if (string.IsNullOrWhiteSpace(_cs.GatewayHostName) && !string.IsNullOrWhiteSpace(ehubHost))
                    {
                        _cs = IotHubConnectionStringBuilder.Create(
                            config.EdgeHubConnectionString + ";GatewayHostName=" + ehubHost);
                    }
                }
            }
            catch (Exception e) {
                _logger.Error(e, "Bad configuration value in EdgeHubConnectionString config.");
            }

            ModuleId = moduleId;
            DeviceId = deviceId;
            Gateway  = ehubHost;

            if (string.IsNullOrEmpty(DeviceId))
            {
                var ex = new InvalidConfigurationException(
                    "If you are running outside of an IoT Edge context or in EdgeHubDev mode, then the " +
                    "host configuration is incomplete and missing the EdgeHubConnectionString setting." +
                    "You can run the module using the command line interface or in IoT Edge context, or " +
                    "manually set the 'EdgeHubConnectionString' environment variable.");

                _logger.Error(ex, "The Twin module was not configured correctly.");
                throw ex;
            }

            _bypassCertValidation = config.BypassCertVerification;
            if (!_bypassCertValidation)
            {
                var certPath = Environment.GetEnvironmentVariable("EdgeModuleCACertificateFile");
                if (!string.IsNullOrWhiteSpace(certPath))
                {
                    InstallCert(certPath);
                }
                else if (!string.IsNullOrEmpty(ehubHost))
                {
                    _bypassCertValidation = true;
                }
            }
            if (!string.IsNullOrEmpty(ehubHost))
            {
                // Running in edge mode
                // the configured transport (if provided) will be forced to it's OverTcp
                // variant as follows: AmqpOverTcp when Amqp, AmqpOverWebsocket or AmqpOverTcp specified
                // and MqttOverTcp otherwise. Default is MqttOverTcp
                if ((config.Transport & TransportOption.Mqtt) != 0)
                {
                    // prefer Mqtt over Amqp due to performance reasons
                    _transport = TransportOption.MqttOverTcp;
                }
                else
                {
                    _transport = TransportOption.AmqpOverTcp;
                }
                _logger.Information("Connecting all clients to {edgeHub} using {transport}.",
                                    ehubHost, _transport);
            }
            else
            {
                _transport = config.Transport;
            }
            _timeout = TimeSpan.FromMinutes(5);
        }
        /// <summary>
        /// Create sdk factory
        /// </summary>
        /// <param name="config"></param>
        /// <param name="logger"></param>
        public IoTSdkFactory(IModuleConfig config, ILogger logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            // The runtime injects this as an environment variable
            var deviceId = Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID");
            var moduleId = Environment.GetEnvironmentVariable("IOTEDGE_MODULEID");
            var ehubHost = Environment.GetEnvironmentVariable("IOTEDGE_GATEWAYHOSTNAME");

            if (string.IsNullOrEmpty(deviceId) ||
                string.IsNullOrEmpty(moduleId))
            {
                try {
                    if (!string.IsNullOrEmpty(config.EdgeHubConnectionString))
                    {
                        _cs = IotHubConnectionStringBuilder.Create(config.EdgeHubConnectionString);

                        if (string.IsNullOrEmpty(_cs.SharedAccessKey))
                        {
                            throw new InvalidConfigurationException(
                                      "Connection string is missing shared access key.");
                        }
                        if (string.IsNullOrEmpty(_cs.DeviceId))
                        {
                            throw new InvalidConfigurationException(
                                      "Connection string is missing device id.");
                        }

                        deviceId = _cs.DeviceId;
                        moduleId = _cs.ModuleId;
                        ehubHost = _cs.GatewayHostName;
                    }
                }
                catch (Exception e) {
                    _logger.Error(e, "Bad configuration value in EdgeHubConnectionString config.");
                }
            }

            ModuleId = moduleId;
            DeviceId = deviceId;

            if (string.IsNullOrEmpty(DeviceId))
            {
                var ex = new InvalidConfigurationException(
                    "If you are running outside of an IoT Edge context or in EdgeHubDev mode, then the " +
                    "host configuration is incomplete and missing the EdgeHubConnectionString setting." +
                    "You can run the module using the command line interface or in IoT Edge context, or " +
                    "manually set the 'EdgeHubConnectionString' environment variable.");

                _logger.Error(ex, "The Twin module was not configured correctly.");
                throw ex;
            }

            _bypassCertValidation = config.BypassCertVerification;
            if (!_bypassCertValidation)
            {
                var certPath = Environment.GetEnvironmentVariable("EdgeModuleCACertificateFile");
                if (!string.IsNullOrWhiteSpace(certPath))
                {
                    InstallCert(certPath);
                }
            }

            if (_bypassCertValidation)
            {
                // Running in debug mode - can only use mqtt over tcp
                _transport = TransportOption.MqttOverTcp;
            }
            else
            {
                _transport = config.Transport;
            }

            _timeout = TimeSpan.FromMinutes(5);
        }
        /// <summary>
        /// Create sdk factory
        /// </summary>
        /// <param name="config"></param>
        /// <param name="logger"></param>
        public IoTSdkFactory(IModuleConfig config, ILogger logger)
        {
            _logger = logger ?? throw new ArgumentNullException(nameof(logger));

            // The runtime injects this as an environment variable
            var deviceId = Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID");
            var moduleId = Environment.GetEnvironmentVariable("IOTEDGE_MODULEID");
            var ehubHost = Environment.GetEnvironmentVariable("IOTEDGE_GATEWAYHOSTNAME");

            try {
                if (!string.IsNullOrEmpty(config.EdgeHubConnectionString))
                {
                    _cs = IotHubConnectionStringBuilder.Create(config.EdgeHubConnectionString);
                    if (string.IsNullOrEmpty(_cs.DeviceId))
                    {
                        throw new InvalidConfigurationException(
                                  "Connection string is not a device or module connection string.");
                    }
                    deviceId = _cs.DeviceId;
                    moduleId = _cs.ModuleId;
                    ehubHost = _cs.GatewayHostName;
                }
                else if (string.IsNullOrEmpty(moduleId))
                {
                    throw new InvalidConfigurationException(
                              "Must have connection string or module id to create clients.");
                }
            }
            catch (Exception e) {
                var ex = new InvalidConfigurationException(
                    "The host configuration is incomplete and is missing a " +
                    "connection string for Azure IoTEdge or IoTHub. " +
                    "You either have to run the host under the control of " +
                    "EdgeAgent, or manually set the 'EdgeHubConnectionString' " +
                    "environment variable or configure the connection string " +
                    "value in your 'appsettings.json' configuration file.", e);
                _logger.Error("Bad configuration", () => ex);
                throw ex;
            }

            ModuleId = moduleId;
            DeviceId = deviceId;

            _bypassCertValidation = config.BypassCertVerification;
            if (!_bypassCertValidation)
            {
                var certPath = Environment.GetEnvironmentVariable("EdgeModuleCACertificateFile");
                if (!string.IsNullOrWhiteSpace(certPath))
                {
                    InstallCert(certPath);
                }
            }

            if (_bypassCertValidation)
            {
                // Running in debug mode - can only use mqtt over tcp
                _transport = TransportOption.MqttOverTcp;
            }
            else
            {
                _transport = config.Transport;
            }

            _timeout = TimeSpan.FromMinutes(5);
        }
Esempio n. 5
0
        /// <summary>
        /// This method reads the app.config file to
        /// load the current configuration.
        /// </summary>
        /// <returns></returns>
        public void ConnectToDatabase(DataManager dataManager)
        {
            // locals
            string methodName = "ConnectToDatabase";
            string objectName = "AuthenticationManager";

            // Create variable for a possible CustomException
            CustomException exception = null;

            try
            {
                // If connection is not set
                if (String.IsNullOrEmpty(dataManager.DataConnector.ConnectionString))
                {
                    // Read Configuration File
                    this.Configuration.Read();

                    // If the configuration is valid
                    if (this.Configuration.IsValid)
                    {
                        // if the ConnectionString exists
                        if (this.Configuration.HasConnectionString)
                        {
                            // Set the connection string using Integrated Secrity (Windows Authentication)
                            dataManager.DataConnector.ConnectionString = this.Configuration.ConnectionString;
                        }
                        else
                        {
                            // set the server
                            string serverName = this.Configuration.DatabaseServer;

                            // set the databaseName
                            string databaseName = this.Configuration.DatabaseName;

                            // If integrated security is set to true
                            if (this.Configuration.IntegratedSecurity)
                            {
                                // Set the connection string using Integrated Secrity (Windows Authentication)
                                dataManager.DataConnector.ConnectionString = dataManager.DataConnector.BuildConnectionString(serverName, databaseName);
                            }
                            else
                            {
                                // set the userName
                                string userName = this.Configuration.DatabaseUserName;

                                // set the password
                                string password = this.Configuration.DatabasePassword;

                                // build the connectionstring for Sql Server Authentication
                                dataManager.DataConnector.ConnectionString = dataManager.DataConnector.BuildConnectionString(serverName, databaseName, userName, password);
                            }
                        }
                    }
                }

                // check if database is already connected
                if (dataManager.DataConnector.State == System.Data.ConnectionState.Open)
                {
                    // close connection and reopen (there should not be any open connection here.
                    // To Do: Log Error 'Database Connection Was Already Open'
                    dataManager.DataConnector.Close();
                }

                // Open Connection
                dataManager.DataConnector.Open();
            }
            catch (Exception error)
            {
                // If ErrorProcessor exists
                if (this.ErrorProcessor != null)
                {
                    // Only create a new configuration error if it does not already exist.
                    if (error as CustomException == null)
                    {
                        // If the configuration is not valid
                        if (!this.Configuration.IsValid)
                        {
                            // Create Instance of configurationError
                            exception = new InvalidConfigurationException(methodName, objectName, error);
                        }
                        else
                        {
                            // Create Instance of dataConnectionError
                            exception = new DataConnectionFailedException(methodName, objectName, error);
                        }
                    }

                    // Log this error
                    this.ErrorProcessor.LogError(methodName, objectName, exception);
                }
            }
        }
Esempio n. 6
0
        public byte[] GetBinaryPayload()
        {
            if (String.IsNullOrEmpty(Input))
            {
                throw InvalidConfigurationException.FromErrorCode(ErrorCodes.Verifiers.MissingBinaryInput);
            }

            try
            {
                var bytes = new List <Byte>();

                var bytesList = Input.Split(' ');
                foreach (var byteStr in bytesList)
                {
                    var lowerByteStr = byteStr.ToLower();
                    if (lowerByteStr.Contains("soh"))
                    {
                        bytes.Add(0x01);
                    }
                    else if (lowerByteStr.Contains("stx"))
                    {
                        bytes.Add(0x02);
                    }
                    else if (lowerByteStr.Contains("etx"))
                    {
                        bytes.Add(0x03);
                    }
                    else if (lowerByteStr.Contains("eot"))
                    {
                        bytes.Add(0x04);
                    }
                    else if (lowerByteStr.Contains("ack"))
                    {
                        bytes.Add(0x06);
                    }
                    else if (lowerByteStr.Contains("cr"))
                    {
                        bytes.Add(0x0d);
                    }
                    else if (lowerByteStr.Contains("lf"))
                    {
                        bytes.Add(0x0a);
                    }
                    else if (lowerByteStr.Contains("nak"))
                    {
                        bytes.Add(0x15);
                    }
                    else if (lowerByteStr.Contains("esc"))
                    {
                        bytes.Add(0x1b);
                    }
                    else if (lowerByteStr.Contains("del"))
                    {
                        bytes.Add(0x1b);
                    }
                    else if (lowerByteStr.StartsWith("0x"))
                    {
                        bytes.Add(Byte.Parse(byteStr.Substring(2), System.Globalization.NumberStyles.HexNumber));
                    }
                    else
                    {
                        bytes.Add(Byte.Parse(byteStr, System.Globalization.NumberStyles.HexNumber));
                    }
                }

                return(bytes.ToArray());
            }
            catch (Exception ex)
            {
                throw InvalidConfigurationException.FromErrorCode(ErrorCodes.Verifiers.CouldNotConvertInputToBytes, ex.Message);
            }
        }
        public void Default_Constructor()
        {
            InvalidConfigurationException ex = new InvalidConfigurationException();

            Assert.Equal("Invalid configuration.", ex.Message);
        }
        public void Message_Constructor()
        {
            InvalidConfigurationException ex = new InvalidConfigurationException("Custom message.");

            Assert.Equal("Custom message.", ex.Message);
        }
        /// <summary>
        /// This method reads the app.config file to
        /// load the current configuration.
        /// </summary>
        /// <returns></returns>
        public void ConnectToDatabase(DataManager dataManager)
        {
            // locals
            string methodName = "ConnectToDatabase";
            string objectName = "AuthenticationManager";

            // Create variable for a possible CustomException
            CustomException exception = null;

            try
            {
                // If connection is not set
                if (String.IsNullOrEmpty(dataManager.DataConnector.ConnectionString))
                {
                    // if the connectionName is set
                    if (TextHelper.Exists(dataManager.ConnectionName))
                    {
                        // Set the ConnectionString (requires DataJuggler.Core.UltimateHelper version 1.3.5 or greater)
                        dataManager.DataConnector.ConnectionString = EnvironmentVariableHelper.GetEnvironmentVariableValue(dataManager.ConnectionName);
                    }
                    else
                    {
                        // this is for environments using a web.config or app.config.

                        // For Dot Net Core / Blazor or any new projects, Environment Variables are now the
                        // recommended way to store connection strings.

                        // Read Configuration File
                        this.Configuration.Read();

                        // If the configuration is valid
                        if (this.Configuration.IsValid)
                        {
                            // if the ConnectionString exists
                            if (this.Configuration.HasConnectionString)
                            {
                                // Set the connection string using Integrated Secrity (Windows Authentication)
                                dataManager.DataConnector.ConnectionString = this.Configuration.ConnectionString;
                            }
                            else
                            {
                                // set the server
                                string serverName = this.Configuration.DatabaseServer;

                                // set the databaseName
                                string databaseName = this.Configuration.DatabaseName;

                                // If integrated security is set to true
                                if (this.Configuration.IntegratedSecurity)
                                {
                                    // Set the connection string using Integrated Secrity (Windows Authentication)
                                    dataManager.DataConnector.ConnectionString = dataManager.DataConnector.BuildConnectionString(serverName, databaseName);
                                }
                                else
                                {
                                    // set the userName
                                    string userName = this.Configuration.DatabaseUserName;

                                    // set the password
                                    string password = this.Configuration.DatabasePassword;

                                    // build the connectionstring for Sql Server Authentication
                                    dataManager.DataConnector.ConnectionString = dataManager.DataConnector.BuildConnectionString(serverName, databaseName, userName, password);
                                }
                            }
                        }
                    }
                }

                // check if database is already connected
                if (dataManager.DataConnector.State == System.Data.ConnectionState.Open)
                {
                    // close connection and reopen (there should not be any open connections here)
                    // I have been thinking of a bulk insert feature in the future, but that is not for this method
                    // To Do: Log Error 'Database Connection Was Already Open'
                    dataManager.DataConnector.Close();
                }

                // Open Connection
                dataManager.DataConnector.Open();
            }
            catch (Exception error)
            {
                // If ErrorProcessor exists
                if (this.ErrorProcessor != null)
                {
                    // Only create a new configuration error if it does not already exist.
                    if (error as CustomException == null)
                    {
                        // If the configuration is not valid
                        if (!this.Configuration.IsValid)
                        {
                            // Create Instance of configurationError
                            exception = new InvalidConfigurationException(methodName, objectName, error);
                        }
                        else
                        {
                            // Create Instance of dataConnectionError
                            exception = new DataConnectionFailedException(methodName, objectName, error);
                        }
                    }

                    // Log this error
                    this.ErrorProcessor.LogError(methodName, objectName, exception);
                }
            }
        }