public void GuardarArticulo(string contenido, string titulo)
 {
     _logging.Info($"vamos a insertar el articulo {titulo}");
     _almacenamiento.Guardar(titulo, contenido);
     _logging.Info($"articulo {titulo} insertado");
     _cache.Add(titulo, contenido);
 }
Exemple #2
0
        public void Subscribe(string channelName)
        {
            using (var redisClient = new RedisClient(_connection.Url, _connection.Port))
                using (_subscription = redisClient.CreateSubscription())
                {
                    _subscription.OnSubscribe = channel =>
                    {
                        _logging.Info(String.Format("Redis Started Listening On to '{0}'", channel));
                    };
                    _subscription.OnUnSubscribe = channel =>
                    {
                        _logging.Info(String.Format("Redis UnSubscribed from '{0}'", channel));
                        redisClient.UnSubscribe();
                    };
                    _subscription.OnMessage = (channel, msg) =>
                    {
                        _logging.Info(String.Format("Received '{0}' from channel '{1}'", msg, channel));

                        MessageReceiveEventArgs receivedMsg = new Util.MessageReceiveEventArgs(msg);
                        OnMessageReceivedEventHandler(this, receivedMsg);
                    };

                    if (OnSubscribeDoneEventHandler != null)
                    {
                        SubscribeDoneEventArgs subscribeDoneEventMsg = new SubscribeDoneEventArgs(true);
                        OnSubscribeDoneEventHandler(this, subscribeDoneEventMsg);
                    }

                    _subscription.SubscribeToChannels(channelName); //blocking
                }
        }
Exemple #3
0
 public void Start()
 {
     try
     {
         Logger.Info($"Starting http server on port {Port} serving from {rootDirectory}");
         listener.Start();
         while (true)
         {
             try
             {
                 abort = false;
                 Logger.Info($"Waiting for a request...");
                 var context = listener.GetContext();
                 Process(context);
             }
             catch (Exception ex)
             {
                 Logger.Error(ex);
                 break;
             }
         }
     }
     catch (Exception ex)
     {
         Logger.Error(ex);
     }
 }
Exemple #4
0
        private void OnExit(object sender, EventArgs e)
        {
            _tray.Dispose();
            Application.Exit();

            _logger.Info("Closing application...");
            ShowApplication();
            Task.Run(() =>
            {
                Thread.Sleep(1500);
                _closeApplicationFn();
            });
        }
Exemple #5
0
        private Message <string, string> publishAsync(string channel, string key, object message)
        {
            var messageJson = JsonConvert.SerializeObject(message);

            _logging.Info(String.Format("Publishing '{0}' to '{1}' using '{2}'", messageJson, channel, MessageBrokerEnum.Kafka));
            return(_producer.ProduceAsync(channel, key, messageJson).Result);
        }
        /*============================================================================*/
        /* Private Functions                                                           */
        /*============================================================================*/

        private void HandleContextView(object contextView)
        {
            if (_contextView != null)
            {
                return;
            }
            IContextView castContextView = contextView as IContextView;

            if (castContextView == null)
            {
                return;
            }

            _contextView = castContextView;

            if (_contextViewStateWatcher != null)
            {
                _logger.Warn("A IViewStateWatcher on the context view has already been set");
                return;
            }

            if (!_context.injector.HasDirectMapping(typeof(IViewStateWatcher)))
            {
                _logger.Info("No ViewStateWatcherExtension has been found yet. We will check again at the end of the contextview Configuration");
                _context.AddConfigHandler(new InstanceOfMatcher(typeof(IContextView)), HandleViewStateWatcher);
                return;
            }
            else
            {
                HandleViewStateWatcher(_context.injector.GetInstance(typeof(IViewStateWatcher)));
            }
        }
Exemple #7
0
        private long publish(string channel, object message)
        {
            var messageJson = JsonConvert.SerializeObject(message);

            _logging.Info(String.Format("Publishing '{0}' to '{1}' using '{2}'", messageJson, channel, MessageBrokerEnum.Redis));
            return(_redis.PublishMessage(channel, messageJson));
        }
Exemple #8
0
        private IEnumerable <BcrLine> RunBcr(IEnumerable <Report> reports)
        {
            var bag = new ConcurrentBag <BcrLine>();

            var extraReportsToRun = new ConcurrentBag <Report>();

            Parallel.ForEach(
                reports,
                new ParallelOptions {
                MaxDegreeOfParallelism = 3
            },
                t =>
            {
                try
                {
                    var bcrLines = RunBcr(t);
                    foreach (var line in bcrLines)
                    {
                        bag.Add(line);
                    }
                }
                catch (Exception)
                {
                    if (t.ShouldFallBack)
                    {
                        var fallbackReports = t.FallbackReports().ToList();
                        _log.Info(
                            string.Format(
                                "Error getting BCR for {0}. Will fallback to {1}:{2}",
                                t.Parameter,
                                string.Join(
                                    Environment.NewLine,
                                    fallbackReports.Select(x => x.Parameter).ToArray()),
                                Environment.NewLine));
                        fallbackReports.ForEach(r => extraReportsToRun.Add(r));
                    }
                }
            });

            if (extraReportsToRun.Any())
            {
                return(bag.Concat(RunBcr(extraReportsToRun)));
            }

            return(bag);
        }
Exemple #9
0
        private void publishAsync(string channel, object message, IBasicProperties props)
        {
            var jsonString = JsonConvert.SerializeObject(message);
            var body       = Encoding.UTF8.GetBytes(jsonString);

            _logging.Info(String.Format("Publishing '{0}' to '{1}' using '{2}'", jsonString, channel, MessageBrokerEnum.RabbitMQ));
            _rabbitChannel.QueueDeclare(channel, true, false, false, null);
            _rabbitChannel.BasicPublish(string.Empty, channel, props, body);
        }
        public virtual void TestSetLoggingLevel()
        {
            IList    methodsCalled = SetRootInterceptor();
            ILogging logger        = Logger.Get(typeof(LoggingTestCase.ITestLogger));

            Logger.LoggingLevel(Logger.Debug);
            ((LoggingTestCase.ITestLogger)logger.Trace()).Msg();
            ((LoggingTestCase.ITestLogger)logger.Debug()).Msg();
            ((LoggingTestCase.ITestLogger)logger.Info()).Msg();
            Assert.AreEqual(Pair.Of(Logger.Debug, "msg"), ((Pair)PopFirst(methodsCalled)));
            Assert.AreEqual(Pair.Of(Logger.Info, "msg"), ((Pair)PopFirst(methodsCalled)));
            logger.LoggingLevel(Logger.Info);
            ((LoggingTestCase.ITestLogger)logger.Debug()).Msg();
            ((LoggingTestCase.ITestLogger)logger.Info()).Msg();
            ((LoggingTestCase.ITestLogger)logger.Error()).Msg();
            Assert.AreEqual(Pair.Of(Logger.Info, "msg"), ((Pair)PopFirst(methodsCalled)));
            Assert.AreEqual(Pair.Of(Logger.Error, "msg"), ((Pair)PopFirst(methodsCalled)));
        }
Exemple #11
0
        public static void Main(string[] args)
        {
            SetupApplicationExceptionHandling();

            Logger.Info($"Activating {AppNAme} ...");
            _windowsTray = new WindowsTray("Game Mutex Killer", Logger, CloseApplication);
            _windowsTray.RunConsoleInBackground(() =>
            {
                Logger.Info($"{AppNAme} activated");
                _mutexKiller = new MutexKiller(Logger);
                _mutexKiller.StartKilling();
            });



            Console.ReadLine();
            CloseApplication();
        }
Exemple #12
0
        public bool DeleteJob(Guid jobCorrelationId)
        {
            if (jobCorrelationId == Guid.Empty)
            {
                throw new ArgumentOutOfRangeException(nameof(jobCorrelationId), "Specified jobCorrelationId is invalid");
            }

            var res = _repository.DeleteJob(jobCorrelationId);

            if (res)
            {
                _logging.Info($"Job {jobCorrelationId} deleted");
            }
            else
            {
                _logging.Warn($"Failed to delete job {jobCorrelationId}");
            }
            return(res);
        }
 public void KillMutex()
 {
     foreach (var mutex in _mutexList)
     {
         var lockKillResult = _handleWrapper.KillLock(mutex);
         if (lockKillResult.Any() && lockKillResult.All(l => l))
         {
             _logger.Info($"Killed lock for {mutex}");
         }
     }
 }
Exemple #14
0
 public void Execute()
 {
     logger.Info("Loaded scene {0}", evt.Scene.name);
     switch (evt.Scene.name)
     {
     case SceneNames.GAME:
         scoreModel.ResetScore();
         dispatcher.Dispatch(new SoundEvent(SoundEvent.Type.PLAY_MUSIC_TRACK, "game"));
         break;
     }
 }
Exemple #15
0
        public Guid CreateNew(HardSubtitlesJobRequestModel input)
        {
            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }

            var res = HandleNewHardSubtitlesxJob(input);

            _logging.Info($"Created new hard sub job : {res}");
            return(res);
        }
Exemple #16
0
        public void Run()
        {
            _output.Write("Bitte eine Zahl eingeben: ");
            var n1 = _input.ReadInt();

            _output.Write("Bitte eine zweite Zahl eingeben: ");
            var n2 = _input.ReadInt();

            _logging.Info("Es wird die Summe aus {n1} und {n2} berechnet.");

            var sum = _calculator.Add(n1, n2);

            _output.Write($"Summe: {sum}\n");
        }
Exemple #17
0
 public void Start()
 {
     Logger.Info($"Starting http server on port {Port} serving from {rootDirectory}");
     listener.Start();
     while (true)
     {
         abort = false;
         Logger.Info($"Waiting for a request...");
         var context = listener.GetContext();
         var thread  = new Thread(p => Process((HttpListenerContext)p));
         thread.Start(context);
     }
 }
        public void Configure()
        {
            mediatorMap.Map <ILanguageView>().ToMediator <LanguageMediator>();
            mediatorMap.Map <ICurrentLanguageView>().ToMediator <CurrentLanguageMediator>();
            mediatorMap.Map <IChangeLanguageView>().ToMediator <ChangeLanguageMediator>();
            commandMap.Map(LanguageRequestEvent.Type.REQUEST_CONTENT).ToCommand <RequestTextCommand>();
            commandMap.Map(LanguageRequestEvent.Type.REQUEST_CURRENT_LANGUAGE).ToCommand <RequestTextCommand>();
            commandMap.Map(LanguageEvent.Type.CHANGE_LANGUAGE).ToCommand <ChangeLanguageCommand>();
            commandMap.Map(LanguageEvent.Type.CHANGE_LANGUAGE).ToCommand <SaveLanguageCommand>();

            string language;

            if (saveService.LanguageName == null)
            {
                language = Enum.GetName(typeof(SystemLanguage), Application.systemLanguage);
                logger.Info("Setting System Language: {0}", language);
            }
            else
            {
                language = saveService.LanguageName;
                logger.Info("Loading Saved Language: {0}", language);
            }
            model.SetCurrentLanguage(language);
        }
Exemple #19
0
    public static void UpdateIndexFromFilesInFolder(SPath template, SPath indexPath, SPath path)
    {
        var runTask = UpdateIndexFromFilesInFolderTask(path, indexPath, template);

        runTask
        .FinallyInUI((success, ex) => {
            if (!success)
            {
                logger.Error(ex);
            }
            logger.Info($"Index updated with result: {success}");
            EditorUtility.ClearProgressBar();
        })
        .Start();
    }
Exemple #20
0
        public void Execute()
        {
            // Entry point into the command

            // Logger outputs to console
            logger.Info("Command Incrementing Count");

            // We access the model from the injected value
            model.IncrementCount();

            // Sends off an event to the global event dispatcher with a payload
            // This event can then trigger other commands and be heard from mediators
            dispatcher.Dispatch(new CountUpdatedEvent(CountUpdatedEvent.Type.VALUE_CHANGED, model.Count));

            // After execute is finished commands are disposed
        }
 private void Modified(string source)
 {
     if (!IsReady)
     {
         return;
     }
     IsPersistent = true;
     foreach (var g in m_grids)
     {
         Logger.Info("Mark {0} for saving.  Source: {1}", g.CustomName, source);
         g.Save                     = true;
         g.OnGridChanged           -= OnGridChanged;
         g.OnBlockAdded            -= OnBlockAdded;
         g.OnBlockIntegrityChanged -= OnBlockIntegrityChanged;
         g.OnBlockRemoved          -= OnBlockRemoved;
     }
 }
Exemple #22
0
        /// <summary>
        /// Deletes all users. This function only works in "Development"
        /// environment.
        /// </summary>
        public async Task DeleteAllUsers()
        {
            int  _rowsAffected = 0;
            bool _isValid      = true;
            var  _errorTitle   = "UserManagementApi:DeleteAllUsers";
            var  env           = _env.GetUserVariable("Environment");

            //is Development?
            if (!env.Equals("Development"))
            {
                ResponseError_ModelView(_errorTitle, "No Connection to db was found");
                _isValid = false;
            }

            //Connection String
            if (string.IsNullOrWhiteSpace(ConnectionString))
            {
                ResponseError_ModelView(_errorTitle, "No Connection to db was found");
                _isValid = false;
            }

            await Task.Run(() =>
            {
                try
                {
                    if (_isValid)
                    {
                        using (IDbConnection db = new SqlConnection(ConnectionString))
                        {
                            if (db.State == ConnectionState.Closed)
                            {
                                db.Open();
                            }

                            _rowsAffected = db.Execute(SqlQueries.DeleteAllUsers_Sql);
                            _logging.Info(_errorTitle, $"Users Rows Deleted {_rowsAffected}");
                        }
                    }
                }
                catch (Exception ex)
                {
                    _logging.Error(_errorTitle, ex.ToString());
                }
            });
        }
        public void Subscribe(string channel)
        {
            using (var connection = _connectionFactory.CreateConnection())
                using (_channelMq = connection.CreateModel())
                {
                    cancelled = false;

                    _channelMq.QueueDeclare(channel, true, false, false, null);

                    var consumer = new EventingBasicConsumer(_channelMq);
                    EventHandler <BasicDeliverEventArgs> queueMsgReceived = (model, ea) =>
                    {
                        var body    = ea.Body;
                        var message = Encoding.UTF8.GetString(body);
                        _logging.Info("Rabbit Received {0}", message);

                        MessageReceiveEventArgs receivedMsg = new Util.MessageReceiveEventArgs(message);
                        OnMessageReceivedEventHandler(this, receivedMsg);
                    };
                    consumer.Received += queueMsgReceived;
                    string c = _channelMq.BasicConsume(channel, true, consumer);

                    Console.CancelKeyPress += (_, e) =>
                    {
                        e.Cancel  = true; // prevent the process from terminating.
                        cancelled = true;
                    };

                    if (OnSubscribeDoneEventHandler != null)
                    {
                        SubscribeDoneEventArgs subscribeDoneEventMsg = new SubscribeDoneEventArgs(true);
                        OnSubscribeDoneEventHandler(this, subscribeDoneEventMsg);
                    }

                    while (!cancelled)
                    {
                        Thread.Sleep(TimeSpan.FromMilliseconds(10));
                    }

                    consumer.Received -= queueMsgReceived;
                }
        }
        /// <exception cref="System.Security.SecurityException"></exception>
        /// <exception cref="System.MissingMethodException"></exception>
        public virtual void TestPrintWriterLogger()
        {
            ByteArrayOutputStream        bout        = new ByteArrayOutputStream();
            PrintWriterLoggerInterceptor interceptor = new PrintWriterLoggerInterceptor(new PrintWriter
                                                                                            (bout, true));

            Logger.Intercept(interceptor);
            ILogging logger = Logger.Get(typeof(LoggingTestCase.ITestLogger));

            ((LoggingTestCase.ITestLogger)logger.Debug()).Msg();
            ((LoggingTestCase.ITestLogger)logger.Info()).Msg();
            string actual   = Platform4.AsUtf8(bout.ToByteArray());
            string debugMsg = PrintWriterLoggerInterceptor.FormatMessage(Logger.Debug, "msg",
                                                                         null);
            string infoMsg = PrintWriterLoggerInterceptor.FormatMessage(Logger.Info, "msg", null
                                                                        );

            Assert.IsTrue((actual.IndexOf(debugMsg) >= 0));
            Assert.IsTrue((actual.IndexOf(infoMsg) >= 0));
        }
Exemple #25
0
        public TranscodingJobState UpdateProgress(TaskProgressModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            if (!ModelState.IsValid)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState));
            }
            if (model.Failed)
            {
                _logging.Warn($"Task {model.Id} failed at {model.MachineName}");
            }
            if (model.Done)
            {
                _logging.Info($"Task {model.Id} done at {model.MachineName}");
            }
            return(_repository.SaveProgress(model.Id, model.Failed, model.Done, model.Progress, model.VerifyProgress, model.MachineName));
        }
        public async void Execute(string text)
        {
            var info = parser.Deserialize <AppInfo>(text);

            if (info.EnableLogging == 0)
            {
//                log.Level = LoggingLevel.OFF;
            }
            log.Trace(">>>>>>>>> INIT APP");
            localization.Add(info.Localization);

            var parameters = UriExtentsions.GetParams(platform.URL);

            if (platform.IsEditor)
            {
                settings.ExerciseId = info.DefaultExercise;
                settings.Mode       = settings.Mode ?? info.DefaultMode;
            }
            else if (!parameters.ContainsKey(RunnerConsts.IS_LOCAL))
            {
                settings.BasePath = info.BasePath;
            }

            platform.AntiAliasing  = GetAA(parameters, info.AntiAliasing);
            platform.EnableLogging = info.EnableLogging;

            var startedAt = info.StartedAt;
            var startTime = DateTimeOffset.FromUnixTimeSeconds(startedAt);

            var span = DateTime.UtcNow - startTime;

            log.Info("+++++++++++++++++++++++++++++++++++++++++ Time to start the unity app: " + span);

            var bundles = info.Bundles;
            await loadBundle.Execute(bundles);

            log.Trace(">>>>>>>>> ON ENGINE READY");
            sender.OnEngineReady();
        }
Exemple #27
0
        public void Subscribe(string channel)
        {
            using (_consumerKafka =
                       new Consumer <Null, string>(constructConfig(_brokerList, true, new Guid().ToString()), null, new StringDeserializer(Encoding.UTF8)))
            {
                // Note: All event handlers are called on the main thread.

                _consumerKafka.OnMessage += (_, msg)
                                            =>
                {
                    _logging.Info($"Executor ID : {_executorID} Topic: {msg.Topic} Partition: {msg.Partition} Offset: {msg.Offset} {msg.Value}");

                    MessageReceiveEventArgs receivedMsg = new Util.MessageReceiveEventArgs(msg.Value);
                    OnMessageReceivedEventHandler(this, receivedMsg);
                };

                _consumerKafka.Subscribe(channel);

                if (OnSubscribeDoneEventHandler != null)
                {
                    SubscribeDoneEventArgs subscribeDoneEventMsg = new SubscribeDoneEventArgs(true);
                    OnSubscribeDoneEventHandler(this, subscribeDoneEventMsg);
                }


                var cancelled = false;
                Console.CancelKeyPress += (_, e) =>
                {
                    e.Cancel  = true; // prevent the process from terminating.
                    cancelled = true;
                };

                while (!cancelled)
                {
                    _consumerKafka.Poll(TimeSpan.FromMilliseconds(10));
                }
            }
        }
 public IContext AddChild(IContext child)
 {
     if (!_children.Contains(child))
     {
         _logger.Info("Adding child context {0}", new object[] { child });
         if (!child.Uninitialized)
         {
             _logger.Warn("Child context {0} must be uninitialized", new object[] { child });
         }
         if (child.injector.parent != null)
         {
             _logger.Warn("Child context {0} must not have a parent Injector", new object[] { child });
         }
         _children.Add(child);
         child.injector.parent = injector;
         child.POST_DESTROY   += OnChildDestroy;
     }
     return(this);
 }
Exemple #29
0
 public void extension_does_NOT_throw_for_INFO()
 {
     logger.Info("");
 }
Exemple #30
0
 public void Info(string message, params object[] args)
 {
     logger?.Info(string.Format(message, args));
 }