public IConnection CreateConnection()
        {
            var connectionString = _configuration.RabbitMqConnectionString;

            if (connectionString == null)
            {
                _logger?.Fatal("Not connection string found for RabbitMQ. Can not create a bus. Aborting...");
                throw new ConfigurationErrorsException("Could not find a connection string for RabbitMQ. Please add a connection string in the <connectionStrings> section of the application's configuration file. For example: <add name=\"RabbitMQ\" connectionString=\"host=localhost\" />");
            }

            try
            {
                _factory.Uri = new Uri(connectionString);

                if (_configuration.RabbitMqClusterHosts == null)
                {
                    _logger?.Verbose("Creating RabbitMQ connection. connection-string={RabbitConnectionString}", _configuration.RabbitMqConnectionString);
                    return(_factory.CreateConnection());
                }

                _logger?.Verbose("Creating RabbitMQ cluster connection. connection-string={RabbitConnectionString}, cluster-hosts={RabbitClusterHosts}", _configuration.RabbitMqConnectionString, _configuration.RabbitMqClusterHosts);
                return(_factory.CreateConnection(AmqpTcpEndpoint.ParseMultiple(_configuration.RabbitMqClusterHosts)));
            }
            catch (Exception ex)
            {
                _logger?.Fatal(ex, "Cannot connect to RabbitMQ using the provided configuration.");
                throw;
            }
        }
Exemple #2
0
 /// <inheritdoc />
 public void LogFatal <T>(T value)
 {
     if (IsFatalLoggingEnabled)
     {
         _logger?.Fatal(value);
     }
 }
Exemple #3
0
 protected override void OnStartup(StartupEventArgs e)
 {
     base.OnStartup(e);
     Logger = LogManager.GetCurrentClassLogger();
     try {
         // Exception handlers
         DispatcherUnhandledException += (m, n) => {
             Exception exception = n.Exception;
             Exception innerException = GetInnerException(exception);
             Logger.Error(exception, "[OnStartup] An unhandled dispatcher exception occurred.");
             HandleException(innerException);
             n.Handled = true;
             Current.Shutdown();
         };
         AppDomain.CurrentDomain.UnhandledException += (m, n) => {
             Exception exception = n.ExceptionObject as Exception;
             if (exception == null) {
                 Logger.Fatal("[OnStartup] Unknow error killed application");
             } else {
                 Logger.Fatal(exception, "[OnStartup] An unhandled exception occurred and the application is terminating");
             }
             HandleException(exception);
         };
         // Initialize dispatcher helper so we can access UI thread in view model
         DispatcherHelper.Initialize();
         // Bootstrapping
         DiBootstrapperFrontend.Initialize(IoC.Container);
         Logger.Info("[OnStartup] Application successfully started");
     } catch (Exception exception) {
         Logger.Fatal(exception, "[OnStartup] Error during starting Application");
         HandleException(exception);
         Current.Shutdown();
     }
 }
Exemple #4
0
        public void Start()
        {
            logger = LoggerFactory.GetLogger("SimpleHttpServer.Server");

            logger.Info("Server starting on port {0}", port);

            if (listener != null)
            {
                logger.Fatal("Server already started");
                throw new InvalidOperationException("Already started");
            }

            listener = new HttpListener();
            listener.Prefixes.Add(string.Format("http://*:{0}/", port));

            try
            {
                listener.Start();
            }
            catch(Exception ex)
            {
                logger.Fatal("Error starting server", ex);
                throw;
            }

            logger.Info("Server started");

            logger.Debug("Waiting for first request");
            listener.BeginGetContext(ProcessRequest, null);
        }
        protected bool ValueExists(
            string columnName,
            string tableName,
            object value,
            MySqlConnection connection)
        {
            bool exists = true;

            try
            {
                MySqlCommand command = CreateSelectCommand(columnName, tableName, columnName, "=", value);
                command.Connection = connection;

                MySqlDataReader reader = command.ExecuteReader();

                exists = reader.Read();

                reader.Close();
            }
            catch (Exception ex)
            {
                _logger?.Fatal(ex);
                exists = false;
            }

            return(exists);
        }
Exemple #6
0
        private void FatalShutdown(Exception e, string message)
        {
            _logger?.Fatal(e, message);
            Shutdown(-1);

            User32.MessageBox(IntPtr.Zero,
                              $"{message}. Details: {e.GetBaseException().Message}",
                              "Fatal error",
                              MessageBoxStyle.OK |
                              MessageBoxStyle.IconError);
        }
Exemple #7
0
        public IConnection CreateConnection()
        {
            var connectionString = _configuration.RabbitMqConnectionString;

            if (connectionString == null)
            {
                _logger?.Fatal("Not connection string found for RabbitMQ. Can not create a bus. Aborting...");
                throw new ConfigurationErrorsException("Could not find a connection string for RabbitMQ. Please add a connection string in the <connectionStrings> section of the application's configuration file. For example: <add name=\"RabbitMQ\" connectionString=\"host=localhost\" />");
            }

            try
            {
                _factory.Uri = new Uri(connectionString);

                if (!_configuration.LogSensitiveData && !String.IsNullOrWhiteSpace(_factory.Uri.UserInfo))
                {
                    connectionString = connectionString.Replace($"{_factory.Uri.UserInfo}@", "*** BLOCKED ***@");
                }

                if (_configuration.RabbitMqAutomaticRecoveryEnabled && _factory is ConnectionFactory connectionFactory)
                {
                    connectionFactory.AutomaticRecoveryEnabled = true;
                }

                if (_configuration.RabbitMqClusterHosts == null)
                {
                    _logger?.Verbose("Creating RabbitMQ connection. connection-string={RabbitConnectionString}, automatic-recovery-enabled={RabbitAutomaticRecoveryEnabled}", connectionString, _configuration.RabbitMqAutomaticRecoveryEnabled);
                    return(_factory.CreateConnection());
                }

                _logger?.Verbose("Creating RabbitMQ cluster connection. connection-string={RabbitConnectionString}, cluster-hosts={RabbitClusterHosts}, automatic-recovery-enabled={RabbitAutomaticRecoveryEnabled}", connectionString, _configuration.RabbitMqClusterHosts, _configuration.RabbitMqAutomaticRecoveryEnabled);

                return(_factory.CreateConnection(AmqpTcpEndpoint.ParseMultiple(_configuration.RabbitMqClusterHosts)));
            }
            catch (Exception ex)
            {
                _logger?.Fatal(ex, "Cannot connect to RabbitMQ using the provided configuration.");
                throw;
            }
        }
        private JToken CreateTestOnJira(RhinoTestCase testCase)
        {
            // shortcuts
            var onProject = Configuration.ConnectorConfiguration.Project;
            var testType  = $"{capabilities[AtlassianCapabilities.TestType]}";

            // setup context
            testCase.Context["issuetype-id"] = $"{jiraClient.GetIssueTypeFields(idOrKey: testType, path: "id")}";
            testCase.Context["project-key"]  = onProject;

            // setup request body
            var issue = jiraClient.Create(testCase.ToJiraCreateRequest()).AsJObject();

            if (issue == default || !issue.ContainsKey("id"))
            {
                logger?.Fatal("Was not able to create a test case.");
                return(default);
Exemple #9
0
        public static void SetError(this IResponse response, System.Exception ex, ILogger logger)
        {
            response.DidError = true;

            var cast = ex as DatabaseException;

            if (cast == null)
            {
                logger?.Fatal(ex.ToString());
                response.ErrorMessage = "There was an internal error, please contact to technical support.";
            }
            else
            {
                logger?.Error(ex.Message);
                response.ErrorMessage = ex.Message;
            }
        }
Exemple #10
0
 private static void LogWithLogger(LogItem logItem, ILogger logger)
 {
     switch (logItem.LogLevel)
     {
         case LogLevel.Trace:
             logger.Trace(() => logItem.Message, logItem.Exception);
             break;
         case LogLevel.Info:
             logger.Info(() => logItem.Message, logItem.Exception);
             break;
         case LogLevel.Warn:
             logger.Warn(() => logItem.Message, logItem.Exception);
             break;
         case LogLevel.Error:
             logger.Error(() => logItem.Message, logItem.Exception);
             break;
         case LogLevel.Fatal:
             logger.Fatal(() => logItem.Message, logItem.Exception);
             break;
     }
 }
        protected override async void OnAppearing()
        {
            await _splashImage.ScaleTo(1, 2000);

            base.OnAppearing();

            try
            {
                DIContainerInitializer.Instance.Initialize();

                Constants.DbPath = DependencyService.Get <IPath>().GetDatabasePath(Constants.DbFileName);
                _logger          = DependencyService.Get <ILogManager>().GetLog();
                _dbManager       = ServiceLocator.Current.GetInstance <IDbManager>();
                _pageCreator     = ServiceLocator.Current.GetInstance <PageCreator>();

#if DELETEDBDEBUG
                if (!_dbManager.TryDeleteDatabase(out var excep))
                {
                    _logger.Fatal("Failed to delete DB.", excep);
                    throw excep;
                }
#endif

                if (!_dbManager.TryCreateDatabase(out var exception))
                {
                    _logger.Fatal("Failed to create DB.", exception);
                    throw exception;
                }
            }
            catch (Exception ex)
            {
                _logger?.Fatal("Exception while loading app.", ex);
                throw;
            }

            Application.Current.MainPage = new NavigationPage(_pageCreator.CreateGroupsPage())
            {
                BarBackgroundColor = _blueColor,
            };
        }
        public static async Task Main(string[] args)
        {
            try
            {
                Setup(args);

#if !DEBUG
                System.Console.WriteLine("Press 'y' to continue.");
                if (System.Console.ReadKey().Key != ConsoleKey.Y)
                {
                    return;
                }
                System.Console.WriteLine();
#endif

                await ExecuteAsync();
            }
            catch (Exception e)
            {
                log?.Fatal("Application failed: {Message}", e.Message);
                log?.Verbose(e, "Application failed with unhandled exception.");
            }
        }
 public static void CreateLogItems(ILogger logger)
 {
     foreach (var pocoLogItem in Session.List<PocoLogItem>(100).Get())
     {
         switch (pocoLogItem.LogLevel)
         {
             case LogLevel.Debug:
                 logger.Debug(pocoLogItem.Message, pocoLogItem.Details);
                 break;
             case LogLevel.Info:
                 logger.Info(pocoLogItem.Message, pocoLogItem.Details);
                 break;
             case LogLevel.Warning:
                 logger.Warn(pocoLogItem.Message, pocoLogItem.Details);
                 break;
             case LogLevel.Error:
                 logger.Error(pocoLogItem.Message, pocoLogItem.Details);
                 break;
             case LogLevel.Fatal:
                 logger.Fatal(pocoLogItem.Message, new Exception(pocoLogItem.Details));
                 break;
         }
     }
 }
 protected override void Log(ILogger logger, Exception exception, string format, params object[] args)
 {
     logger.Fatal(exception, format, args);
 }
Exemple #15
0
 /// <summary>
 /// Log message with info level.
 /// </summary>
 /// <param name="initiator"></param>
 /// <param name="code"></param>
 /// <param name="message"></param>
 /// <param name="referenceId"></param>
 /// <param name="data"></param>
 public void Fatal(string initiator, string code, string message, string referenceId = null, object data = null)
 {
     mLogger?.Fatal(mManager.Log(initiator, code, message, referenceId, data));
 }
        private static void ProcessFile(string file, Func<string, bool> assemblyVersionCondition, IList<Assembly> assemblyList, ILogger logger)
        {
            try
            {
                logger.Info(string.Format(CultureInfo.InvariantCulture, "GACAssemblyLocator filename match! Loading assembly {0}.", file));
                Assembly a = Assembly.LoadFile(file);

                if (assemblyVersionCondition != null)
                {
                    if (assemblyVersionCondition(a.FullName))
                    {
                        assemblyList.Add(a);
                    }
                }
                else
                {
                    // If no condition is specified, accept DLLs from all versions
                    assemblyList.Add(a);
                }
            }
            catch (Exception error)
            {
                logger.Fatal(string.Format(CultureInfo.InvariantCulture, "GACAssemblyLocator failed to load assembly (file {0}). Error: {1}", file, error.ToString()));
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultContainer"/> class.
        /// </summary>
        public DefaultContainer()
            : base()
        {
            // 初始化日志系统的相关组件
            try {
                if (loggerFactory == null) throw new Exception("日志对象没有被初始化");
                IConfigurationInterpreter interpreter = new XmlInterpreter();
                interpreter.ProcessResource(interpreter.Source, Kernel.ConfigurationStore);
                this.Kernel.AddComponentInstance("logger", typeof(ILoggerFactory), loggerFactory);
                logger = loggerFactory.CreateLogger<DefaultContainer>("Framework");
            }
            catch (Exception ex) {
                System.Diagnostics.EventLog.WriteEntry("Framework", "日志启动错误:" + ex.Message, System.Diagnostics.EventLogEntryType.Error);
                throw;
            }

            // 加载服务器端的服务
            try {
                string filename = FileUtility.ConvertToFullPath(@"Uniframework.config");
                logger.Info("开始加载注册表服务");
                this.Kernel.AddComponentInstance("configService", typeof(IConfigurationService), new XMLConfigurationService(filename));

                logger.Info("开始加载嵌入式对象数据库服务");
                AddComponent("ObjectDatabaseService", typeof(IDb4oDatabaseService), typeof(Db4oDatabaseService));

                logger.Info("开始加载事件分发服务");
                AddFacility("eventautowiring", new EventAutoWiringFacility());

                logger.Info("开始加载会话管理服务");
                AddComponent("SessionService", typeof(ISessionService), typeof(SessionService));

                logger.Info("开始加载系统管理服务");
                AddFacility("System.Facility", new SystemFacility());

                logger.Info("开始加载客户端初始化服务");
                AddComponent("InitializeService", typeof(IInitializeService), typeof(InitializeService));

                logger.Info("开始加载远程调用服务");
                AddComponent("DefaultServiceCaller", typeof(IServiceCaller), typeof(DefaultServiceCaller));

                CheckBuiltInService(); // 对远程服务及远程方法进行注入处理

                AbstractExtend[] loadedExtends = LoadFrameworkExtends();

                string[] customServices = LoadFrameworkComponents();

                object[] components = ActivatingComponents();

                WiringEvent();

                foreach (AbstractExtend extend in loadedExtends) {
                    extend.LoadFinished(components);
                }

                logger.Info("开始加载应用服务器网关");
                AddComponent("ServiceGateway", typeof(ServiceGateway));

                systemReady = true;
                logger.Info("应用服务器启动完成");
            }
            catch (Exception ex) {
                logger.Fatal("注册组件时发生错误", ex);
            }
        }
Exemple #18
0
 private static void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
 {
     _logger?.Fatal("", e.Exception);
 }
Exemple #19
0
        /// <summary>
        /// Reads a single <see cref="Chunk"/> from the file.
        /// </summary>
        /// <returns>The parsed <see cref="Chunk"/> -or- <see langword="null"/> if the end of the file has been reached.</returns>
        /// <exception cref="IOException">An I/O error occurred.</exception>
        /// <exception cref="SmfDecoderException">The file is corrupt and/or cannot be decoded due to a fatal error.</exception>
        public Chunk ReadChunk()
        {
            var isEof = _source.BaseStream.Position >= _source.BaseStream.Length - 1;

            if (_ntrks == 0)
            {
                if (isEof)
                {
                    _logger?.Info(Strings.FinishedAtEnd, _source.BaseStream.Position);
                }
                else
                {
                    _logger?.Warn(Strings.FinishedBeforeEnd, _source.BaseStream.Position);
                }
                return(null);
            }
            if (isEof)
            {
                var msg = string.Format(Strings.UnexpectedEofTracks, _ntrks);
                _logger?.Fatal(msg, _source.BaseStream.Position);
                throw new SmfDecoderException(msg, _source.BaseStream.Position);
            }

            // Read id and length
            var id  = Encoding.ASCII.GetString(_source.ReadBytes(4));
            var len = MidiBytesConverter.ReadBigEndianUInt(_source.ReadBytes(4));

            // Begin decoding the data by chunk type
            switch (id)
            {
            case MidiHeader.HeaderIdentifier:
                if (_ntrks > -1)
                {
                    _logger?.Error(Strings.DuplicateHeader, _source.BaseStream.Position - 8);
                }
                var next = _source.BaseStream.Position + len;
                // Read the values
                var format = MidiBytesConverter.ReadBigEndianUShort(_source.ReadBytes(2));
                _ntrks = MidiBytesConverter.ReadBigEndianUShort(_source.ReadBytes(2));
                var div = MidiBytesConverter.ReadBigEndianShort(_source.ReadBytes(2));
                // Jump to next chunk if case the header is longer than 6 for some reason
                if (_source.BaseStream.Position < next)
                {
                    _logger?.Warn(Strings.WrongLength, _source.BaseStream.Position - 10);
                    _source.BaseStream.Position = next;
                }
                // Create the header chunk object, taking in to account the time division method used
                return(div < 0 ? new MidiHeader(format, (ushort)_ntrks, (sbyte)(div >> 8), (byte)(div & 0xFF)) : new MidiHeader(format, (ushort)_ntrks, div));

            case MidiTrack.TrackIdentifier:
                if (_ntrks == -1)
                {
                    _logger?.Warn(Strings.NoHeader, _source.BaseStream.Position - 8);
                }
                // Read all the events in the track and return the track
                return(new MidiTrack(ReadTrackEvents(len)));

            default:
                _logger?.Error(Strings.UnknownChunk, _source.BaseStream.Position - 8);
                return(new UnknownChunk(id, _source.ReadBytes((int)len)));
            }
        }
        public CollectorService(IEnumerable<string> work_on_this_users_only = null)
        {
            ServiceName = asc_mail_collection_service_name;
            EventLog.Log = "Application";

            // These Flags set whether or not to handle that specific
            // type of event. Set to true if you need it, false otherwise.
            CanHandlePowerEvent = false;
            CanHandleSessionChangeEvent = false;
            CanPauseAndContinue = false;
            CanShutdown = true;
            CanStop = true;
            try
            {
                _log = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Nlog, "CollectorService");

                _log.Info("Connecting to db...");

                _manager = new MailBoxManager(25, _log);

                var auth_error_warning_timeout =
                    ConfigurationManager.AppSettings["mail.AuthErrorSendWarningAlertTimeout"] != null
                        ? TimeSpan.FromSeconds(
                            Convert.ToInt32(ConfigurationManager.AppSettings["mail.AuthErrorSendWarningAlertTimeout"]))
                        : TimeSpan.FromHours(2);

                _manager.AuthErrorWarningTimeout = auth_error_warning_timeout;

                _log.Info("Auth login error warning timeout is {0}.", auth_error_warning_timeout.ToString());

                var auth_error_disable_mailbox_timeout =
                    ConfigurationManager.AppSettings["mail.AuthErrorDisableMailboxTimeout"] != null
                        ? TimeSpan.FromSeconds(
                            Convert.ToInt32(ConfigurationManager.AppSettings["mail.AuthErrorDisableMailboxTimeout"]))
                        : TimeSpan.FromDays(3);

                _log.Info("Auth login error disable mailbox timeout is {0}.", auth_error_disable_mailbox_timeout.ToString());

                _manager.AuthErrorDisableTimeout = auth_error_disable_mailbox_timeout;

                _log.Info("Creating collector service...");

                var handlers_log = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Nlog, "MessageHandlers");
                var queue_settings = MailQueueSettings.FromConfig;
                if (work_on_this_users_only != null)
                    queue_settings.WorkOnUsersOnly = work_on_this_users_only.ToList();
                else
                {
                    var user_to_work_on = ConfigurationManager.AppSettings["mail.OneUserMode"];
                    if (!string.IsNullOrEmpty(user_to_work_on))
                        queue_settings.WorkOnUsersOnly.Add(user_to_work_on);
                }

                _manager.TenantOverdueDays = queue_settings.OverdueDays;

                var handlers = MessageHandlersSettings.FromConfig(handlers_log, "mail");

                var enable_activity_log = ConfigurationManager.AppSettings["mail.EnableActivityLog"] == null || Convert.ToBoolean(ConfigurationManager.AppSettings["mail.EnableActivityLog"]);

                _manager.EnableActivityLog = enable_activity_log;

                _log.Info("Db aggregator activity log is {0}.", enable_activity_log ? "enabled" : "disabled");

                _collector = new Collector(_manager, queue_settings, handlers);

                _log.Info("Service is ready.");

                AggregatorLogger.Instance.Initialize(_manager, GetServiceIp());
                _log.Info("Aggregator logger initialized.");
            }
            catch (Exception ex)
            {
                _log.Fatal("CollectorService error under constuct: {0}", ex.ToString());
            }
        }
Exemple #21
0
 private static void UnhandledExceptionTrapper(object sender, UnhandledExceptionEventArgs eventArgs)
 {
     _logger.Fatal(eventArgs.ExceptionObject.ToString());
     //Environment.Exit(1);
 }
        //void SerialPortErrorReceived(object sender, SerialErrorReceivedEventArgs e)
        //{
        //    Debug.WriteLine($"SerialPort exception: {e.EventType.ToString()}");
        //    log.Error($"SerialPort Error: {e.EventType.ToString()}");
        //    //MessageDialog.ShowAsync($"SerialPort Error: {e.EventType.ToString()}", "TNC Connect Error", MessageBoxButton.OK);
        //    _serialPort.Close();
        //    return;
        //}

        //delegate void CloseDialogWindow(Window window);
        //void CloseWindow(Window window) => window.Close();

        //public void CloseDlgWindow(Window window)
        //{
        //    if ((window.Dispatcher.CheckAccess()))
        //    {
        //        window.Close();
        //    }
        //    else
        //    {
        //        window.Dispatcher.Invoke(DispatcherPriority.Normal, new CloseDialogWindow(CloseWindow), window);
        //    }
        //}

        public async Task <bool> BBSConnectThreadProcAsync()
        {
            _packetMessagesSent.Clear();
            _packetMessagesReceived.Clear();

            SerialDevice serialDevice = EventHandlerForDevice.Instance.Device;

            serialDevice.BaudRate    = (uint)_tncDevice.CommPort?.Baudrate;
            serialDevice.StopBits    = (SerialStopBitCount)_tncDevice.CommPort?.Stopbits;
            serialDevice.DataBits    = Convert.ToUInt16(_tncDevice.CommPort.Databits);
            serialDevice.Parity      = (SerialParity)_tncDevice.CommPort.Parity;
            serialDevice.Handshake   = (SerialHandshake)_tncDevice.CommPort.Flowcontrol;
            serialDevice.ReadTimeout = new TimeSpan(0, 0, 1);             // hours, min, sec
            //serialDevice.ReadTimeout = new TimeSpan(0, 0, 0); // hours, min, sec
            serialDevice.WriteTimeout = new TimeSpan(0, 0, 0);
            bool carrierDetectState         = serialDevice.CarrierDetectState;
            bool dataSetReadyState          = serialDevice.DataSetReadyState;
            bool breakSignalState           = serialDevice.BreakSignalState;
            bool isDataTerminalReadyEnabled = serialDevice.IsDataTerminalReadyEnabled;
            bool isRequestToSendEnabled     = serialDevice.IsRequestToSendEnabled;

            _serialPort = new SerialPort();


            //_serialPort.RtsEnable = _TncDevice.CommPort.Flowcontrol == _serialPort.Handshake.RequestToSend ? true : false;
            //_serialPort..ErrorReceived += new SerialErrorReceivedEventHandler(SerialPortErrorReceived);
            LogHelper(LogLevel.Info, "\n");
            LogHelper(LogLevel.Info, $"{DateTime.Now.ToString()}");
            LogHelper(LogLevel.Info, $"{_tncDevice.Name}: {serialDevice.PortName}, {serialDevice.BaudRate}, {serialDevice.DataBits}, {serialDevice.StopBits}, {serialDevice.Parity}, {serialDevice.Handshake}");
            try
            {
                _connectState = ConnectState.ConnectStateNone;

                string readText    = "";
                string readCmdText = "";

                try
                {
                    _connectState = ConnectState.ConnectStatePrepareTNCType;
                    if (_tncDevice.Name == "XSC_Kantronics_KPC3-Plus")
                    {
                        readCmdText = await KPC3PlusAsync();
                    }
                    else if (_tncDevice.Name == "XSC_Kenwood_TM-D710A" || _tncDevice.Name == "XSC_Kenwood_TH-D72A")
                    {
                        bool success = await KenwoodAsync();

                        if (!success)
                        {
                            throw new IOException();
                            //return false;
                        }
                    }
                    // Send Pre-Commands
                    string   preCommands     = _tncDevice.InitCommands.Precommands;
                    string[] preCommandLines = preCommands.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                    _connectState = ConnectState.ConnectStatePrepare;
                    foreach (string commandLine in preCommandLines)
                    {
                        await _serialPort.WriteAsync(commandLine + "\r\n");

                        //readText = await _serialPort.ReadLine();       // Read command
                        //log.Info(readCmdText + _TNCPrompt + readText);

                        readText = await _serialPort.ReadToAsync(_TNCPrompt);                                   // Result for command

                        //log.Info(readText);

                        //readCmdText = await _serialPort.ReadTo(_TNCPrompt);		// Next command
                    }
                }
                catch (Exception e)
                {
                    if (e is IOException)
                    {
                        await Utilities.ShowMessageDialogAsync("Looks like the USB cable to the TNC is disconnected, or the radio is off", "TNC Connect Error");

                        return(false);
                    }

                    LogHelper(LogLevel.Error, $"{e.Message}");
                    await Utilities.ShowMessageDialogAsync("Failed setting up the TNC");

                    return(false);
                }
                // Connect to JNOS
                TimeSpan readTimeout = _serialPort.ReadTimeout;
                _serialPort.ReadTimeout = new TimeSpan(0, 0, 0, 60, 0);
                BBSConnectTime          = DateTime.Now;
                _connectState           = ConnectState.ConnectStateBBSTryConnect;
                await _serialPort.WriteAsync("connect " + _messageBBS + "-1" + "\r\x05");

                //readText = await _serialPort.ReadLineAsync();        // Read command

                string readConnectText = await _serialPort.ReadLineAsync();                    // Read command response

                if (readConnectText.ToLower().Contains(_tncDevice.Prompts.Timeout.ToLower()))
                {
                    await Utilities.ShowMessageDialogAsync("Timeout connecting to the BBS.\nIs the BBS connect name and frequency correct?\nIs the antenna connected.\nThe BBS may be out of reach.", "BBS Connect Error");

                    goto Disconnect;
                }

                _connectState   = ConnectState.ConnectStateBBSConnected;
                readConnectText = await _serialPort.ReadToAsync(_BBSPrompt);                      // read connect response

                //Debug.WriteLine(readConnectText + _BBSPrompt);
                //log.Info(readText + "\n" + readConnectText + _BBSPrompt);
                _serialPort.ReadTimeout = readTimeout;

                // Test
                await _serialPort.WriteAsync("B\r\x05");               // Disconnect from BBS (JNOS)

                readText = await _serialPort.ReadToAsync(_TNCPrompt);

                //readText = await _serialPort.ReadTo(_BBSPrompt);    // Next command
                //Debug.WriteLine(readText + "\n");

                await _serialPort.WriteAsync("XM 0\r\x05");

                readText = await _serialPort.ReadToAsync(_BBSPrompt);                      // Read command

                //Debug.WriteLine(readText);
                //log.Info(readText);

                //readCmdText = await _serialPort.ReadLine();   // Read prompt
                //Debug.WriteLine(readCmdText);
                //log.Info(readCmdText);

                // Send messages
                foreach (PacketMessage packetMessage in _packetMessagesToSend)
                {
                    _error = true;
                    if (_error)
                    {
                        break;
                    }

                    if (packetMessage.BBSName == _messageBBS)
                    {
                        SendMessageAsync(packetMessage);
                        //_serialPort.ReadTimeout = new TimeSpan(0, 0, 4, 0, 0);
                        //try
                        //{
                        //	await _serialPort.Write("SP " + packetMessage.MessageTo + "\r");
                        //	await _serialPort.Write(packetMessage.MessageSubject + "\r");
                        //	await _serialPort.Write(packetMessage.MessageBody + "\r\x1a\r\x05");

                        //	readText = await _serialPort.ReadLine();       // Read SP
                        //	Debug.WriteLine(readText);
                        //	log.Info(readText);

                        //	readText = await _serialPort.ReadTo(") >");      // read response
                        //	Debug.WriteLine(readText + _BBSPrompt);
                        //	log.Info(readText + _BBSPrompt);

                        //	readText = await _serialPort.ReadTo("\n");         // Next command
                        //	Debug.WriteLine(readText + "\n");

                        //	packetMessage.MessageSentTime = DateTime.Now;
                        //	_packetMessagesSent.Add(packetMessage);
                        //}
                        //catch (Exception e)
                        //{
                        //	log.Error("Send message exception:", e);
                        //	//_serialPort.DiscardInBuffer();
                        //	//_serialPort.DiscardOutBuffer();
                        //	_error = true;
                        //}
                        //_serialPort.ReadTimeout = new TimeSpan(0, 0, 0, 5, 0);
                    }
                }

                if (!readConnectText.Contains("0 messages") && !_error)
                {
//					ReceiveMessages("");
                }

                if (_Areas != null && !_error)
                {
                    foreach (string area in _Areas)
                    {
//						ReceiveMessages(area);
                    }
                }
                //SendMessageReceipts();					// Send message receipts

                await _serialPort.WriteAsync("B\r\x05");                               // Disconnect from BBS (JNOS)

                //readText = await _serialPort.ReadLine();           // Read command
                //Debug.WriteLine(readText);
                //log.Info(readText);
Disconnect:
                //readText = await _serialPort.ReadLine();           // Read disconnect response
                //Debug.WriteLine(readText);
                //log.Info(readText);

                BBSDisconnectTime = DateTime.Now;
                //serialPort.Write(cmd, 0, 1);            // Ctrl-C to return to cmd mode. NOT for Kenwood

                SendMessageReceiptsAsync();                          // TODO testing

                _serialPort.ReadTimeout = new TimeSpan(0, 0, 0, 5, 0);
                readCmdText             = await _serialPort.ReadToAsync(_TNCPrompt);          // Next command

                //Debug.WriteLine(readCmdText + _TNCPrompt);

                // Send PostCommands
                string   postCommands     = _tncDevice.InitCommands.Postcommands;
                string[] postCommandLines = postCommands.Split(new char[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                _connectState = ConnectState.ConnectStatePost;
                foreach (string commandLine in postCommandLines)
                {
                    await _serialPort.WriteAsync(commandLine + "\r");

                    readText = await _serialPort.ReadLineAsync();                                  // Read command

                    //log.Info(readCmdText + _TNCPrompt + readText);

                    //readText = await _serialPort.ReadLine();              // Command result
                    //log.Info(readText);

                    readCmdText = await _serialPort.ReadToAsync(_TNCPrompt);                       // Next command
                }
                // Enter converse mode and send FCC call sign
                _connectState = ConnectState.ConnectStateConverseMode;
                await _serialPort.WriteAsync(_tncDevice.Commands.Conversmode + "\r");

                readText = await _serialPort.ReadLineAsync();                       // Read command

                //log.Info(readCmdText + _TNCPrompt + readText);

                string fccId = $"FCC Station ID = {Singleton<IdentityViewModel>.Instance.UserCallsign}";
                await _serialPort.WriteAsync(fccId + "\r");

                readText = await _serialPort.ReadLineAsync();

                //log.Info(readText);
                await _serialPort.WriteAsync("\x03\r");                                        // Ctrl-C exits converse mode

                readCmdText = await _serialPort.ReadToAsync(_TNCPrompt);

                //log.Info(readCmdText + _TNCPrompt);
            }
            catch (Exception e)
            {
                //Debug.WriteLineLine($"Serial port exception: {e.GetType().ToString()}");
                log.Error($"Serial port exception. Connect state: {Enum.Parse(typeof(ConnectState), _connectState.ToString())}.", e);
                if (_connectState == ConnectState.ConnectStateBBSTryConnect)
                {
                    //await _serialPort.Write("XM 0\r\x05");
                    await Utilities.ShowMessageDialogAsync("It appears that the radio is tuned to the wrong frequency,\nor the BBS was out of reach", "BBS Connect Error");

                    throw;
                }
                else if (_connectState == ConnectState.ConnectStatePrepareTNCType)
                {
                    //MessageDialog.Show("Unable to connect to the TNC.\nIs the TNC on?\nFor Kenwood; is the radio in \"packet12\" mode?", "BBS Connect Error", MessageBoxButton.OK);
                }
                else if (_connectState == ConnectState.ConnectStateConverseMode)
                {
                    await Utilities.ShowMessageDialogAsync($"Error sending FCC Identification - {Singleton<IdentityViewModel>.Instance.UserCallsign}.", "TNC Converse Error");
                }
                else if (_connectState == ConnectState.ConnectStateBBSConnected)
                {
                    await _serialPort.WriteAsync("B\r\x05");

                    log.Error("BBS Error Disconnect");
                }
                //else if (e.Message.Contains("not exist"))
                else if (e is IOException)
                {
                    await Utilities.ShowMessageDialogAsync("Looks like the USB cable to the TNC is disconnected, or the radio is off", "TNC Connect Error");
                }
                else if (e is UnauthorizedAccessException)
                {
                    await Utilities.ShowMessageDialogAsync($"The COM Port ({_tncDevice.CommPort.Comport}) is in use by another application. ", "TNC Connect Error");
                }
                else
                {
                    log.Fatal($"Connect state: {Enum.Parse(typeof(ConnectState), _connectState.ToString())} Exception: {e.Message}");
                }
                //_serialPort.Debug.WriteLine("B\r\n");
                await Utilities.ShowMessageDialogAsync("Failed to communicate with the TNC");

                return(false);
            }
            finally
            {
            }

            //CloseDlgWindow(ConnectDlg);
            return(true);
        }
Exemple #23
0
 public void Fatal(string message)
 {
     _writes.Fatal(_moduleName + message);
 }
 public void LogFatal(string message)
 {
     _logger.Fatal(message);
 }
Exemple #25
0
 public void Fatal(string message)
 {
     logger.Fatal(message);
 }
Exemple #26
0
 public void Fatal(string messageTemplate)
 {
     _logger.Fatal(messageTemplate);
 }
Exemple #27
0
 public void Fatal(string message, params object[] arguments)
 {
     _logger.Fatal(message, arguments);
 }
        public AggregatorService(IEnumerable<string> workOnThisUsersOnly = null)
        {
            ServiceName = AscMailCollectionServiceName;
            EventLog.Log = "Application";

            // These Flags set whether or not to handle that specific
            // type of event. Set to true if you need it, false otherwise.
            CanHandlePowerEvent = false;
            CanHandleSessionChangeEvent = false;
            CanPauseAndContinue = false;
            CanShutdown = true;
            CanStop = true;
            try
            {
                XmlConfigurator.Configure();

                _log = LoggerFactory.GetLogger(LoggerFactory.LoggerType.Log4Net, "MainThread");

                Environment.SetEnvironmentVariable("MONO_TLS_SESSION_CACHE_TIMEOUT", "0");

                _queueSettings = MailQueueSettings.FromConfig;
                
                if (workOnThisUsersOnly != null)
                    _queueSettings.WorkOnUsersOnly = workOnThisUsersOnly.ToList();
                else
                {
                    var userToWorkOn = ConfigurationManager.AppSettings["mail.OneUserMode"];
                    if (!string.IsNullOrEmpty(userToWorkOn))
                        _queueSettings.WorkOnUsersOnly.Add(userToWorkOn);
                }

                var authErrorWarningTimeout =
                    ConfigurationManager.AppSettings["mail.auth-error-warning-in-minutes"] != null
                        ? TimeSpan.FromMinutes(
                            Convert.ToInt32(ConfigurationManager.AppSettings["mail.auth-error-warning-in-minutes"]))
                        : TimeSpan.FromHours(1);

                _log.Info("Auth login error warning timeout is {0}.", authErrorWarningTimeout.ToString());

                var authErrorDisableMailboxTimeout =
                    ConfigurationManager.AppSettings["mail.auth-error-disable-mailbox-in-minutes"] != null
                        ? TimeSpan.FromMinutes(
                            Convert.ToInt32(ConfigurationManager.AppSettings["mail.auth-error-disable-mailbox-in-minutes"]))
                        : TimeSpan.FromDays(3);

                _log.Info("Auth login error disable mailbox timeout is {0}.", authErrorDisableMailboxTimeout.ToString());

                _log.Info("MailWorkerQueue: ConcurrentThreadCount = {0} and CheckInterval = {1} CheckPOP3_UIDL_Chunck = {2}",
                _queueSettings.ConcurrentThreadCount, _queueSettings.CheckInterval, _queueSettings.CheckPop3UidlChunk);

                var configBuilder = new TasksConfig.Builder();

                if (_queueSettings.WorkOnUsersOnly != null && _queueSettings.WorkOnUsersOnly.Any())
                {
                    var i = 0;
                    var users = string.Empty;
                    _queueSettings.WorkOnUsersOnly.ForEach(user => users += string.Format("\r\n\t\t\t\t{0}. \"{1}\"", ++i, user));

                    _log.Info("Aggregator will get tasks for this users only:" + users);
                }

                var queueLifetime = ConfigurationManager.AppSettings["mail.queue-lifetime-seconds"] != null
                        ? TimeSpan.FromSeconds(
                            Convert.ToInt32(ConfigurationManager.AppSettings["mail.queue-lifetime-seconds"]))
                        : TimeSpan.FromSeconds(30);

                var showActiveUpLogs = ConfigurationManager.AppSettings["mail.show-activeup-logs"] != null &&
                                       Convert.ToBoolean(
                                           ConfigurationManager.AppSettings["mail.show-activeup-logs"]);

                _tasksConfig = configBuilder.SetUsersToWorkOn(_queueSettings.WorkOnUsersOnly)
                                            .SetOnlyTeamlabTasks(_queueSettings.OnlyTeamlabTasks)
                                            .SetActiveInterval(_queueSettings.ActivityTimeout)
                                            .SetChunkOfPop3CheckUidLinDb(_queueSettings.CheckPop3UidlChunk)
                                            .SetEnableSignalr(_queueSettings.EnableSignalr)
                                            .SetMaxMessagesPerSession(_queueSettings.MaxMessagesPerSession)
                                            .SetMaxTasksAtOnce(_queueSettings.ConcurrentThreadCount)
                                            .SetQueueLifetime(queueLifetime)
                                            .SetTenantCachingPeriod(_queueSettings.TenantCachingPeriod)
                                            .SetShowActiveUpLogs(showActiveUpLogs)
                                            .SetInactiveMailboxesRatio(_queueSettings.InactiveMailboxesRatio)
                                            .SetAuthErrorWarningTimeout(authErrorWarningTimeout)
                                            .SetAuthErrorDisableMailboxTimeout(authErrorDisableMailboxTimeout)
                                            .Build();

                _tsInterval = _queueSettings.CheckInterval;

                _manager = new MailBoxManager(_log)
                {
                    AuthErrorWarningTimeout = _tasksConfig.AuthErrorWarningTimeout,
                    AuthErrorDisableTimeout = _tasksConfig.AuthErrorDisableMailboxTimeout
                };

                _queueManager = new QueueManager(_manager, _tasksConfig, _log);

                _resetEvent = new ManualResetEvent(false);

                _cancelTokenSource = new CancellationTokenSource();

                _lcts = new LimitedConcurrencyLevelTaskScheduler(_tasksConfig.MaxTasksAtOnce);

                _taskFactory = new TaskFactory(_lcts);

                _tsTaskStateCheckInterval = ConfigurationManager.AppSettings["mail.task-check-state-seconds"] != null
                        ? TimeSpan.FromSeconds(
                            Convert.ToInt32(ConfigurationManager.AppSettings["mail.task-check-state-seconds"]))
                        : TimeSpan.FromSeconds(30);

                if (ConfigurationManager.AppSettings["mail.default-api-scheme"] != null)
                {
                    var defaultApiScheme = ConfigurationManager.AppSettings["mail.default-api-scheme"];

                    ApiHelper.SetupScheme(defaultApiScheme);
                }

                _log.Info("Service is ready.");
            }
            catch (Exception ex)
            {
                _log.Fatal("CollectorService error under construct: {0}", ex.ToString());
            }
        }
Exemple #29
0
        protected virtual async Task ConsumeMessage(IMessageContext commandContext)
        {
            try
            {
                var             command      = commandContext.Message as ICommand;
                var             needReply    = !string.IsNullOrEmpty(commandContext.ReplyToEndPoint);
                var             sagaInfo     = commandContext.SagaInfo;
                IMessageContext messageReply = null;
                if (command == null)
                {
                    _internalConsumer.CommitOffset(commandContext);
                    return;
                }
                var needRetry = command.NeedRetry;

                using (var scope = IoCFactory.Instance.CurrentContainer.CreateChildContainer())
                {
                    scope.RegisterInstance(typeof(IMessageContext), commandContext);
                    var messageStore       = scope.Resolve <IMessageStore>();
                    var eventMessageStates = new List <MessageState>();
                    var commandHandledInfo = messageStore.GetCommandHandledInfo(commandContext.MessageID);
                    if (commandHandledInfo != null)
                    {
                        if (needReply)
                        {
                            messageReply = _messageQueueClient.WrapMessage(commandHandledInfo.Result,
                                                                           commandContext.MessageID,
                                                                           commandContext.ReplyToEndPoint, producer: Producer,
                                                                           messageId: ObjectId.GenerateNewId().ToString());
                            eventMessageStates.Add(new MessageState(messageReply));
                        }
                    }
                    else
                    {
                        var eventBus           = scope.Resolve <IEventBus>();
                        var messageHandlerType = _handlerProvider.GetHandlerTypes(command.GetType()).FirstOrDefault();
                        _logger?.InfoFormat("Handle command, commandID:{0}", commandContext.MessageID);

                        if (messageHandlerType == null)
                        {
                            _logger?.Debug($"command has no handlerTypes, message:{command.ToJson()}");
                            if (needReply)
                            {
                                messageReply = _messageQueueClient.WrapMessage(new NoHandlerExists(),
                                                                               commandContext.MessageID,
                                                                               commandContext.ReplyToEndPoint, producer: Producer);
                                eventMessageStates.Add(new MessageState(messageReply));
                            }
                        }
                        else
                        {
                            object messageHandler = null;
                            do
                            {
                                try
                                {
                                    if (messageHandler == null)
                                    {
                                        messageHandler = scope.Resolve(messageHandlerType.Type);
                                    }

                                    using (var transactionScope = new TransactionScope(TransactionScopeOption.Required,
                                                                                       new TransactionOptions {
                                        IsolationLevel = IsolationLevel.ReadCommitted
                                    },
                                                                                       TransactionScopeAsyncFlowOption.Enabled))
                                    {
                                        if (messageHandlerType.IsAsync)
                                        {
                                            await((dynamic)messageHandler).Handle((dynamic)command)
                                            .ConfigureAwait(false);
                                        }
                                        else
                                        {
                                            var handler = messageHandler;
                                            await Task.Run(() => { ((dynamic)handler).Handle((dynamic)command); }).ConfigureAwait(false);
                                        }
                                        if (needReply)
                                        {
                                            messageReply = _messageQueueClient.WrapMessage(commandContext.Reply,
                                                                                           commandContext.MessageID, commandContext.ReplyToEndPoint,
                                                                                           producer: Producer);
                                            eventMessageStates.Add(new MessageState(messageReply));
                                        }

                                        eventBus.GetEvents()
                                        .ForEach(@event =>
                                        {
                                            var topic        = @event.GetFormatTopic();
                                            var eventContext = _messageQueueClient.WrapMessage(@event,
                                                                                               commandContext.MessageID, topic, @event.Key,
                                                                                               sagaInfo: sagaInfo, producer: Producer);
                                            eventMessageStates.Add(new MessageState(eventContext));
                                        });

                                        eventBus.GetToPublishAnywayMessages()
                                        .ForEach(@event =>
                                        {
                                            var topic        = @event.GetFormatTopic();
                                            var eventContext = _messageQueueClient.WrapMessage(@event,
                                                                                               commandContext.MessageID, topic,
                                                                                               @event.Key, sagaInfo: sagaInfo, producer: Producer);
                                            eventMessageStates.Add(new MessageState(eventContext));
                                        });

                                        eventMessageStates.AddRange(GetSagaReplyMessageStates(sagaInfo, eventBus));

                                        messageStore.SaveCommand(commandContext, commandContext.Reply,
                                                                 eventMessageStates.Select(s => s.MessageContext).ToArray());
                                        transactionScope.Complete();
                                    }
                                    needRetry = false;
                                }
                                catch (Exception e)
                                {
                                    eventMessageStates.Clear();
                                    messageStore.Rollback();

                                    if (e is OptimisticConcurrencyException && needRetry)
                                    {
                                        eventBus.ClearMessages();
                                    }
                                    else
                                    {
                                        if (needReply)
                                        {
                                            messageReply = _messageQueueClient.WrapMessage(e.GetBaseException(),
                                                                                           commandContext.MessageID,
                                                                                           commandContext.ReplyToEndPoint,
                                                                                           producer: Producer,
                                                                                           messageId: ObjectId.GenerateNewId().ToString());
                                            eventMessageStates.Add(new MessageState(messageReply));
                                        }
                                        eventBus.GetToPublishAnywayMessages()
                                        .ForEach(@event =>
                                        {
                                            var topic        = @event.GetFormatTopic();
                                            var eventContext = _messageQueueClient.WrapMessage(@event,
                                                                                               commandContext.MessageID,
                                                                                               topic, @event.Key, sagaInfo: sagaInfo, producer: Producer);
                                            eventMessageStates.Add(new MessageState(eventContext));
                                        });
                                        if (e is DomainException exception)
                                        {
                                            var domainExceptionEvent = exception.DomainExceptionEvent;
                                            if (domainExceptionEvent != null)
                                            {
                                                var topic = domainExceptionEvent.GetFormatTopic();

                                                var exceptionMessage = _messageQueueClient.WrapMessage(domainExceptionEvent,
                                                                                                       commandContext.MessageID,
                                                                                                       topic,
                                                                                                       producer: Producer);
                                                eventMessageStates.Add(new MessageState(exceptionMessage));
                                            }
                                            _logger?.Warn(command.ToJson(), e);
                                        }
                                        else
                                        {
                                            _logger?.Error(command.ToJson(), e);
                                            //if we meet with unknown exception, we interrupt saga
                                            if (sagaInfo != null)
                                            {
                                                eventBus.FinishSaga(e);
                                            }
                                        }
                                        eventMessageStates.AddRange(GetSagaReplyMessageStates(sagaInfo, eventBus));
                                        messageStore.SaveFailedCommand(commandContext, e,
                                                                       eventMessageStates.Select(s => s.MessageContext).ToArray());
                                        needRetry = false;
                                    }
                                }
                            } while (needRetry);
                        }
                    }
                    if (eventMessageStates.Count > 0)
                    {
                        var sendTask = _messagePublisher.SendAsync(eventMessageStates.ToArray());
                        // we don't need to wait the send task complete here.
                    }
                }
            }
            catch (Exception ex)
            {
                _logger?.Fatal($"consume command failed", ex);
            }
            _internalConsumer.CommitOffset(commandContext);
        }
 public void Fatal(string message) => Logger.Fatal(message);
Exemple #31
0
 public static void Fatal(string message, Exception ex = null) => _logger?.Fatal(message, ex);
Exemple #32
0
        public void ProcessRequest(HttpContext context)
        {
            string mobile = context.Request["mobile"];
            string page   = context.Request["page"];
            string rows   = context.Request["rows"];

            logger.Info(string.Format("请求的参数:{0},{1},{2}", mobile, page, rows));
            try
            {
                if (string.IsNullOrEmpty(mobile) || string.IsNullOrEmpty(page) || string.IsNullOrEmpty(rows))
                {
                    context.Response.ContentType = "text/plain";
                    context.Response.Write("参数错误");
                }
                else
                {
                    DataTable         dt    = new DataTable();
                    string            sql   = @"SELECT 
                                  t.order_no orderno,
                                  t.create_time createtime,
                                  t.user_payed userpay,
                                  t.product_name productname,
                                  t.mobile,
                                  t.face,
                                  (case
                                    when t.refund_state <> 10 
                                    then t1.name 
                                    else t2.name end) status
                                    from (select RID
                                            from (select R.RID,ROWNUM LINENUM
                                                    from (select t.rowid RID from order_main t
                                                        where  
                                                        t.pay_status=0 and t.down_channel_no=107 and  
                                                        t.mobile =:Mobile 
                                                        order by t.create_time desc
                                                        ) R where ROWNUM <= :PS * :PI)
                                                    where LINENUM > :PS * (:PI - 1)) TAB1
                                    inner join order_main t on t.rowid = tab1.rid
                                    left join sys_dictionary t1 on t.refund_state = t1.value and t1.type = 'ReStatus'
                                    left join sys_dictionary t2 on t.order_status = t2.value and t2.type = 'OrderStatus' 
                                    order by t.create_time desc";
                    OracleParameter[] opams =
                    {
                        new OracleParameter(":Mobile", mobile),
                        new OracleParameter(":PS",     rows),
                        new OracleParameter(":PI",     page)
                    };
                    dt = SqlHelper.GetDataTable(sql, CommandType.Text, opams);
                    string ret = JsonConvert.SerializeObject(new { rows = dt }, new IsoDateTimeConverter()
                    {
                        DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
                    });
                    context.Response.ContentType = "text/plain";
                    context.Response.Write(ret);
                }
            }
            catch (Exception ex)
            {
                logger.Info(ex.Message);
                logger.Fatal(ex.Message, ex);
                context.Response.ContentType = "text/plain";
                context.Response.Write("Server Error");
            }
        }
Exemple #33
0
        private static void Main(string[] args)
        {
            _logger = LogFactory.GetLogger(typeof (Program));

            IDatabaseInitializer<CashRegisterContext> seed;

            // Empty
            // seed = new EmptyInitializer();

            // Kalle Seed
            //seed = new CashProductInitializer();

            // Lærke Seed
            seed = new FullProductInitializer();

            using (var contex = new CashRegisterContext(seed))
            {
                Console.WriteLine("FLAF");
                contex.Database.Initialize(true);
                contex.SaveChanges();
            }

            IDalFacade dalFacade = new DalFacade();
            IProductDao pd = new ProductDao(dalFacade);
            IProductController pc = new ProductController(pd);

            SalesOrder o;

            using (var uow = dalFacade.UnitOfWork)
            {
                var d = new Discount
                {
                    Description = "Discount",
                    Percent = 0,
                };
                uow.DiscountRepository.Insert(d);
                uow.Save();

                o = new SalesOrder
                {
                    Date = DateTime.Now,
                    Status = OrderStatus.Created,
                };
                uow.SalesOrderRepository.Insert(o);

            }
            using (var uow = dalFacade.UnitOfWork)
            {

                var t = new Transaction
                {
                    Date = DateTime.Now,
                    Description = "Flaf",
                    PaymentType = PaymentType.Cash,
                    Price = 20,
                    SalesOrder = o,
                    Status = TransactionStatus.Created
                };
                uow.TransactionRepository.Insert(t);
                uow.Save();
            }

                Console.WriteLine("ProductTabs");
            foreach (var productTab in pc.ProductTabs)
            {
                Console.WriteLine(productTab.Priority + ": " + productTab.Name);
                foreach (var productType in productTab.ProductTypes)
                {
                    Console.WriteLine("\t" + productType.Name);
                    foreach (var productGroup in productType.ProductGroups)
                    {
                        Console.WriteLine("\t\t" + productGroup.Name);
                        foreach (var product in productGroup.Products)
                        {
                            Console.WriteLine("\t\t\t" + product.Name);
                        }
                    }
                }
            }

            _logger.Fatal("Fatal");
            _logger.Err("Error");
            _logger.Warn("Warn");
            _logger.Info("Info");
            _logger.Debug("Debug");
        }
Exemple #34
0
        // ----

        public void Fatal(string messageTemplate)
        {
            innerLogger.Fatal(messageTemplate);
        }
        private async Task MigrateProjectPermissionsAsync(TableauProject sourceProject, TableauProject destProject)
        {
            _logger?.Debug($"Migrating permissions for project {sourceProject.Name}");

            var sourcePermissionService = _tableauServiceFactorySource.GetService <TableauPermissionService>();
            var destPermissionService   = _tableauServiceFactoryDest.GetService <TableauPermissionService>();
            var sourceUserService       = _tableauServiceFactorySource.GetService <TableauUserService>();
            var destUserService         = _tableauServiceFactoryDest.GetService <TableauUserService>();
            var sourceGroupService      = _tableauServiceFactorySource.GetService <TableauGroupService>();
            var destGroupService        = _tableauServiceFactoryDest.GetService <TableauGroupService>();

            var sourcePermissions = await sourcePermissionService.GetPermissionsAsync(
                ResourceType.Project, sourceProject.Id
                ).ConfigureAwait(false);

            // pre-load all destination groups to facilitate searching by name
            var destGroups = await destGroupService.GetGroupsAsync().ConfigureAwait(false);

            if (sourcePermissions.GranteeCapabilities == null)
            {
                _logger?.Debug("No granteee capabilities found");
                return;
            }

            foreach (var granteeCapability in sourcePermissions.GranteeCapabilities)
            {
                var destGranteeId   = "";
                var destGranteeName = "";
                if (granteeCapability.GranteeType == GranteeType.User)
                {
                    var sourceUser = await sourceUserService.GetUserAsync(
                        granteeCapability.GranteeId
                        ).ConfigureAwait(false);

                    var destUser = await destUserService.FindUserAsync(
                        sourceUser.Name, sourceUser.Domain?.Name
                        ).ConfigureAwait(false);

                    destGranteeId   = destUser.Id;
                    destGranteeName = destUser.UserPrincipalName;
                }
                else if (granteeCapability.GranteeType == GranteeType.Group)
                {
                    var sourceGroup = await sourceGroupService.GetGroupAsync(
                        granteeCapability.GranteeId
                        ).ConfigureAwait(false);

                    if (!destGroups.Any(g => g.Name.EqualsIgnoreCase(sourceGroup.Name)))
                    {
                        _logger?.Fatal($"Destination group not found: {sourceGroup.Name}");
                        throw new Exception($"Destination group not found: {sourceGroup.Name}");
                    }
                    var destGroup = destGroups.Single(g => g.Name.EqualsIgnoreCase(sourceGroup.Name));
                    destGranteeId   = destGroup.Id;
                    destGranteeName = destGroup.Name;
                }

                foreach (var capability in granteeCapability.Capabilities.Capability)
                {
                    _logger?.Debug(
                        String.Format(
                            "Adding permission for {0} {1}: {2} {3}",
                            granteeCapability.GranteeType.ToString(),
                            destGranteeName,
                            capability.Mode,
                            capability.Name
                            )
                        );

                    if (!_settingsMonitor.CurrentValue.DryRun)
                    {
                        await destPermissionService.AddCapabilityAsync(
                            ResourceType.Project,
                            destProject.Id,
                            granteeCapability.GranteeType,
                            destGranteeId,
                            (CapabilityName)Enum.Parse(typeof(CapabilityName), capability.Name, true),
                            (CapabilityMode)Enum.Parse(typeof(CapabilityMode), capability.Mode, true)
                            ).ConfigureAwait(false);

                        _logger?.Debug("Added permission");
                    }
                }
            }
        }
Exemple #36
0
 private void Fatal_Clicked(Object sender, EventArgs args)
 {
     logger.Fatal("Fatal Clicked");
 }
        protected async Task ConsumeMessage(IMessageContext eventContext)
        {
            try
            {
                _logger?.Debug($"start handle event {_consumerId} {eventContext.Message.ToJson()}");

                var message             = eventContext.Message;
                var sagaInfo            = eventContext.SagaInfo;
                var messageHandlerTypes = _handlerProvider.GetHandlerTypes(message.GetType());

                if (messageHandlerTypes.Count == 0)
                {
                    _logger?.Debug($"event has no handlerTypes, message:{message.ToJson()}");
                    _internalConsumer.CommitOffset(eventContext);
                    return;
                }

                //messageHandlerTypes.ForEach(messageHandlerType =>
                foreach (var messageHandlerType in messageHandlerTypes)
                {
                    using (var scope = IoCFactory.Instance.CurrentContainer.CreateChildContainer())
                    {
                        scope.RegisterInstance(typeof(IMessageContext), eventContext);
                        var messageStore     = scope.Resolve <IMessageStore>();
                        var subscriptionName = $"{_subscriptionName}.{messageHandlerType.Type.FullName}";
                        if (!messageStore.HasEventHandled(eventContext.MessageID, subscriptionName))
                        {
                            var eventMessageStates   = new List <MessageState>();
                            var commandMessageStates = new List <MessageState>();
                            var eventBus             = scope.Resolve <IEventBus>();
                            try
                            {
                                var messageHandler = scope.Resolve(messageHandlerType.Type);
                                using (var transactionScope = new TransactionScope(TransactionScopeOption.Required,
                                                                                   new TransactionOptions
                                {
                                    IsolationLevel = IsolationLevel.ReadCommitted
                                },
                                                                                   TransactionScopeAsyncFlowOption.Enabled))
                                {
                                    if (messageHandlerType.IsAsync)
                                    {
                                        await((dynamic)messageHandler).Handle((dynamic)message)
                                        .ConfigureAwait(false);
                                    }
                                    else
                                    {
                                        await Task.Run(() => { ((dynamic)messageHandler).Handle((dynamic)message); })
                                        .ConfigureAwait(false);
                                    }

                                    //get commands to be sent
                                    eventBus.GetCommands()
                                    .ForEach(cmd =>
                                             commandMessageStates.Add(new MessageState(_commandBus?.WrapCommand(cmd,
                                                                                                                sagaInfo: sagaInfo, producer: Producer)))
                                             );
                                    //get events to be published
                                    eventBus.GetEvents()
                                    .ForEach(msg =>
                                    {
                                        var topic = msg.GetFormatTopic();
                                        eventMessageStates.Add(new MessageState(_messageQueueClient.WrapMessage(msg,
                                                                                                                topic: topic,
                                                                                                                key: msg.Key, sagaInfo: sagaInfo, producer: Producer)));
                                    });

                                    eventBus.GetToPublishAnywayMessages()
                                    .ForEach(msg =>
                                    {
                                        var topic = msg.GetFormatTopic();
                                        eventMessageStates.Add(new MessageState(_messageQueueClient.WrapMessage(msg,
                                                                                                                topic: topic, key: msg.Key,
                                                                                                                sagaInfo: sagaInfo, producer: Producer)));
                                    });

                                    eventMessageStates.AddRange(GetSagaReplyMessageStates(sagaInfo, eventBus));

                                    messageStore.HandleEvent(eventContext,
                                                             subscriptionName,
                                                             commandMessageStates.Select(s => s.MessageContext),
                                                             eventMessageStates.Select(s => s.MessageContext));

                                    transactionScope.Complete();
                                }
                                if (commandMessageStates.Count > 0)
                                {
                                    _commandBus?.SendMessageStates(commandMessageStates);
                                }
                                if (eventMessageStates.Count > 0)
                                {
                                    _messagePublisher?.SendAsync(eventMessageStates.ToArray());
                                }
                            }
                            catch (Exception e)
                            {
                                eventMessageStates.Clear();
                                messageStore.Rollback();
                                if (e is DomainException)
                                {
                                    var domainExceptionEvent = ((DomainException)e).DomainExceptionEvent;
                                    if (domainExceptionEvent != null)
                                    {
                                        var topic            = domainExceptionEvent.GetFormatTopic();
                                        var exceptionMessage = _messageQueueClient.WrapMessage(domainExceptionEvent,
                                                                                               eventContext.MessageID,
                                                                                               topic,
                                                                                               producer: Producer);
                                        eventMessageStates.Add(new MessageState(exceptionMessage));
                                    }
                                    _logger?.Warn(message.ToJson(), e);
                                }
                                else
                                {
                                    //IO error or sytem Crash
                                    //if we meet with unknown exception, we interrupt saga
                                    if (sagaInfo != null)
                                    {
                                        eventBus.FinishSaga(e);
                                    }
                                    _logger?.Error(message.ToJson(), e);
                                }

                                eventBus.GetToPublishAnywayMessages()
                                .ForEach(msg =>
                                {
                                    var topic = msg.GetFormatTopic();
                                    eventMessageStates.Add(new MessageState(_messageQueueClient.WrapMessage(msg,
                                                                                                            topic: topic, key: msg.Key, sagaInfo: sagaInfo, producer: Producer)));
                                });

                                eventMessageStates.AddRange(GetSagaReplyMessageStates(sagaInfo, eventBus));

                                messageStore.SaveFailHandledEvent(eventContext, subscriptionName, e,
                                                                  eventMessageStates.Select(s => s.MessageContext).ToArray());
                                if (eventMessageStates.Count > 0)
                                {
                                    _messagePublisher?.SendAsync(eventMessageStates.ToArray());
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _logger?.Fatal($"Handle event failed event: {eventContext.ToJson()}", e);
            }
            _internalConsumer.CommitOffset(eventContext);
        }
        private static async Task Main(string[] args)
        {
            if (args == null || args.Length == 0)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("No configuration filename argument supplied. Cannot continue.");
                return;
            }

            InitialiseConfiguration(args);
            InitialiseLogging();

            try
            {
                // setup clients/references
                _cosmosClient       = new CosmosClient(_configuration["CosmosDB:Uri"], _configuration["CosmosDB:PrimaryKey"]);
                _blobServiceClient  = new BlobServiceClient(_configuration["Storage:ConnectionString"]);
                _database           = _cosmosClient.GetDatabase(_configuration["CosmosDB:DatabaseName"]);
                _imagesContainer    = _database.GetContainer(Constants.ImagesContainerName);
                _galleriesContainer = _database.GetContainer(Constants.GalleriesContainerName);
                _galleryId          = new DatabaseId();
                _httpClient         = new HttpClient {
                    BaseAddress = new Uri(_configuration["BaseUrl"])
                };

                // set the message queue listener
                var queueName = _configuration["Storage:ImageProcessingQueueName"];
                _queueClient = new QueueClient(_configuration["Storage:ConnectionString"], queueName);
                int.TryParse(_configuration["Storage:MessageBatchSize"], out var messageBatchSize);
                int.TryParse(_configuration["Storage:MessageBatchVisibilityTimeoutMins"], out var messageBatchVisibilityMins);
                if (!await _queueClient.ExistsAsync())
                {
                    _log.Fatal($"LB.PhotoGalleries.Worker.Program.Main() - {queueName} queue does not exist. Cannot continue.");
                    return;
                }

                if (!int.TryParse(_configuration["ZeroMessagesPollIntervalSeconds"], out var zeroMessagesPollIntervalSeconds))
                {
                    zeroMessagesPollIntervalSeconds = 5;
                }
                var delayTime         = TimeSpan.FromSeconds(zeroMessagesPollIntervalSeconds);
                var zeroMessagesCount = 0;

                // keep processing the queue until the program is shutdown
                while (true)
                {
                    // get a batch of messages from the queue to process
                    // getting a batch is more efficient as it minimises the number of HTTP calls we have to make to the queue
                    var messages = await _queueClient.ReceiveMessagesAsync(messageBatchSize, TimeSpan.FromMinutes(messageBatchVisibilityMins));

                    if (zeroMessagesCount < 2)
                    {
                        _log.Information($"LB.PhotoGalleries.Worker.Program.Main() - Received {messages.Value.Length} messages from the {queueName} queue ");
                    }

                    if (messages.Value.Length > 0)
                    {
                        // this is the fastest method of processing messages I have found so far. It's wrong I know to use async and block, but numbers don't lie.
                        Parallel.ForEach(messages.Value, message =>
                        {
                            HandleMessageAsync(message).GetAwaiter().GetResult();
                        });

                        // assign a gallery thumbnail if one is missing
                        await AssignGalleryThumbnailAsync();
                    }

                    // if we we received messages this iteration then there's a good chance there's more to process so don't pause between polls
                    // otherwise limit the rate we poll the queue and also don't log messages after a while
                    if (messages.Value.Length == 0)
                    {
                        if (zeroMessagesCount == 2)
                        {
                            _log.Information($"Stopping logging until we we receive messages again. Still polling the queue every {delayTime} seconds though");
                        }

                        zeroMessagesCount += 1;
                        await Task.Delay(delayTime);
                    }
                    else
                    {
                        zeroMessagesCount = 0;
                    }
                }
            }
            catch (Exception exception)
            {
                _log.Fatal(exception, "LB.PhotoGalleries.Worker.Program.Main() - Unhandled exception!");
            }
        }
 //use for testing purposes
 public static void LogAllLevelMessages(ILogger logger)
 {
     logger.Debug("Hey, are you a programmer? Logger.Name = " + logger.Name);
     logger.Info("Here's something interesting.");
     logger.Warn("Uh-oh, that's disturbing.");
     logger.Error("That was unexpected.");
     logger.Fatal("The roof is on fire!");
 }
Exemple #40
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, MimirContext db)
        {
            if (env.IsDevelopment())
            {
                log.Info("LittleC is a potato!");
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/error");
            }

            // Load logic configs.
            log.Info("Loading logic configs.");
            try
            {
                Program.ServerName = (from o in db.Options where o.Option == "ServerName" select o.Value).First();
                if ((from o in db.Options where o.Option == "PrivateKeyXml" select o.Value).First() == string.Empty)
                {
                    SignatureWorker.GenKey(db);
                }
                RSACryptoServiceProviderExtensions.FromXmlString(Program.PrivateKeyProvider,
                                                                 (from o in db.Options where o.Option == "PrivateKeyXml" select o.Value).First());
                Program.PublicKey    = (from o in db.Options where o.Option == "PublicKey" select o.Value).First();
                Program.ServerDomain = (from o in db.Options where o.Option == "ServerDomain" select o.Value).First();
                int.TryParse((from o in db.Options where o.Option == "SecurityLoginTryTimes" select o.Value).First(),
                             out Program.SecurityLoginTryTimes);
                bool.TryParse((from o in db.Options where o.Option == "IsEnableMultiProfiles" select o.Value).First(),
                              out Program.IsEnableMultiProfiles);
                int.TryParse((from o in db.Options where o.Option == "MaxTokensPerProfile" select o.Value).First(),
                             out Program.MaxTokensPerProfile);
                int.TryParse((from o in db.Options where o.Option == "TokensExpireDaysLimit" select o.Value).First(),
                             out Program.TokensExpireDaysLimit);
                long.TryParse((from o in db.Options where o.Option == "SessionsExpireSeconds" select o.Value).First(),
                              out Program.SessionsExpireSeconds);
                Program.SkinDomains = (from o in db.Options where o.Option == "SkinDomains" select o.Value).First().Split(",");
                int.TryParse((from o in db.Options where o.Option == "MaxProfileCountPerQuery" select o.Value).First(),
                             out Program.MaxProfileCountPerQuery);
                bool.TryParse((from o in db.Options where o.Option == "IsEnableLandingPage" select o.Value).First(),
                              out Program.IsEnableLandingPage);
                bool.TryParse((from o in db.Options where o.Option == "IsEnableSmtp" select o.Value).First(),
                              out Program.IsEnableSmtp);
                Program.SmtpDomain = (from o in db.Options where o.Option == "SmtpDomain" select o.Value).First();
                int.TryParse((from o in db.Options where o.Option == "SmtpPort" select o.Value).First(),
                             out Program.SmtpPort);
                Program.SmtpEmail    = (from o in db.Options where o.Option == "SmtpEmail" select o.Value).First();
                Program.SmtpName     = (from o in db.Options where o.Option == "SmtpName" select o.Value).First();
                Program.SmtpPassword = (from o in db.Options where o.Option == "SmtpPassword" select o.Value).First();
                bool.TryParse((from o in db.Options where o.Option == "SmtpIsSsl" select o.Value).First(),
                              out Program.SmtpIsSsl);
                int.TryParse((from o in db.Options where o.Option == "MaxProfileCountPerUser" select o.Value).First(),
                             out Program.MaxProfileCountPerUser);
                bool.TryParse((from o in db.Options where o.Option == "IsHttps" select o.Value).First(),
                              out Program.IsHttps);
            }
            catch (Exception)
            {
                log.Fatal("Bad database.");
                throw;
            }
            log.Info("Logic configs loaded.");

            app.UseSession();

            //app.UseHttpsRedirection();
            app.UseStaticFiles(new StaticFileOptions()
            {
                ServeUnknownFileTypes = true,
                DefaultContentType    = "image/png"
            });

            app.Use(next =>
            {
                return(async context =>
                {
                    context.Response.OnStarting(() =>
                    {
                        // Add ALI.
                        if (Program.IsHttps)
                        {
                            context.Response.Headers.Add("X-Authlib-Injector-API-Location", "https://" + Program.ServerDomain + "/api/");
                        }
                        else
                        {
                            context.Response.Headers.Add("X-Authlib-Injector-API-Location", "http://" + Program.ServerDomain + "/api/");
                        }

                        context.Response.Headers["Server"] = "Mimir";
                        context.Response.Headers.Add("Author", "Romonov");
                        return Task.CompletedTask;
                    });
                    await next(context);
                });
            });

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "yggdrasil_sessionserver_get_profile",
                    template: "api/sessionserver/session/minecraft/profile/{uuid}",
                    defaults: new { controller = "SessionServer", action = "Profile" });
                routes.MapRoute(
                    name: "yggdrasil_sessionserver_join",
                    template: "api/sessionserver/session/minecraft/join",
                    defaults: new { controller = "SessionServer", action = "Join" });
                routes.MapRoute(
                    name: "yggdrasil_sessionserver_has_joined",
                    template: "api/sessionserver/session/minecraft/hasJoined",
                    defaults: new { controller = "SessionServer", action = "HasJoined" });
                routes.MapRoute(
                    name: "yggdrasil_api_profiles_query",
                    template: "api/api/profiles/minecraft",
                    defaults: new { controller = "Api", action = "Profiles" });
                routes.MapRoute(
                    name: "yggdrasil_authserver",
                    template: "api/authserver/{action}",
                    defaults: new { controller = "AuthServer" });
                routes.MapRoute(
                    name: "yggdrasil_index",
                    template: "api",
                    defaults: new { controller = "Api", action = "Index" });
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Index}/{action=Index}/{id?}");
            });
        }
Exemple #41
0
        public T Save <T>(T t) where T : PandaObject
        {
            if (t != null)
            {
                if (t.IsValid())
                {
                    int userid = Util.CurrentIdentityId;

                    if (userid > 0)
                    {
                        User user = Util.CurrentIdentity;

                        using (ISession session = SessionFactory.OpenSession())
                        {
                            using (ITransaction trans = session.BeginTransaction())
                            {
                                if ((user.DeletedDate == null ||
                                     user.DeletedUser == null ||
                                     user.IsActive == false))
                                {
                                    if (t.Id > 0)
                                    {
                                        if (t.DeletedDate == null) // If its a forward request from delete
                                        {
                                            logger.Info(String.Format("Attempting to update type {0} Id {1}", typeof(T), t.Id));
                                            t.ModifiedUser = user;
                                            t.ModifiedDate = DateTime.UtcNow;
                                        }
                                        else
                                        {
                                            logger.Info(String.Format("Attempting to Deleting type {0} Id {1}", typeof(T), t.Id));
                                            t.DeletedUser = user;
                                        }

                                        session.SaveOrUpdate(t);
                                        logger.Info(String.Format("Update complete for type {0} Id {1}", typeof(T), t.Id));
                                    }
                                    else
                                    {
                                        logger.Info(String.Format("Attempting to create type {0}", typeof(T)));
                                        t.CreatedDate = DateTime.UtcNow;
                                        t.CreatedUser = user;

                                        session.Save(t);

                                        logger.Info(String.Format("Create complete for type {0} assigned Id {1}", typeof(T), t.Id));
                                    }
                                }
                                else
                                {
                                    logger.Fatal(String.Format("Invalid User : User Id Provided was {0} ", userid)
                                                 , new UnauthorizedAccessException(
                                                     String.Format("Unauthorized access by userid {0}", userid)));

                                    throw new Exception("User is not valid");
                                }

                                trans.Commit();
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("Invalid user authentication");
                    }
                }
                else
                {
                    var valresult = t.Validate();
                    throw new ValidationException("Invalid Object : VALIDATION ERROR ", valresult);
                }
            }
            else
            {
                throw new Exception("Null object, Invalid object state");
            }

            return(t);
        }
 protected override void Log(ILogger logger, string format, params object[] args)
 {
     logger.Fatal(format, args);
 }