コード例 #1
0
        /// <inheritdoc />
        public void Stop()
        {
            var subclassTypeName = GetType().Name;

            _logger.Info($"{nameof(Stop)} called on {subclassTypeName}");
            var cancelRequestedAt = DateTime.Now;

            // declare cancellation, wait for all clear
            _cts.Cancel();
            const int MaxWaitInSeconds = 10;
            var       exitBy           = DateTime.Now.AddSeconds(MaxWaitInSeconds);

            while (DateTime.Now <= exitBy)
            {
                if (!IsRunning())
                {
                    break;
                }

                Thread.Sleep(500); // brief delay before re-check
            }

            if (IsRunning())
            {
                _logger.Warn($"Tried to call {nameof(Stop)} for '{GetType().Name}', but could not shut it down within {TimeSpan.FromSeconds(MaxWaitInSeconds).TotalMilliseconds} milliseconds!");
            }
            else
            {
                _logger.Info($"Finished {nameof(Stop)} for '{GetType().Name}' in {Math.Abs(exitBy.Subtract(DateTime.Now).TotalMilliseconds)} milliseconds");
            }
        }
コード例 #2
0
        private void UdpCallback(string payload)
        {
            try
            {
                var payloadObj = UdpPayload.Parse(payload);
                if (payloadObj.Status == PayloadStatus.Success)
                {
                    switch (payloadObj.Type)
                    {
                    case PayloadType.Controller:
                        HandleControllerPayload(payloadObj.Payload);
                        break;

                    case PayloadType.Mouse:
                        HandleMousePayload(payloadObj.Payload);
                        break;

                    default:
                        _logger.Warn($"Unknown payload type: {payloadObj.Type.ToString()}");
                        _logger.Debug($"Payload: {payload}");
                        break;
                    }
                }
                else
                {
                    _logger.Warn($"Unable to parse incoming payload");
                    _logger.Debug($"Payload: {payload}");
                }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
            }
        }
コード例 #3
0
        /// <inheritdoc />
        public void ManagerStart()
        {
            _logger.Info($"{nameof(ManagerStart)} was hit");

            // write runtime startup metrics
            var currentVersion = _fm.GetExecutingAssemblyVersion();
            var sb             = new StringBuilder();

            sb.AppendLine($"Starting up {nameof(AlertManager)} (version {currentVersion}) with the following settings:");
            sb.AppendLine($"\t{nameof(RuntimeSettings)} is {(_rs == null ? "null" : "initialized")}");
            sb.AppendLine($"\t- {nameof(_rs.IsLocalDebugging)} = {_rs.IsLocalDebugging}");
            sb.AppendLine($"\t- {nameof(_rs.EmailSmtpServer)} = {_rs.EmailSmtpServer}");
            sb.AppendLine($"\t- {nameof(_rs.EmailSmtpPort)} = {_rs.EmailSmtpPort}");
            sb.AppendLine($"\t- {nameof(_rs.EmailSmtpUseSsl)} = {_rs.EmailSmtpUseSsl}");
            sb.AppendLine($"\t- {nameof(_rs.EmailSenderAddress)} = {_rs.EmailSenderAddress}");
            sb.AppendLine($"\t- {nameof(_rs.EmailRecipientAddress)} = {_rs.EmailRecipientAddress}");
            _logger.Info(sb.ToString());

            // initialize uptime tracker
            _uptimeDelayInMinutes = _rs.IsLocalDebugging ? 1 : 20;
            _uptimeTimer          = new System.Threading.Timer(LogUptime);
            _uptimeTimer.Change(0, (int)TimeSpan.FromMinutes(_uptimeDelayInMinutes).TotalMilliseconds);

            // report battery presence
            _isBatteryDetected = IsBatteryAvailable();
            if (_isBatteryDetected)
            {
                _logger.Info("Battery was found");
            }
            else
            {
                _logger.Warn("No battery was found, so changes in power state will not be reported");
            }

            // report power draw
            _powerSource = SystemInformation.PowerStatus.PowerLineStatus;
            if (_powerSource == PowerLineStatus.Online)
            {
                _logger.Info($"{nameof(PowerLineStatus)} - Running on wall power");
            }
            else if (_powerSource == PowerLineStatus.Offline)
            {
                _logger.Warn($"{nameof(PowerLineStatus)} - Running on battery");
            }
            else
            {
                _logger.Error($"{nameof(PowerLineStatus)} - Unable to determine power draw source!");
            }

            // if on battery power mode, then drop into notification logic
            if (_powerSource == PowerLineStatus.Offline)
            {
                NotifyPowerOnBattery();
            }
        }
コード例 #4
0
        private ErrorModel BuildErrorModel(ExceptionContext exceptionContext)
        {
            var isShowErrors         = _configuration.GetValue <bool>("IsShowErrors");
            var genericErrorMessage  = _configuration.GetValue <string>("ErrorMessage");
            var isHttpContextNotNull = exceptionContext.HttpContext != null;
            var errorMessage         = genericErrorMessage;

            var exceptionType = exceptionContext.Exception.GetType();

            if (exceptionType == typeof(BusinessValidationException))
            {
                errorMessage = exceptionContext.Exception.Message;
                _logger.Warn(exceptionContext.Exception.Message);

                if (isHttpContextNotNull)
                {
                    exceptionContext.HttpContext.Response.StatusCode = 412;
                }
            }
            else if (exceptionType == typeof(BadRequestException))
            {
                errorMessage = exceptionContext.Exception.Message;
                _logger.Warn(exceptionContext.Exception.Message);

                if (isHttpContextNotNull)
                {
                    exceptionContext.HttpContext.Response.StatusCode = 400;
                }
            }
            else
            {
                _logger.Error(exceptionContext.Exception);

                if (isShowErrors)
                {
                    errorMessage = exceptionContext.Exception.Message;
                }

                if (isHttpContextNotNull)
                {
                    exceptionContext.HttpContext.Response.StatusCode = 500;
                }
            }

            var errorModel = new ErrorModel
            {
                Message = errorMessage,
                Id      = _correlationContextAccessor.CorrelationContext.CorrelationId
            };

            return(errorModel);
        }
コード例 #5
0
 public string Log([FromBody] AppError Error)
 {
     // Error.User = this.GetRefUser();
     _logger.Info(Error.FormatException());
     _logger.Error(Error.FormatException());
     _logger.Warn(Error.FormatException());
     return("Logged");
 }
コード例 #6
0
 /// <inheritdoc />
 protected override void OnPause()
 {
     _logger.Warn($"Entered {nameof(OnPause)}");
     base.OnPause();
     _alertManager.ManagerStop();
     _logger.Warn($"Exiting {nameof(OnPause)}");
 }
コード例 #7
0
 private static CustomDbException LogAndGetCustomDbException <TService>(this Exception dbException, IAppLogger <TService> logger, string message)
 {
     logger.Warn(dbException, message);
     return(new CustomDbException(message, dbException));
 }
コード例 #8
0
        /// <inheritdoc />
        public void Send(string subject, string body)
        {
            if (string.IsNullOrWhiteSpace(_runtimeSettings.EmailSenderAddress))
            {
                _logger.Error($"Unable to send email because setting '{nameof(_runtimeSettings.EmailSenderAddress)}' is missing! -- subject = {subject} -- body = {body}");
                return;
            }

            if (string.IsNullOrWhiteSpace(_runtimeSettings.EmailRecipientAddress))
            {
                _logger.Error($"Unable to send email because setting '{nameof(_runtimeSettings.EmailRecipientAddress)}' is missing! -- subject = {subject} -- body = {body}");
                return;
            }

            SmtpClient  client = null;
            MailMessage mm     = null;

            try
            {
                Debug.WriteLine("Creating mail message");
                mm = new MailMessage
                {
                    BodyEncoding = Encoding.UTF8,
                    IsBodyHtml   = false,
                    From         = new MailAddress(_runtimeSettings.EmailSenderAddress, _runtimeSettings.EmailSenderName ?? _runtimeSettings.EmailSenderAddress),
                    Subject      = subject,
                    Body         = body
                };
                mm.To.Add(new MailAddress(_runtimeSettings.EmailRecipientAddress, _runtimeSettings.EmailRecipientName ?? _runtimeSettings.EmailRecipientAddress));

                Debug.WriteLine("Creating SMTP Client");
                client = new SmtpClient
                {
                    Host                  = _runtimeSettings.EmailSmtpServer,
                    Port                  = _runtimeSettings.EmailSmtpPort,
                    EnableSsl             = _runtimeSettings.EmailSmtpUseSsl,
                    DeliveryMethod        = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials           = new NetworkCredential(_runtimeSettings.EmailSmtpLogonName, _runtimeSettings.EmailSmtpLogonPassword),
                    Timeout               = 30000
                };

                if (_isEmailSendingAllowed)
                {
                    Debug.WriteLine("Sending message...");
                    client.Send(mm);
                }
                else
                {
                    _logger.Warn($"Did not send email because {nameof(_isEmailSendingAllowed)} was {_isEmailSendingAllowed}");
                }
            }
            catch (SmtpException smtpEx)
            {
                var message = $"{nameof(SmtpException)} trying to send SmtpClient message: {smtpEx}";
                if (smtpEx.InnerException != null)
                {
                    message += $" --- Inner Exception: {smtpEx.InnerException}";
                }
                _logger?.Error(message);
            }
            catch (Exception ex)
            {
                var message = $"General exception trying to send SmtpClient message: {ex}";
                if (ex.InnerException != null)
                {
                    message += $" --- Inner Exception: {ex.InnerException}";
                }
                _logger?.Error(message);
            }
            finally
            {
                client?.Dispose();
                mm?.Dispose();
            }
        }
コード例 #9
0
        public async Task <bool> RunAsync()
        {
            var connectionInformationEmby1 = _connectionInformationFactory
                                             .CreateConnectionInformation <IConsoleEmbyInstance1ConnectionOptions>();
            var connectionInformationPlex1 = _connectionInformationFactory
                                             .CreateConnectionInformation <IConsolePlexInstance1ConnectionOptions>();

            var embyClient = _clientFactory.CreateClient <IEmbyClient>(connectionInformationEmby1);
            var plexClient = _clientFactory.CreateClient <IPlexClient>(connectionInformationPlex1);

            var userCredentialsService = _serviceFactory.CreateService <IUserCredentialsService>();

            var clients = new List <IClient> {
                embyClient, plexClient
            };

            bool retval;

            try
            {
                // FYI: As async access to the console is not possible, login data is collected ahead of the async login tasks.
                // FYI: Each client gets an instance of the credentials service, but it's up to the client to use it or not.
                clients.ForEach(x => x.SetLoginData(userCredentialsService));

                var didLoginAll = await LoginAllClientsAsync(clients);

                if (didLoginAll == false)
                {
                    _logger.Error("Login to one or more servers failed.");
                    return(false);
                }

                var plexExportLogic = _logicFactory.CreateLogic <IPlexExportLogic>();
                var embyImportLogic = _logicFactory.CreateLogic <IEmbyImportLogic>();

                // TODO - handle RemoteLoggedOut?
                //_embyClient.RemoteLoggedOut += EmbyClient_RemoteLoggedOut;

                //await _embyService.DoItAsync(_embyClient);

                var didExportFromPlex = await plexExportLogic.RunAsync();

                if (didExportFromPlex == false)
                {
                    _logger.Warn("No items to process - exiting.");
                    return(false);
                }

                var didImportToEmby = await embyImportLogic.RunAsync(plexExportLogic.MovieMetadataItems);

                if (didImportToEmby == false)
                {
                    _logger.Warn("Import failed.");
                    return(false);
                }

                _logger.Info("Import finished.");
            }
            finally
            {
                var didLogoutAll = await LogoutAllClientsAsync(clients);

                retval = didLogoutAll;
                _logger.Info("Logic done.");
            }

            return(retval);
        }
コード例 #10
0
ファイル: Feeder.cs プロジェクト: IronhideIvan/pass-thru
        public void Connect(string deviceId)
        {
            if (!UInt32.TryParse(deviceId, out _deviceId))
            {
                throw new PTGenericException($"Error parsing device ID '{deviceId}'. Must be a number.");
            }

            if (_deviceId < 1 || _deviceId > 16)
            {
                throw new PTGenericException($"Illegal device ID '{deviceId}'. Must be between 1 and 16, inclusive.");
            }

            // Initialize the joystick and position structure.
            _joystick = new vJoy();

            // Get the driver attributes (Vendor ID, Product ID, Version Number)
            if (!_joystick.vJoyEnabled())
            {
                throw new PTGenericException("vJoy driver not enabled: Failed Getting vJoy attributes.");
            }
            else
            {
                _logger.Debug($"Vendor: {_joystick.GetvJoyManufacturerString()}");
                _logger.Debug($"Product: {_joystick.GetvJoyProductString()}");
                _logger.Debug($"Version: {_joystick.GetvJoySerialNumberString()}");
            }

            // Test if DLL matches the driver
            uint dllVer = 0, drvVer = 0;
            bool isDriverMatch = _joystick.DriverMatch(ref dllVer, ref drvVer);

            if (isDriverMatch)
            {
                _logger.Debug($"Version of Driver Matches DLL Version ({dllVer})");
            }
            else
            {
                _logger.Warn($"Version of Driver ({drvVer}) does NOT match DLL Version ({dllVer})");
            }

            // Get the state of the requested device
            var status = _joystick.GetVJDStatus(_deviceId);

            switch (status)
            {
            case VjdStat.VJD_STAT_OWN:
                _logger.Debug($"vJoy Device '{_deviceId}' is already owned by this feeder.");
                break;

            case VjdStat.VJD_STAT_FREE:
                _logger.Debug($"vJoy Device '{_deviceId}' is free\n");
                break;

            case VjdStat.VJD_STAT_BUSY:
                throw new PTGenericException($"vJoy Device '{_deviceId}' is already owned by another feeder. Cannot connect.");

            case VjdStat.VJD_STAT_MISS:
                throw new PTGenericException($"vJoy Device '{_deviceId}' is not installed or disabled. Cannot connect.");

            default:
                throw new PTGenericException($"vJoy Device '{_deviceId}' general error. Cannot connect.");
            }
            ;

            // Acquire the target
            if ((status == VjdStat.VJD_STAT_OWN) || ((status == VjdStat.VJD_STAT_FREE) && (!_joystick.AcquireVJD(_deviceId))))
            {
                throw new PTGenericException($"Failed to acquire vJoy device number '{_deviceId}'.");
            }
            else
            {
                _logger.Info($"Acquired: vJoy device number '{_deviceId}'.");
            }

            _axisX  = _joystick.GetVJDAxisExist(_deviceId, HID_USAGES.HID_USAGE_X);
            _axisY  = _joystick.GetVJDAxisExist(_deviceId, HID_USAGES.HID_USAGE_Y);
            _axisZ  = _joystick.GetVJDAxisExist(_deviceId, HID_USAGES.HID_USAGE_Z);
            _axisRX = _joystick.GetVJDAxisExist(_deviceId, HID_USAGES.HID_USAGE_RX);
            _axisRY = _joystick.GetVJDAxisExist(_deviceId, HID_USAGES.HID_USAGE_RY);
            _axisRZ = _joystick.GetVJDAxisExist(_deviceId, HID_USAGES.HID_USAGE_RZ);
            // Get the number of buttons and POV Hat switchessupported by this vJoy device
            _nButtons      = _joystick.GetVJDButtonNumber(_deviceId);
            _contPovNumber = _joystick.GetVJDContPovNumber(_deviceId);
            _discPovNumber = _joystick.GetVJDDiscPovNumber(_deviceId);

            _joystick.GetVJDAxisMin(_deviceId, HID_USAGES.HID_USAGE_X, ref _axisMinX);
            _joystick.GetVJDAxisMax(_deviceId, HID_USAGES.HID_USAGE_X, ref _axisMaxX);
            _joystick.GetVJDAxisMin(_deviceId, HID_USAGES.HID_USAGE_Y, ref _axisMinY);
            _joystick.GetVJDAxisMax(_deviceId, HID_USAGES.HID_USAGE_Y, ref _axisMaxY);
            _joystick.GetVJDAxisMin(_deviceId, HID_USAGES.HID_USAGE_Z, ref _axisMinZ);
            _joystick.GetVJDAxisMax(_deviceId, HID_USAGES.HID_USAGE_Z, ref _axisMaxZ);
            _joystick.GetVJDAxisMin(_deviceId, HID_USAGES.HID_USAGE_RX, ref _axisMinRX);
            _joystick.GetVJDAxisMax(_deviceId, HID_USAGES.HID_USAGE_RX, ref _axisMaxRX);
            _joystick.GetVJDAxisMin(_deviceId, HID_USAGES.HID_USAGE_RY, ref _axisMinRY);
            _joystick.GetVJDAxisMax(_deviceId, HID_USAGES.HID_USAGE_RY, ref _axisMaxRY);
            _joystick.GetVJDAxisMin(_deviceId, HID_USAGES.HID_USAGE_RZ, ref _axisMinRZ);
            _joystick.GetVJDAxisMax(_deviceId, HID_USAGES.HID_USAGE_RZ, ref _axisMaxRZ);

            PrintDeviceSupport();
        }