Exemplo n.º 1
0
        public static void Start()
        {
            log.Warn("ENTRO  SchedulerSubasta START");

            MvcApplication.scheduler = StdSchedulerFactory.GetDefaultScheduler();
            MvcApplication.scheduler.Start();

            IJobDetail job     = JobBuilder.Create <FinalizarTarea>().Build();
            int        minutos = 0;

            if (DateTime.Now.Minute == 60)
            {
                minutos = 1;
            }
            else
            {
                minutos = DateTime.Now.Minute + 1;
            }

            ITrigger trigger = TriggerBuilder.Create()
                               .WithDailyTimeIntervalSchedule
                                   (s =>
                                   s.WithIntervalInMinutes(1)
                                   .OnEveryDay()
                                   .StartingDailyAt(TimeOfDay.HourAndMinuteOfDay(DateTime.Now.Hour, minutos))
                                   )
                               .Build();

            MvcApplication.scheduler.ScheduleJob(job, trigger);
            log.Warn("ENTRO  SchedulerSubasta START");
            //scheduler.ScheduleJob(job, trigger);
        }
Exemplo n.º 2
0
 public void Warn(string message)
 {
     if (!string.IsNullOrEmpty(message))
     {
         _loggerError.Warn(message);
     }
 }
Exemplo n.º 3
0
 /// <summary>
 /// 发布警告信息
 /// </summary>
 /// <param name="message"></param>
 /// <param name="exception"></param>
 public void Warn(object message, Exception exception)
 {
     if (log.IsWarnEnabled)
     {
         log.Warn(message, exception);
     }
 }
Exemplo n.º 4
0
        void ILog.Log(LogLevel level, Exception exception, object message)
        {
            switch (level)
            {
            case LogLevel.Debug:
                _inner.Debug(message, exception);
                break;

            case LogLevel.Info:
                _inner.Info(message, exception);
                break;

            case LogLevel.Warn:
                _inner.Warn(message, exception);
                break;

            case LogLevel.Error:
                _inner.Error(message, exception);
                break;

            case LogLevel.Fatal:
                _inner.Fatal(message, exception);
                break;

            default:
                throw new ArgumentOutOfRangeException("level");
            }
        }
Exemplo n.º 5
0
 public void Warn(object message)
 {
     if (IsWarnEnabled)
     {
         log.Warn(message);
     }
 }
Exemplo n.º 6
0
        public void Log(string level, string message)
        {
            try
            {
                switch (level)
                {
                case "Info":
                    logger.Info(message);
                    break;

                case "Warn":
                    logger.Warn(message);
                    break;

                case "Error":
                    logger.Error(message);
                    break;

                case "Fatal":
                    logger.Fatal(message);
                    break;

                case "Debug":
                    logger.Debug(message);
                    break;

                default:
                    logger.Info(message);
                    break;
                }
            }
            catch {
                throw new NotImplementedException();
            }
        }
Exemplo n.º 7
0
 /// <summary>
 /// 警告
 /// </summary>
 public static void Warn(string message)
 {
     if (log.IsWarnEnabled)
     {
         log.Warn(message);
     }
 }
Exemplo n.º 8
0
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("log4net!");


        //我们会以类(class)的类型(type)为参数来调用GetLogger(),
        //以便跟踪我们正在进行日志记录的类。传递的类(class)的类型(type)可以用typeof(Classname)方法来获得
        // log4net.ILog log = log4net.LogManager.GetLogger(typeof(log4Net));

        //也可以通过反射获得
        log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        log.Error("log4net error", new Exception("在这里发生了一个error异常!"));
        log.Fatal("log4net  fatal", new Exception("在发生了一个致命fatal错误"));
        log.Info("log4net info 提示:系统正在运行");
        log.Debug("log4net 调试信息:debug");
        log.Warn("log4net 警告:warn");

        int n = 0;

        for (n = 1; n <= 10; n++)
        {
            if (n % 2 == 0)
            {
                string s = n.ToString();
                log.Info(s + "为偶数");
            }
            else
            {
                string s = n.ToString();
                log.Warn(s + "为奇数");
            }
        }
    }
Exemplo n.º 9
0
        public void WriteLog(int tipo, Object mensaje)
        {
            log4net.GlobalContext.Properties["mensaje"] = "Exepcion Mensaje";
            try
            {
                if (tipo == 0)
                {
                    log.Debug(mensaje);
                }
                if (tipo == 1)
                {
                    log.Warn(mensaje);
                }
                if (tipo == 2)
                {
                    log.Error(mensaje);
                }

                if (tipo == 3)
                {
                    log.Fatal(mensaje);
                }
            }
            catch (Exception ex) {
                throw ex;
            }
        }
Exemplo n.º 10
0
 /// <summary>
 /// 警告
 /// </summary>
 /// <param name="Message"></param>
 public static void WarnInfo(string Message)
 {
     if (!log.IsWarnEnabled)
     {
         SetConfig();
     }
     log.Warn(Message);
 }
Exemplo n.º 11
0
        /// <summary>
        /// Creates an instance object. This shouldn't be used directly - Please use WorldMgr.CreateInstance
        /// to create an instance.
        /// </summary>
        public BaseInstance(ushort ID, GameTimer.TimeManager time, RegionData data) : base(time, data)
        {
            m_regionID = ID;
            m_skinID   = data.Id;

            //Notify we've created an instance.
            log.Warn("An instance is created! " + Name + ", RegionID: " + ID + ", SkinID: " + Skin);
        }
Exemplo n.º 12
0
 private void _listener_MessageNotProcessing(object sender, MessageProcessEventArgs e)
 {
     if (e.Message != null)
     {
         _logger.Warn($"MessageNotProcessing status:{e.Status} , message: {e.Message}");
     }
     else
     {
         _logger.Warn($"MessageNotProcessing status:{e.Status} , message: null");
     }
 }
Exemplo n.º 13
0
 public void Warn(string format, params object[] arg)
 {
     if (arg == null || arg.Length == 0)
     {
         logger.Warn(format);
     }
     else
     {
         logger.Warn(string.Format(format, arg));
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// When an applied effect starts
        /// duration spells only
        /// </summary>
        /// <param name="effect"></param>
        public override void OnEffectStart(GameSpellEffect effect)
        {
            base.OnEffectStart(effect);

            GamePlayer player = Caster as GamePlayer;
            GameNPC    npc    = effect.Owner as GameNPC;

            if (player != null && npc != null)
            {
                if (m_controlledBrain == null)
                {
                    m_controlledBrain = new ControlledNpcBrain(player);
                }

                if (!m_isBrainSet)
                {
                    npc.AddBrain(m_controlledBrain);
                    m_isBrainSet = true;

                    GameEventMgr.AddHandler(npc, GameLivingEvent.PetReleased, new DOLEventHandler(ReleaseEventHandler));
                }

                if (player.ControlledBrain != m_controlledBrain)
                {
                    // sorc: "The slough serpent is enthralled!" ct_spell
                    Message.SystemToArea(effect.Owner, Util.MakeSentence(Spell.Message1, npc.GetName(0, false)), eChatType.CT_Spell);
                    MessageToCaster(npc.GetName(0, true) + " is now under your control.", eChatType.CT_Spell);

                    player.SetControlledBrain(m_controlledBrain);

                    foreach (GamePlayer ply in npc.GetPlayersInRadius(WorldMgr.VISIBILITY_DISTANCE))
                    {
                        ply.Out.SendNPCCreate(npc);
                        if (npc.Inventory != null)
                        {
                            ply.Out.SendLivingEquipmentUpdate(npc);
                        }

                        ply.Out.SendObjectGuildID(npc, player.Guild);
                    }
                }
            }
            else
            {
                // something went wrong.
                if (log.IsWarnEnabled)
                {
                    log.Warn(string.Format("charm effect start: Caster={0} effect.Owner={1}",
                                           (Caster == null ? "(null)" : Caster.GetType().ToString()),
                                           (effect.Owner == null ? "(null)" : effect.Owner.GetType().ToString())));
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="index"></param>
        /// <param name="dataGridViewRow"></param>
        /// <returns></returns>
        public int InsertAt(int index, OfferBookGridRow dataGridViewRow)
        {
            int _ret = 0;

            try
            {
                if (this.grouped)
                {
                    int pos;
                    //lock (this.Rows)
                    lock (syncRoot)
                    {
                        pos = ValidatePosition(index, ref dataGridViewRow);

                        if (pos > 0)
                        {
                            this.Rows.Insert(pos, dataGridViewRow);
                        }
                        else
                        {
                            this.Rows.Insert(1, dataGridViewRow);
                        }
                        _ret = pos;
                    }
                }
                else
                {
                    //Workaround: the broadcasting service is sending the signal even after the cancellation.
                    //We must make sure that the list is empty after cancellation
                    if (index <= this.Rows.Count + 1)
                    {
                        //lock (this.Rows)
                        lock (syncRoot)
                        {
                            this.Rows.Insert(index, dataGridViewRow);
                            _ret = index;
                        }
                    }
                }
            }
            catch (ArgumentOutOfRangeException outOfRangeEx)
            {
                logger.Warn(String.Format("OfferBookGrid > InsertAt({0}): a posição {1} de {2} do livro (Agrupado:{3}) não existe mais ({4}).", this.Stock, index, this.RowCount, this.grouped, outOfRangeEx.Message));
            }
            catch (Exception ex)
            {
                //AplicacaoGeral.ReportarErro("OfferBookGrid > InsertAt", ex + " | " + index.ToString() + " | " + this.RowCount.ToString() + " | " + this.grouped.ToString());
                logger.ErrorFormat("Exception [{0}] [{1}] [{2}] [{3}]", ex, index, this.RowCount, this.grouped);
            }

            return(_ret);
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

            log.Warn("Hi There");
            log.WarnFormat("Hi There {0}", "Jeff");
            log.Warn(new { Hi = 2, Lo = "string", Complex = new { ComplicatedObject = true } });

            log.Error("Boom", GenerateException());
            log.Error(GenerateAggregateException());

            System.Console.ReadKey();
        }
Exemplo n.º 17
0
        /// <inheritdoc />
        /// <overloads>
        /// <inheritdoc />
        /// </overloads>
                #pragma warning restore 1573
        public override void Write
        (
            LogLevel logLevel,
            string message,
            [CallerMemberName]
            string callerMemberName = "",
            [CallerFilePath]
            string callerFilePath = "",
            [CallerLineNumber]
            int callerLineNumber = 0
        )
        {
            if (IgnoreLogLevel(logLevel))
            {
                return;
            }

            if (message == null)
            {
                return;
            }

            SetCallerContext(callerMemberName, callerFilePath, callerLineNumber.ToString());

            if (logLevel == LogLevel.Trace)
            {
                _log.Debug(message);
            }
            else if (logLevel == LogLevel.Debug)
            {
                _log.Debug(message);
            }
            else if (logLevel == LogLevel.Info)
            {
                _log.Info(message);
            }
            else if (logLevel == LogLevel.Warn)
            {
                _log.Warn(message);
            }
            else if (logLevel == LogLevel.Error)
            {
                _log.Error(message);
            }
            else if (logLevel == LogLevel.Fatal)
            {
                _log.Fatal(message);
            }

            SetCallerContext(null, null, null);
        }
Exemplo n.º 18
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // CHAT
            //RouteTable.Routes.MapHubs();
            // QUARTZ.NET TAREAS
            log.Warn("ANTES DE SchedulerSubasta");
            //SchedulerMail.Start();
            SchedulerSubasta.Start();
            log.Warn("DESPUES DE SchedulerSubasta");
        }
        /// <summary>
        /// Creates a new GameInventoryItem based on an
        /// InventoryTemplateID. Will disappear after 3 minutes if
        /// added to the world
        /// </summary>
        /// <param name="templateID">the templateID to load and create an item</param>
        /// <returns>Found item or null</returns>
        public static WorldInventoryItem CreateFromTemplate(string templateID)
        {
            ItemTemplate template = GameServer.Database.FindObjectByKey <ItemTemplate>(templateID);

            if (template == null)
            {
                if (log.IsWarnEnabled)
                {
                    log.Warn("Item Creation: Template not found!\n" + Environment.StackTrace);
                }
                return(null);
            }

            return(CreateFromTemplate(template));
        }
Exemplo n.º 20
0
 public static void Warn(System.Type type, object message)
 {
     logger = LogManager.GetLogger(type);
     if (!logger.Logger.Repository.Configured)
         XmlConfigurator.ConfigureAndWatch(new System.IO.FileInfo(GetConfigFile() + ".config"));
     logger.Warn(message);
 }
Exemplo n.º 21
0
 public static void Warn(string message, Exception ex, ILog log)
 {
     if (log.IsWarnEnabled)
     {
         log.Warn(message, ex);
     }
 }
Exemplo n.º 22
0
        /// <summary>
        /// 格式化输出异常信息
        /// </summary>
        /// <param name="level"></param>
        /// <param name="message"></param>
        /// <param name="exception"></param>
        private void Log(LoggerLevel level, string message, Exception exception)
        {
            switch (level)
            {
            case LoggerLevel.Debug:
                _Logger4net.Debug(message, exception);
                break;

            case LoggerLevel.Info:
                _Logger4net.Info(message, exception);
                break;

            case LoggerLevel.Warn:
                _Logger4net.Warn(message, exception);
                break;

            case LoggerLevel.Error:
                _Logger4net.Error(message, exception);
                break;

            case LoggerLevel.Fatal:
                _Logger4net.Fatal(message, exception);
                break;
            }
        }
Exemplo n.º 23
0
        private IFieldDataPlugin GetSinglePluginOrThrow()
        {
            var directory = new DirectoryInfo(Context.AssemblyFolder);

            var plugins = new List <IFieldDataPlugin>();

            foreach (var file in directory.GetFiles("*.dll"))
            {
                var assembly = LoadAssembly(file.FullName, message => Log.Warn($"Skipping '{file.FullName}': {message}"));

                if (assembly == null)
                {
                    continue;
                }

                plugins.AddRange(FindAllPluginImplementations(assembly));
            }

            if (plugins.Count > 1)
            {
                throw new ExpectedException(
                          $"'{Context.AssemblyFolder}' contains multiple IFieldDataPlugin implementations. You'll need to explicitly specify an /{nameof(Context.AssemblyPath)} option.");
            }

            if (plugins.Count != 1)
            {
                throw new ExpectedException($"Can't find any IFieldDataPlugin implementations in '{Context.AssemblyFolder}'.");
            }

            return(plugins.Single());
        }
Exemplo n.º 24
0
 public void Warn(Func <string> message)
 {
     if (_logger.IsWarnEnabled)
     {
         _logger.Warn(decorate_message_with_audit_information(message.Invoke().escape_curly_braces()));
     }
 }
Exemplo n.º 25
0
        /// <summary>
        /// Creates and summons the djinn if it isn't already up.
        /// </summary>
        /// <param name="player"></param>
        /// <returns></returns>
        public override bool Interact(GamePlayer player)
        {
            if (!base.Interact(player))
            {
                return(false);
            }

            if (Djinn == null)
            {
                try
                {
                    Djinn = new SummonedDjinn(this);
                }
                catch (Exception e)
                {
                    log.Warn(String.Format("Unable to create ancient bound djinn: {0}", e.Message));
                    return(false);
                }
            }

            if (!Djinn.IsSummoned)
            {
                Djinn.Summon();
            }

            return(true);
        }
Exemplo n.º 26
0
        public string SqlFunc(string stmt)
        {
            MySqlConnection dbConn = GetConn();

            try
            {
                MySqlCommand myCommand = dbConn.CreateCommand();
                myCommand.CommandText = stmt;
                object retVal = myCommand.ExecuteScalar();
                if (log.IsDebugEnabled)
                {
                    log.Debug(stmt);
                }
                if (retVal != null && retVal.ToString() == "System.Byte[]")
                {
                    log.Warn("cast error: " + stmt);
                }
                return(retVal == null ? "" : retVal.ToString());
            }
            catch (Exception e)
            {
                log.Error(e.Message + " " + stmt);
                return("");
            }
            finally
            {
                if (pooled)
                {
                    dbConn.Close();
                }
            }
        }
Exemplo n.º 27
0
 /// <summary>
 /// Used for logging some abnormal information which you think the application should not be go this rule.
 /// For example, in the ApplyLeave method, the input parameter Employee should not be null.  But it is really null you could have a log here.
 /// </summary>
 /// <param name="s"></param>
 public static void Warn(object s)
 {
     if (WarnLog.IsWarnEnabled)
     {
         WarnLog.Warn(s);
     }
 }
Exemplo n.º 28
0
        /// <summary>
        /// Reads the Alias file and creates a AliasItem containg the information read
        /// </summary>
        /// <param name="path">Path to the Alias file</param>
        /// <returns>A AliasItem containg the information from the Alias file</returns>
        /// <remarks>
        /// If the alias file do not have a language specified in the name then the
        /// default language specified in the settings will be used
        /// </remarks>
        public object Handle(string path, DatabaseLogger logger)
        {
            string fileName    = System.IO.Path.GetFileNameWithoutExtension(path);
            int    splittIndex = fileName.IndexOf('_');

            AliasItem alias = new AliasItem();

            if (splittIndex < 0)
            {
                //No underscore in the file name use the default language
                alias.Language = Settings.Current.General.Language.DefaultLanguage;
            }
            else
            {
                alias.Language = fileName.Substring(splittIndex + 1);
            }
            try
            {
                alias.Alias = ReadAll(path);
            }
            catch (System.IO.IOException ex)
            {
                logger(new DatabaseMessage()
                {
                    MessageType = DatabaseMessage.BuilderMessageType.Error, Message = "Could not read file " + path
                });
                _logger.Warn(ex.ToString());
                return(null);
            }

            return(alias);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Fetches the list of servers and adds them to serverView's server collection
        /// </summary>
        public void fetchServers()
        {
            WebRequest  serverReq  = WebRequest.Create("http://kaillera.com/raw_server_list2.php?version=0.9");
            WebResponse serverResp = serverReq.GetResponse();

            using (StreamReader sr = new StreamReader(serverResp.GetResponseStream()))
            {
                while (!sr.EndOfStream)
                {
                    try
                    {
                        Server currServer = new Server();
                        currServer.name = sr.ReadLine();
                        string[] servInfo = sr.ReadLine().Split(';');
                        string[] ipPort   = servInfo[0].Split(':');
                        currServer.ip       = IPAddress.Parse(ipPort[0]);
                        currServer.port     = int.Parse(ipPort[1]);
                        currServer.users    = int.Parse(servInfo[1].Split('/')[0]);
                        currServer.numGames = int.Parse(servInfo[2]);
                        currServer.version  = servInfo[3];
                        currServer.location = servInfo[4];
                        addServers(currServer);
                    }
                    catch (Exception)
                    {
                        log.Warn("Invalid server detected!");
                    }
                }
            }
        }
Exemplo n.º 30
0
 public void warn(string message)
 {
     if (logWarn.IsWarnEnabled)
     {
         logWarn.Warn(message);
     }
 }
Exemplo n.º 31
0
        public static void Warn(string message)
        {
            StackFrame sf     = new StackFrame(1);
            string     Method = sf.GetMethod().ToString();

            log.Warn(Method + " " + message);
        }
Exemplo n.º 32
0
        /*
         * Removed this when we provided an overload for base.FormatMessage
         * that will return a message without any date time stamps
         * Josh & Mohamed
         * November 29, 2007
         */

        //private string RemovePrefixDate(string message)
        //{
        //    int amEndDateIndex = message.IndexOf("AM");
        //    int pmEndDateIndex = message.IndexOf("PM");

        //    amEndDateIndex += 2; pmEndDateIndex += 2;

        //    string amPrefix = message.Remove(amEndDateIndex);
        //    string pmPrefix = message.Remove(pmEndDateIndex);

        //    DateTime dateTime;
        //    if (DateTime.TryParse(amPrefix, out dateTime)) return message.Substring(amEndDateIndex);
        //    if (DateTime.TryParse(pmPrefix, out dateTime)) return message.Substring(pmEndDateIndex);

        //    return message;
        //}

        /// <summary>
        /// log message based on log level
        /// </summary>
        /// <param name="message"></param>
        /// <param name="e"></param>
        private void Log(string message, LogEventArgs e)
        {
            switch (e.LogLevel)
            {
            case LogLevel.Debug:
                _logger.Debug(message);
                break;

            case LogLevel.Error:
                _logger.Error(message);
                break;

            case LogLevel.Fatal:
                _logger.Fatal(message);
                break;

            case LogLevel.Info:
                _logger.Info(message);
                break;

            case LogLevel.Warning:
                _logger.Warn(message);
                break;

            default:
                throw new Exception("Unsupported log level.");
            }
        }
 public static void LogRestWarn(ILog logger, IRestResponse restResponse, string warnHeading)
 {
     if (logger != null && restResponse != null)
     {
         var stringBuilder = BuildLoggingString(restResponse, warnHeading);
         logger.Warn(stringBuilder.ToString());
     }
 }
Exemplo n.º 34
0
 internal static void LogMessages(ILog log)
 {
     log.Info("This is an info");
     log.InfoFormat("Base called at {0}", DateTime.Now);
     log.Debug("This is a debug");
     log.Warn("This is a warning");
     log.Error("This is an error");
 }
Exemplo n.º 35
0
        public TrajectoryPlotter(string inputDirectory, string inputFilenamePattern, string outputDirectory, string outputFilename, int width, int height, uint bailout)
        {
            _inputDirectory = inputDirectory;
            _inputFilenamePattern = inputFilenamePattern;
            _outputDirectory = outputDirectory;
            _outputFilename = outputFilename;
            _resolution = new Size(width, height);
            _bailout = bailout;

            _log = LogManager.GetLogger(GetType());

            if (width % 4 != 0)
            {
                _log.Warn("The width should be evenly divisible by 4");
            }
            if (height % 4 != 0)
            {
                _log.Warn("The height should be evenly divisible by 4");
            }

            _hitPlot = new HitPlot4x4(_resolution);
        }
Exemplo n.º 36
0
        public BeaglePlugin()
        {
            server = Daemon.Server;
            db = Daemon.DefaultDatabase;
            log = Daemon.Log;

            query = new Query ();
            query.AddDomain (QueryDomain.Neighborhood);
            query.MaxHits = 10000;

            QueryPart_Property filePart = new QueryPart_Property ();
            filePart.Type = PropertyType.Keyword;
            filePart.Key = "beagle:HitType";
            filePart.Value = "File";
            query.AddPart (filePart);

            QueryPart_Or queryUnion = new QueryPart_Or ();

            foreach (string mt in supportedMimeTypes) {
                QueryPart_Property part = new QueryPart_Property ();
                part.Type = PropertyType.Keyword;
                part.Key = "beagle:MimeType";
                part.Value = mt;
                queryUnion.Add (part);
            }

            query.AddPart (queryUnion);
            query.HitsAddedEvent += OnHitsAdded;
            query.HitsSubtractedEvent += OnHitsSubtracted;
            query.FinishedEvent += OnFinished;

            int attempts = 0;
            while (true) {
                try {
                    query.SendAsync ();
                    break;
                } catch (Exception e) {
                    if (attempts++ >= 5) {
                        log.Warn ("Failed to initialize beagle plugin");
                        query = null;
                        break;
                    }

                    // something bad happened, wait a sec and try again
                    log.Debug ("Sending query failed: " + e.Message);
                    log.Debug ("Waiting 3 seconds...");
                    Thread.Sleep (3000);
                }
            }
        }
Exemplo n.º 37
0
        /// <summary>
        /// Logs messages into the log output
        /// </summary>
        /// <param name="message">Message that is sent to the log ouput</param>
        /// <param name="level">Level of the message</param>
        /// <param name="prefix">Prefix of the log file. It is valid on for PackRollingFileAppender</param>
        public static void Log(string message, LogLevel level, LogFilePrefix prefix, bool throwException)
        {
            try
            {
                if (assembly == null)
                {
                    return;
                }

                log = LogManager.GetLogger(assembly, assembly.GetTypes()[0]);

                if (log == null)
                {
                    return;
                }

                   

                //Save additional information
                string logMessage = message + Environment.NewLine;
                ThreadContext.Properties[PrefixFileAppender.LOG_PREFIX] = prefix;

                switch (level)
                {
                    case LogLevel.Info:
                        log.Info(logMessage);
                        break;
                    case LogLevel.Debug:
                        log.Debug(logMessage);
                        break;
                    case LogLevel.Warn:
                        log.Warn(logMessage);
                        break;
                    case LogLevel.Error:
                        log.Error(logMessage);
                        break;
                    case LogLevel.Fatal:
                        log.Fatal(logMessage);
                        break;
                }
            }
            catch (Exception exc)
            {
                if (throwException)
                {
                    throw exc;
                }
            }
        }
Exemplo n.º 38
0
 public static void Write(string msg, LogLevel lv = LogLevel.INFO)
 {
     log4net.GlobalContext.Properties["LogName"] = string.Format("{0}.{1}.log", DateTime.Now.ToString("yyyy-MM-dd"), lv.ToString().ToLower());
     _Log = LogManager.GetLogger(typeof(LogHelper));
     switch (lv)
     {
         case LogLevel.ALL: _Log.Info(msg); break;
         case LogLevel.DEBUG: _Log.Debug(msg); break;
         case LogLevel.ERROR: _Log.Error(msg); break;
         case LogLevel.FATAL: _Log.Fatal(msg); break;
         case LogLevel.INFO: _Log.Info(msg); break;
         case LogLevel.WARN: _Log.Warn(msg); break;
         default:
             _Log.Info(msg); break;
     }
 }
Exemplo n.º 39
0
        /// <summary>
        /// Logs messages into the log output
        /// </summary>
        /// <param name="message">Message that is sent to the log ouput</param>
        /// <param name="level">Level of the message</param>
        /// <param name="prefix">Prefix of the log file. It is valid on for PackRollingFileAppender</param>
        public static void Log(string message, LogLevel level, LogFilePrefix prefix)
        {
            if (assembly == null)
            {
                return;
            }

            log = LogManager.GetLogger(assembly, assembly.GetTypes()[0]);

            ThreadContext.Properties[PackRollingFileAppender.HTTP_CONTEXT] = String.Empty;
            ThreadContext.Properties[PackRollingFileAppender.SESSION_VARS] = String.Empty;

            //Save additional information
            string logMessage = message + Environment.NewLine;
            if (level > LogLevel.Warn)
            {
                ThreadContext.Properties[PackRollingFileAppender.HTTP_CONTEXT] = AddHTTPContextInfo();
            }

            if (level > LogLevel.Debug)
            {
                ThreadContext.Properties[PackRollingFileAppender.SESSION_VARS] = SessionManager.ToString();
            }

            ThreadContext.Properties[PackRollingFileAppender.LOG_PREFIX] = prefix;

            switch (level)
            {
                case LogLevel.Info:
                    log.Info(logMessage);
                    break;
                case LogLevel.Debug:
                    log.Debug(logMessage);
                    break;
                case LogLevel.Warn:
                    log.Warn(logMessage);
                    break;
                case LogLevel.Error:
                    log.Error(logMessage);
                    break;
                case LogLevel.Fatal:
                    log.Fatal(logMessage);
                    break;
            }
        }
Exemplo n.º 40
0
        public bool SentAll(IEnumerable<IDistributedEventAggregator> eventAggregators, byte[] messageContent,
            TypeDescriptor descriptor)
        {
            Logger = LogManager.GetLogger(NomadConstants.NOMAD_LOGGER_REPOSITORY, typeof (BasicTopicDeliverySubsystem));

            foreach (IDistributedEventAggregator dea in eventAggregators)
            {
                try
                {
                    dea.OnPublish(messageContent, descriptor);
                }
                catch (Exception e)
                {
                    Logger.Warn(string.Format("Could not sent message '{0}' to DEA: {1}", descriptor, dea), e);
                }
            }

            // using the reliable mechanisms of WCF devlivery is always succesfull to all proper processes
            return true;
        }
Exemplo n.º 41
0
 public void Log(string message, LogLevel level, Type type)
 {
     _log = LogManager.GetLogger(type);
     switch (level)
     {
         case LogLevel.Info:
             _log.Info(message);
             break;
         case LogLevel.Debug:
             _log.Debug(message);
             break;
         case LogLevel.Warn:
             _log.Warn(message);
             break;
         case LogLevel.Fatal:
             _log.Fatal(message);
             break;
         case LogLevel.Error:
             _log.Error(message);
             break;
         default:
             throw new ArgumentOutOfRangeException("level");
     }
 }
 private void Log(ILog log, Log4NetAttribute.Levels level, string strText)
 {
     switch(level)
     {
         case Log4NetAttribute.Levels.DEBUG:
             log.Debug(strText);
             break;
         case Log4NetAttribute.Levels.ERROR:
             log.Error(strText);
             break;
         case Log4NetAttribute.Levels.FATAL:
             log.Fatal(strText);
             break;
         case Log4NetAttribute.Levels.INFO:
             log.Info(strText);
             break;
         case Log4NetAttribute.Levels.WARN:
             log.Warn(strText);
             break;
     }
 }
    public static string GetEmailAdressOrNull (AddressEntry addressEntry, IEntityMappingLogger logger, ILog generalLogger)
    {
      OlAddressEntryUserType type;

      if (addressEntry != null)
      {
        try
        {
          type = addressEntry.AddressEntryUserType;
        }
        catch (COMException ex)
        {
          generalLogger.Warn ("Could not get type from AddressEntry", ex);
          logger.LogMappingWarning ("Could not get type from AddressEntry", ex);
          return null;
        }
        if (type == OlAddressEntryUserType.olExchangeUserAddressEntry
            || type == OlAddressEntryUserType.olExchangeRemoteUserAddressEntry
            || type == OlAddressEntryUserType.olExchangeAgentAddressEntry
            || type == OlAddressEntryUserType.olExchangeOrganizationAddressEntry
            || type == OlAddressEntryUserType.olExchangePublicFolderAddressEntry)
        {
          try
          {
            using (var exchUser = GenericComObjectWrapper.Create (addressEntry.GetExchangeUser ()))
            {
              if (exchUser.Inner != null)
              {
                return exchUser.Inner.PrimarySmtpAddress;
              }
            }
          }
          catch (COMException ex)
          {
            generalLogger.Warn ("Could not get email address from adressEntry.GetExchangeUser()", ex);
            logger.LogMappingWarning ("Could not get email address from adressEntry.GetExchangeUser()", ex);
          }
        }
        else if (type == OlAddressEntryUserType.olExchangeDistributionListAddressEntry
                 || type == OlAddressEntryUserType.olOutlookDistributionListAddressEntry)
        {
          try
          {
            using (var exchDL = GenericComObjectWrapper.Create (addressEntry.GetExchangeDistributionList ()))
            {
              if (exchDL.Inner != null)
              {
                return exchDL.Inner.PrimarySmtpAddress;
              }
            }
          }
          catch (COMException ex)
          {
            generalLogger.Warn ("Could not get email address from adressEntry.GetExchangeDistributionList()", ex);
            logger.LogMappingWarning ("Could not get email address from adressEntry.GetExchangeDistributionList()", ex);
          }
        }
        else if (type == OlAddressEntryUserType.olSmtpAddressEntry
                 || type == OlAddressEntryUserType.olLdapAddressEntry)
        {
          return addressEntry.Address;
        }
        else if (type == OlAddressEntryUserType.olOutlookContactAddressEntry)
        {
          if (addressEntry.Type == "EX")
          {
            try
            {
              using (var exchContact = GenericComObjectWrapper.Create (addressEntry.GetContact ()))
              {
                if (exchContact.Inner != null)
                {
                  if (exchContact.Inner.Email1AddressType == "EX")
                  {
                    return exchContact.Inner.GetPropertySafe (PR_EMAIL1ADDRESS);
                  }
                  else
                  {
                    return exchContact.Inner.Email1Address;
                  }
                }
              }
            }
            catch (COMException ex)
            {
              generalLogger.Warn ("Could not get email address from adressEntry.GetContact()", ex);
              logger.LogMappingWarning ("Could not get email address from adressEntry.GetContact()", ex);
            }
          }
          else
          {
            return addressEntry.Address;
          }
        }
        else
        {
          try
          {
            return addressEntry.GetPropertySafe (PR_SMTP_ADDRESS);
          }
          catch (COMException ex)
          {
            generalLogger.Warn ("Could not get property PR_SMTP_ADDRESS for adressEntry", ex);
            logger.LogMappingWarning ("Could not get property PR_SMTP_ADDRESS for adressEntry", ex);
          }
        }
      }

      return null;
    }
 public static AddressEntry GetEventOrganizerOrNull (AppointmentItem source, IEntityMappingLogger logger, ILog generalLogger, int outlookMajorVersion)
 {
   try
   {
     if (outlookMajorVersion < 14)
     {
       // Microsoft recommends this way for Outlook 2007. May still work with Outlook 2010+
       using (var propertyAccessor = GenericComObjectWrapper.Create (source.PropertyAccessor))
       {
         string organizerEntryID = propertyAccessor.Inner.BinaryToString (propertyAccessor.Inner.GetProperty(PR_SENT_REPRESENTING_ENTRYID));
         return Globals.ThisAddIn.Application.Session.GetAddressEntryFromID (organizerEntryID);
       }
     }
     else
     {
       // NB this works with Outlook 2010 but crashes with Outlook 2007
       return source.GetOrganizer();
     }
   }
   catch (COMException ex)
   {
     generalLogger.Warn ("Can't get organizer of appointment", ex);
     logger.LogMappingWarning ("Can't get organizer of appointment", ex);
     return null;
   }
 }
 public static string GetSenderEmailAddressOrNull (AppointmentItem source, IEntityMappingLogger logger, ILog generalLogger)
 {
   try
   {
     return source.GetPropertySafe (PR_SENDER_EMAIL_ADDRESS);
   }
   catch (COMException ex)
   {
     generalLogger.Warn ("Can't access property PR_SENDER_EMAIL_ADDRESS of appointment", ex);
     logger.LogMappingWarning ("Can't access property PR_SENDER_EMAIL_ADDRESS of appointment", ex);
     return null;
   }
 }
Exemplo n.º 46
0
 public void Log(ILog log)
 {
     string message = "{0}: {1}".AsFormat(Description, Message);
     switch (ResultType)
     {
         case Type.Success:
             log.Info(message); break;
         case Type.Warning:
             log.Warn(message); break;
         case Type.Failure:
             log.Error(message); break;
         default:
             log.Debug(message); break;
     }
 }
Exemplo n.º 47
0
        public override void Connect()
        {
            _log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType + "(" + Hostname + ":" + Port + ")");

            _isConnected = false;
            using (_tcpClient = new TcpClient())
            {
                _tcpClient.ReceiveTimeout = (MaxData > 0 ? Settings.Instance.DownloadTimeoutTime : Settings.Instance.ServerTimeoutTime) * 1000;

                try
                {
                    _log.Info("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") start");
                    _tcpClient.Connect(Hostname, Port);
                    _isConnected = true;
                }
                catch (SocketException ex)
                {
                    _errorCode = (SocketErrorCode) ex.ErrorCode;
                    _log.Error("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") : " + ((SocketErrorCode) ex.ErrorCode), ex);
                }
                catch (Exception ex)
                {
                    _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ")", ex);
                }

                if (_isConnected)
                {
                    _log.Info("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") connected");

                    using (NetworkStream stream = _tcpClient.GetStream())
                    {
                        // we just need a writer if reading in text mode
                        if (MaxData == 0)
                        {
                            _writer = new StreamWriter(stream) {NewLine = "\r\n", AutoFlush = true};
                        }

                        FireConnected();

                        _allowRunning = true;
                        try
                        {
                            #region BINARY READING

                            if (MaxData > 0)
                            {
                                using (var reader = new BinaryReader(stream))
                                {
                                    Int64 missing = MaxData;
                                    Int64 max = Settings.Instance.DownloadPerReadBytes;
                                    byte[] data = null;
                                    do
                                    {
                                        try
                                        {
                                            data = reader.ReadBytes((int) (missing < max ? missing : max));
                                        }
                                        catch (ObjectDisposedException)
                                        {
                                            break;
                                        }
                                        catch (SocketException ex)
                                        {
                                            _errorCode = (SocketErrorCode) ex.ErrorCode;
                                            if (_errorCode != SocketErrorCode.InterruptedFunctionCall)
                                            {
                                                _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading: " + (_errorCode), ex);
                                            }
                                        }
                                        catch (IOException ex)
                                        {
                                            if (ex.InnerException is SocketException)
                                            {
                                                var exi = (SocketException) ex.InnerException;
                                                _errorCode = (SocketErrorCode) exi.ErrorCode;
                                                _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading: " + (_errorCode), ex);
                                            }
                                            else
                                            {
                                                _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading", ex);
                                            }
                                            break;
                                        }
                                        catch (Exception ex)
                                        {
                                            _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading", ex);
                                            break;
                                        }

                                        if (data != null && data.Length != 0)
                                        {
                                            FireDataBinaryReceived(data);
                                            missing -= data.Length;
                                        }
                                        else
                                        {
                                            _log.Warn("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") no data received");
                                            break;
                                        }
                                    } while (_allowRunning && missing > 0);
                                }
                            }

                                #endregion

                                #region TEXT READING

                            else
                            {
                                using (var reader = new StreamReader(stream))
                                {
                                    int failCounter = 0;
                                    string data = "";
                                    do
                                    {
                                        try
                                        {
                                            data = reader.ReadLine();
                                        }
                                        catch (ObjectDisposedException)
                                        {
                                            break;
                                        }
                                        catch (SocketException ex)
                                        {
                                            _errorCode = (SocketErrorCode) ex.ErrorCode;
                                            // we dont need to log this kind of exception, because it is just normal
                                            //Log("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading: " + ((SocketErrorCode)ex.ErrorCode), LogLevel.Exception);
                                        }
                                        catch (IOException ex)
                                        {
                                            if (ex.InnerException is SocketException)
                                            {
                                                var exi = (SocketException) ex.InnerException;
                                                _errorCode = (SocketErrorCode) exi.ErrorCode;
                                                // we dont need to log this kind of exception, because it is just normal
                                                //Log("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading: " + ((SocketErrorCode)exi.ErrorCode), LogLevel.Exception);
                                            }
                                            else
                                            {
                                                _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading", ex);
                                            }
                                            break;
                                        }
                                        catch (Exception ex)
                                        {
                                            _log.Fatal("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") reading", ex);
                                            break;
                                        }

                                        if ( /*data != "" && */data != null)
                                        {
                                            if (data != "")
                                            {
                                                failCounter = 0;
                                                FireDataTextReceived(data);
                                            }
                                        }
                                        else
                                        {
                                            failCounter++;
                                            if (failCounter > Settings.Instance.MaxNoDataReceived)
                                            {
                                                _log.Warn("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") no data received");
                                                break;
                                            }
                                            data = "";
                                        }
                                    } while (_allowRunning);
                                }
                            }

                            #endregion

                            Disconnect();
                        }
                        catch (ObjectDisposedException)
                        {
                            // this is ok...
                        }

                        _log.Info("Connect(" + (MaxData > 0 ? "" + MaxData : "") + ") end");
                    }
                }

                FireDisconnected(_errorCode);
            }

            _tcpClient = null;
            _writer = null;
        }
        static SIPRegAgentState()
        {
            try
            {
                #region Configure logging.

                try
                {

                    log4net.Config.XmlConfigurator.Configure();
                    logger = log4net.LogManager.GetLogger(LOGGER_NAME);
                }
                catch (Exception logExcp)
                {
                    Console.WriteLine("Exception SIPProxyState Configure Logging. " + logExcp.Message);
                }

                #endregion

                if (AppState.GetSection(SIPREGAGENT_CONFIGNODE_NAME) != null)
                {
                    m_sipRegAgentNode = (XmlNode)AppState.GetSection(SIPREGAGENT_CONFIGNODE_NAME);
                }

                if (m_sipRegAgentNode == null)
                {
                    logger.Warn("The SIP Registration Agent " + SIPREGAGENT_CONFIGNODE_NAME + " config node was not available, the agent will not be able to start.");
                }
                else
                {
                    SIPRegAgentSocketsNode = m_sipRegAgentNode.SelectSingleNode(SIPSOCKETS_CONFIGNODE_NAME);
                    Int32.TryParse(AppState.GetConfigNodeValue(m_sipRegAgentNode, MONITOR_LOOPBACK_PORT_KEY), out MonitorLoopbackPort);
                    if (!AppState.GetConfigNodeValue(m_sipRegAgentNode, OUTBOUND_PROXY_KEY).IsNullOrBlank())
                    {
                        OutboundProxy = SIPEndPoint.ParseSIPEndPoint(AppState.GetConfigNodeValue(m_sipRegAgentNode, OUTBOUND_PROXY_KEY));
                    }
                    if (!AppState.GetConfigNodeValue(m_sipRegAgentNode, THREAD_COUNT_KEY).IsNullOrBlank())
                    {
                        Int32.TryParse(AppState.GetConfigNodeValue(m_sipRegAgentNode, THREAD_COUNT_KEY), out ThreadCount);
                    }
                    if (!AppState.GetConfigNodeValue(m_sipRegAgentNode, DISALLOW_PRIVATE_IP_REGISTRARS_KEY).IsNullOrBlank())
                    {
                        Boolean.TryParse(AppState.GetConfigNodeValue(m_sipRegAgentNode, DISALLOW_PRIVATE_IP_REGISTRARS_KEY), out DisallowPrivateIPRegistrars);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPRegAgentState. " + excp.Message);
                throw;
            }
        }
Exemplo n.º 49
0
        /// <summary>
        ///     Write <paramref name="message"/> to log
        /// </summary>
        /// <param name="message"></param>
        /// <param name="logLevel"></param>
        public void WriteLog(string message, Enums.LogLevels logLevel = Enums.LogLevels.Info)
        {
            switch (logLevel)
            {
                case Enums.LogLevels.Debug:
                    {
                        ThreadContext.Properties["logPath"] = Constants.Paths.Debug;
                    }
                    break;

                case Enums.LogLevels.Info:
                    {
                        ThreadContext.Properties["logPath"] = Constants.Paths.Info;
                    }
                    break;

                case Enums.LogLevels.Warn:
                    {
                        ThreadContext.Properties["logPath"] = Constants.Paths.Warn;
                    }
                    break;

                case Enums.LogLevels.Error:
                    {
                        ThreadContext.Properties["logPath"] = Constants.Paths.Error;
                    }
                    break;

                case Enums.LogLevels.Fatal:
                    {
                        ThreadContext.Properties["logPath"] = Constants.Paths.Fatal;
                    }
                    break;
            }
            _logger = LogManager.GetLogger(GetCaller());
            XmlConfigurator.Configure();
            switch (logLevel)
            {
                case Enums.LogLevels.Debug:
                    {
                        _logger.Debug(message);
                    }
                    break;

                case Enums.LogLevels.Info:
                    {
                        _logger.Info(message);
                    }
                    break;

                case Enums.LogLevels.Warn:
                    {
                        _logger.Warn(message);
                    }
                    break;

                case Enums.LogLevels.Error:
                    {
                        _logger.Error(message);
                    }
                    break;

                case Enums.LogLevels.Fatal:
                    {
                        _logger.Fatal(message);
                    }
                    break;
            }

            LogManager.GetRepository().Shutdown();
        }
Exemplo n.º 50
0
        public static void Start(string[] args)
        {
            bool isAlreadyRunning = false;
            List<string> filesToOpen = new List<string>();

            // Set the Thread name, is better than "1"
            Thread.CurrentThread.Name = Application.ProductName;

            // Init Log4NET
            LogFileLocation = LogHelper.InitializeLog4NET();
            // Get logger
            LOG = LogManager.GetLogger(typeof(MainForm));

            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // Initialize the IniConfig
            IniConfig.Init();

            // Log the startup
            LOG.Info("Starting: " + EnvironmentInfo.EnvironmentToString(false));

            // Read configuration
            _conf = IniConfig.GetIniSection<CoreConfiguration>();
            try {
                // Fix for Bug 2495900, Multi-user Environment
                // check whether there's an local instance running already

                try {
                    // Added Mutex Security, hopefully this prevents the UnauthorizedAccessException more gracefully
                    // See an example in Bug #3131534
                    SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null);
                    MutexSecurity mutexsecurity = new MutexSecurity();
                    mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow));
                    mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.ChangePermissions, AccessControlType.Deny));
                    mutexsecurity.AddAccessRule(new MutexAccessRule(sid, MutexRights.Delete, AccessControlType.Deny));

                    bool created;
                    // 1) Create Mutex
                    _applicationMutex = new Mutex(false, @"Local\F48E86D3-E34C-4DB7-8F8F-9A0EA55F0D08", out created, mutexsecurity);
                    // 2) Get the right to it, this returns false if it's already locked
                    if (!_applicationMutex.WaitOne(0, false)) {
                        LOG.Debug("Greenshot seems already to be running!");
                        isAlreadyRunning = true;
                        // Clean up
                        _applicationMutex.Close();
                        _applicationMutex = null;
                    }
                } catch (AbandonedMutexException e) {
                    // Another Greenshot instance didn't cleanup correctly!
                    // we can ignore the exception, it happend on the "waitone" but still the mutex belongs to us
                    LOG.Warn("Greenshot didn't cleanup correctly!", e);
                } catch (UnauthorizedAccessException e) {
                    LOG.Warn("Greenshot is most likely already running for a different user in the same session, can't create mutex due to error: ", e);
                    isAlreadyRunning = true;
                } catch (Exception e) {
                    LOG.Warn("Problem obtaining the Mutex, assuming it was already taken!", e);
                    isAlreadyRunning = true;
                }

                if (args.Length > 0 && LOG.IsDebugEnabled) {
                    StringBuilder argumentString = new StringBuilder();
                    for(int argumentNr = 0; argumentNr < args.Length; argumentNr++) {
                        argumentString.Append("[").Append(args[argumentNr]).Append("] ");
                    }
                    LOG.Debug("Greenshot arguments: " + argumentString);
                }

                for(int argumentNr = 0; argumentNr < args.Length; argumentNr++) {
                    string argument = args[argumentNr];
                    // Help
                    if (argument.ToLower().Equals("/help") || argument.ToLower().Equals("/h") || argument.ToLower().Equals("/?")) {
                        // Try to attach to the console
                        bool attachedToConsole = Kernel32.AttachConsole(Kernel32.ATTACHCONSOLE_ATTACHPARENTPROCESS);
                        // If attach didn't work, open a console
                        if (!attachedToConsole) {
                            Kernel32.AllocConsole();
                        }
                        StringBuilder helpOutput = new StringBuilder();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("Greenshot commandline options:");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t/help");
                        helpOutput.AppendLine("\t\tThis help.");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t/exit");
                        helpOutput.AppendLine("\t\tTries to close all running instances.");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t/reload");
                        helpOutput.AppendLine("\t\tReload the configuration of Greenshot.");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t/language [language code]");
                        helpOutput.AppendLine("\t\tSet the language of Greenshot, e.g. greenshot /language en-US.");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t/inidirectory [directory]");
                        helpOutput.AppendLine("\t\tSet the directory where the greenshot.ini should be stored & read.");
                        helpOutput.AppendLine();
                        helpOutput.AppendLine();
                        helpOutput.AppendLine("\t[filename]");
                        helpOutput.AppendLine("\t\tOpen the bitmap files in the running Greenshot instance or start a new instance");
                        Console.WriteLine(helpOutput.ToString());

                        // If attach didn't work, wait for key otherwise the console will close to quickly
                        if (!attachedToConsole) {
                            Console.ReadKey();
                        }
                        FreeMutex();
                        return;
                    }

                    if (argument.ToLower().Equals("/exit")) {
                        // unregister application on uninstall (allow uninstall)
                        try {
                            LOG.Info("Sending all instances the exit command.");
                            // Pass Exit to running instance, if any
                            SendData(new CopyDataTransport(CommandEnum.Exit));
                        } catch (Exception e) {
                            LOG.Warn("Exception by exit.", e);
                        }
                        FreeMutex();
                        return;
                    }

                    // Reload the configuration
                    if (argument.ToLower().Equals("/reload")) {
                        // Modify configuration
                        LOG.Info("Reloading configuration!");
                        // Update running instances
                        SendData(new CopyDataTransport(CommandEnum.ReloadConfig));
                        FreeMutex();
                        return;
                    }

                    // Stop running
                    if (argument.ToLower().Equals("/norun")) {
                        // Make an exit possible
                        FreeMutex();
                        return;
                    }

                    // Language
                    if (argument.ToLower().Equals("/language")) {
                        _conf.Language = args[++argumentNr];
                        IniConfig.Save();
                        continue;
                    }

                    // Setting the INI-directory
                    if (argument.ToLower().Equals("/inidirectory")) {
                        IniConfig.IniDirectory = args[++argumentNr];
                        continue;
                    }

                    // Files to open
                    filesToOpen.Add(argument);
                }

                // Finished parsing the command line arguments, see if we need to do anything
                CopyDataTransport transport = new CopyDataTransport();
                if (filesToOpen.Count > 0) {
                    foreach(string fileToOpen in filesToOpen) {
                        transport.AddCommand(CommandEnum.OpenFile, fileToOpen);
                    }
                }

                if (isAlreadyRunning) {
                    // We didn't initialize the language yet, do it here just for the message box
                    if (filesToOpen.Count > 0) {
                        SendData(transport);
                    } else {
                        StringBuilder instanceInfo = new StringBuilder();
                        bool matchedThisProcess = false;
                        int index = 1;
                        int currentProcessId;
                        using (Process currentProcess = Process.GetCurrentProcess()) {
                            currentProcessId = currentProcess.Id;
                        }
                        foreach (Process greenshotProcess in Process.GetProcessesByName("greenshot")) {
                            try {
                                instanceInfo.Append(index++ + ": ").AppendLine(Kernel32.GetProcessPath(greenshotProcess.Id));
                                if (currentProcessId == greenshotProcess.Id) {
                                    matchedThisProcess = true;
                                }
                            } catch (Exception ex) {
                                LOG.Debug(ex);
                            }
                            greenshotProcess.Dispose();
                        }
                        if (!matchedThisProcess) {
                            using (Process currentProcess = Process.GetCurrentProcess()) {
                                instanceInfo.Append(index + ": ").AppendLine(Kernel32.GetProcessPath(currentProcess.Id));
                            }
                        }

                        // A dirty fix to make sure the messagebox is visible as a Greenshot window on the taskbar
                        using (Form dummyForm = new Form()) {
                            dummyForm.Icon = GreenshotResources.getGreenshotIcon();
                            dummyForm.ShowInTaskbar = true;
                            dummyForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                            dummyForm.Location = new Point(int.MinValue, int.MinValue);
                            dummyForm.Load += delegate { dummyForm.Size = Size.Empty; };
                            dummyForm.Show();
                            MessageBox.Show(dummyForm, Language.GetString(LangKey.error_multipleinstances) + "\r\n" + instanceInfo, Language.GetString(LangKey.error), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                        }
                    }
                    FreeMutex();
                    Application.Exit();
                    return;
                }

                // From here on we continue starting Greenshot
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                // if language is not set, show language dialog
                if(string.IsNullOrEmpty(_conf.Language)) {
                    LanguageDialog languageDialog = LanguageDialog.GetInstance();
                    languageDialog.ShowDialog();
                    _conf.Language = languageDialog.SelectedLanguage;
                    IniConfig.Save();
                }

                // Check if it's the first time launch?
                if(_conf.IsFirstLaunch) {
                    _conf.IsFirstLaunch = false;
                    IniConfig.Save();
                    transport.AddCommand(CommandEnum.FirstLaunch);
                }
                // Should fix BUG-1633
                Application.DoEvents();
                _instance = new MainForm(transport);
                Application.Run();
            } catch(Exception ex) {
                LOG.Error("Exception in startup.", ex);
                Application_ThreadException(ActiveForm, new ThreadExceptionEventArgs(ex));
            }
        }
Exemplo n.º 51
0
        /// <summary>
        /// Constructor for proxy base class.
        /// </summary>
        /// <param name="name">Name of the proxy.</param>
        /// <param name="listenAddress">Address the proxy listens on.</param>
        /// <param name="listenPort">Port the proxy listens on.</param>
        /// <param name="httpsListenPort">Port the proxy listens on for HTTPS</param>
        /// <param name="proxyPath">Directory path the proxy is running in.</param>
        /// <param name="maxCacheSize">The max cache size in bytes.</param>
        /// <param name="cachePath">Path to the proxy's cache</param>
        /// <param name="packageCachePath">Path to the proxy's packages</param>
        protected RCProxy(string name, IPAddress listenAddress, int listenPort, int httpsListenPort,
            string proxyPath, long maxCacheSize, string cachePath, string packageCachePath)
        {
            _name = name;
            // setup proxy listener variables
            _listenAddress = listenAddress;
            _listenPort = listenPort;
            _httpsListenPort = httpsListenPort;
            _proxyPath = proxyPath;

            // no pending requests
            _requestEvent = new AutoResetEvent(false);

            //create and initialize the logger
            _logger = LogManager.GetLogger(this.GetType());

            bool success = false;

            // initialize the cache directory
            success = InitializeCache(maxCacheSize, cachePath);
            if (!success)
            {
                _logger.Warn("Error initializing the " + name + " cache.");
            }

            // initialize the packages cache
            success = InitializePackagesCache(proxyPath + packageCachePath);
            if (!success)
            {
                _logger.Warn("Error initializing the " + name + " packages cache.");
            }

            // Load the blacklist
            LoadBlacklist();

            // initialize the network usage detector
            _networkUsageDetector = new NetworkUsageDetector(this);
            // Start the timer that logs the network speed and so on.
            _changeNetworkStatusTimer
                           = new Timer(LogSpeedAndApplyNetworkSpeedSettings,
                               null, NETWORK_DETECTION_INTERVAL, NETWORK_DETECTION_INTERVAL);

            // Restore old state
            LoadState();
            // Tell the programm to serialize state before shutdown
            Program.AddShutDownDelegate(SaveState);
        }
Exemplo n.º 52
0
 protected void Init()
 {
     this.logger = Simply.Do.Log(this);
     try
     {
         resolver = Configure();
         ConfigureLogging();
     }
     catch (Exception e)
     {
         ConfigureLogging();
         logger.Warn("Failed to configure: {0}".AsFormat(e.Message) , e);
     }
     logger.InfoFormat("Simple.Net v{0} [{1}]", Simply.Do.Version.ToString(3), ProjectText);
 }
Exemplo n.º 53
0
 /// <summary>
 /// Log a message object with the <see cref="F:log4net.Core.Level.Warn"/> level including
 /// the stack trace of the <see cref="T:System.Exception"/> passed
 /// as a parameter.
 /// </summary>
 /// <param name="message">The message object to log.</param>
 /// <param name="exception">The exception to log, including its stack trace.</param>
 /// <param name="log">The log.</param>
 /// <remarks>
 /// See the <see cref="M:log4net.ILog.Warn(System.Object)"/> form for more detailed information.
 /// </remarks>
 /// <seealso cref="M:log4net.ILog.Warn(System.Object)"/>
 /// <seealso cref="P:log4net.ILog.IsWarnEnabled"/>
 public static void Warn(object message, Exception exception, ILog log)
 {
     log.Warn(message, exception);
 }
Exemplo n.º 54
0
 /// <summary>
 /// Log a message object with the <see cref="F:log4net.Core.Level.Warn"/> level.
 /// </summary>
 /// <param name="message">The message object to log.</param>
 /// <param name="log">The log.</param>
 /// <overloads>Log a message object with the <see cref="F:log4net.Core.Level.Warn"/> level.</overloads>
 /// <remarks>
 /// 	<para>
 /// This method first checks if this logger is <c>WARN</c>
 /// enabled by comparing the level of this logger with the
 /// <see cref="F:log4net.Core.Level.Warn"/> level. If this logger is
 /// <c>WARN</c> enabled, then it converts the message object
 /// (passed as parameter) to a string by invoking the appropriate
 /// <see cref="T:log4net.ObjectRenderer.IObjectRenderer"/>. It then
 /// proceeds to call all the registered appenders in this logger
 /// and also higher in the hierarchy depending on the value of the
 /// additivity flag.
 /// </para>
 /// 	<para><b>WARNING</b> Note that passing an <see cref="T:System.Exception"/>
 /// to this method will print the name of the <see cref="T:System.Exception"/>
 /// but no stack trace. To print a stack trace use the
 /// <see cref="M:log4net.ILog.Warn(System.Object,System.Exception)"/> form instead.
 /// </para>
 /// </remarks>
 /// <seealso cref="M:log4net.ILog.Warn(System.Object,System.Exception)"/>
 /// <seealso cref="P:log4net.ILog.IsWarnEnabled"/>
 public static void Warn(object message, ILog log)
 {
     log.Warn(message);
 }
        static SIPRegistrarState()
        {
            try
            {
                #region Configure logging.

                try
                {
                    log4net.Config.XmlConfigurator.Configure();
                    logger = log4net.LogManager.GetLogger(LOGGER_NAME);
                }
                catch (Exception logExcp)
                {
                    Console.WriteLine("Exception SIPRegistrarState Configure Logging. " + logExcp.Message);
                }

                #endregion

                if (AppState.GetSection(SIPREGISTRAR_CONFIGNODE_NAME) != null)
                {
                    m_sipRegistrarNode = (XmlNode)AppState.GetSection(SIPREGISTRAR_CONFIGNODE_NAME);
                }

                if (m_sipRegistrarNode == null)
                {
                    //throw new ApplicationException("The SIP Registrar could not be started, no " + SIPREGISTRAR_CONFIGNODE_NAME + " config node available.");
                    logger.Warn("The SIP Registrar " + SIPREGISTRAR_CONFIGNODE_NAME + " config node was not available, the agent will not be able to start.");
                }
                else
                {
                    SIPRegistrarSocketsNode = m_sipRegistrarNode.SelectSingleNode(SIPSOCKETS_CONFIGNODE_NAME);
                    if (SIPRegistrarSocketsNode == null)
                    {
                        throw new ApplicationException("The SIP Registrar could not be started, no " + SIPSOCKETS_CONFIGNODE_NAME + " node could be found.");
                    }

                    UserAgentsConfigNode = m_sipRegistrarNode.SelectSingleNode(USERAGENTS_CONFIGNODE_NAME);
                    Int32.TryParse(AppState.GetConfigNodeValue(m_sipRegistrarNode, MONITOR_LOOPBACK_PORT_KEY), out MonitorLoopbackPort);
                    Int32.TryParse(AppState.GetConfigNodeValue(m_sipRegistrarNode, MAXIMUM_ACCOUNT_BINDINGS_KEY), out MaximumAccountBindings);
                    if (!AppState.GetConfigNodeValue(m_sipRegistrarNode, NATKEEPALIVE_RELAY_SOCKET).IsNullOrBlank())
                    {
                        NATKeepAliveRelaySocket = IPSocket.ParseSocketString(AppState.GetConfigNodeValue(m_sipRegistrarNode, NATKEEPALIVE_RELAY_SOCKET));
                    }
                    SwitchboardCertificateName = AppState.GetConfigNodeValue(m_sipRegistrarNode, SWITCHBOARD_CERTIFICATE_NAME_KEY);
                    if (!AppState.GetConfigNodeValue(m_sipRegistrarNode, THREAD_COUNT_KEY).IsNullOrBlank())
                    {
                        Int32.TryParse(AppState.GetConfigNodeValue(m_sipRegistrarNode, THREAD_COUNT_KEY), out ThreadCount);
                    }
                }
            }
            catch (Exception excp)
            {
                logger.Error("Exception SIPRegistrarState. " + excp.Message);
                throw;
            }
        }
Exemplo n.º 56
0
 /// <summary/>
 public static void LeaveWarn(string methodName, string message, bool hasReturnValue, object returnValue, ILog log)
 {
     log.Warn(MakeLeaveMessage(methodName, message, hasReturnValue, returnValue));
 }
Exemplo n.º 57
0
    public void Configure(string collectorName, XElement configElement, ISystemMetricsService systemMetrics)
    {
      _completionTask = new Task(() => IsActive = false);
      _log = SuperCheapIOC.Resolve<ILog>();
      _systemMetrics = systemMetrics;

      var config = new LibratoBackendConfiguration(
          email: configElement.Attribute("email").Value,
          token: configElement.Attribute("token").Value,
          numRetries: configElement.ToInt("numRetries"),
          retryDelay: Utility.ConvertToTimespan(configElement.Attribute("retryDelay").Value),
          postTimeout: Utility.ConvertToTimespan(configElement.Attribute("postTimeout").Value),
          maxBatchSize: configElement.ToInt("maxBatchSize"),
          countersAsGauges: configElement.ToBoolean("countersAsGauges")
        );
      
      _config = config;
      _source = collectorName;
      _serviceVersion = Assembly.GetEntryAssembly().GetName().Version.ToString();

      _preprocessorBlock = new ActionBlock<Bucket>(bucket => ProcessBucket(bucket), Utility.UnboundedExecution());
      _batchBlock = new BatchBlock<LibratoMetric>(_config.MaxBatchSize);
      _outputBlock = new ActionBlock<LibratoMetric[]>(lines => PostToLibrato(lines), Utility.OneAtATimeExecution());
      _batchBlock.LinkTo(_outputBlock);

      _client = new RestClient(LIBRATO_API_URL);
      _client.Authenticator = new HttpBasicAuthenticator(_config.Email, _config.Token);
      _client.Timeout = (int)_config.PostTimeout.TotalMilliseconds;

      _retryPolicy = new RetryPolicy<LibratoErrorDetectionStrategy>(_config.NumRetries);
      _retryPolicy.Retrying += (sender, args) =>
      {
        _log.Warn(String.Format("Retry {0} failed. Trying again. Delay {1}, Error: {2}", args.CurrentRetryCount, args.Delay, args.LastException.Message), args.LastException);
        _systemMetrics.LogCount("backends.librato.retry");
      };
      _retryStrategy = new Incremental(_config.NumRetries, _config.RetryDelay, TimeSpan.FromSeconds(2));
      IsActive = true;
    }
Exemplo n.º 58
0
        public void DelayedStart()
        {
            _log = LogManager.GetLogger(typeof(DeploymentService));

            //            _queueProvider = _realm.QueueProvider;
            //            _queueDeploymentsCommands = _queueProvider.GetQueueById("igor-cloudMorph-deployments");

            try
            {
                var realm = new AwsRealm();

                var environment = realm.Current;

                var metadata = environment.GetMetadata();

                string packageName = null;

                if (metadata.TryGetValue("metadata", out packageName))
                {
                    _log.Info("Package Name: " + packageName);
                }
                else
                {
                    _log.Warn("Can't retreive metadata.");

                    packageName = ConfigurationManager.AppSettings["packageName"];
                }

                _log.Info("Target to download the package: " + packageName);

                var storage = realm.StorageProvider;

                const string deplDir = @"Packages";
                if (!Directory.Exists(deplDir))
                    Directory.CreateDirectory(deplDir);

                string packagePath = Path.Combine(deplDir, packageName);
                if (File.Exists(packagePath))
                {
                    _log.Info("The package was already deployed. Exiting ...");
                    return;
                }

                using (var package = File.Create(packagePath))
                {
                    storage.GetFromBucket("igor-morphCloud-packages", packageName, package);
                }

                string serviceLocation = Path.Combine(@"Services", Path.GetFileNameWithoutExtension(packageName));
                _log.Info("Unpacking package to: " + serviceLocation);

                if (!Directory.Exists(serviceLocation))
                    Directory.CreateDirectory(serviceLocation);

                PackageCompressor.Decompress(packagePath, serviceLocation);
            }
            catch (Exception e)
            {
                _log.Error("Failed to get the package", e);
            }
        }
Exemplo n.º 59
0
        // NB : Best to call this function from the windows Loaded event or after showing the window
        // (otherwise window is just positioned to fill the secondary monitor rather than being maximised).
        public static void MaximizeToSecondaryMonitor(this Window window, ILog Log)
        {
            Log.Debug("Try to maximize window on secondary screen");

            var secScreen = System.Windows.Forms.Screen.AllScreens.Where(s => !s.Primary).FirstOrDefault();
            if (secScreen != null)
            {
                Log.DebugFormat("Secondary-Screen: {0}, {1}, width: {2}, height: {3}", secScreen, secScreen.DeviceName, secScreen.WorkingArea.Width, secScreen.WorkingArea.Height);
            }
            else
            {
                Log.DebugFormat("No secondary screen detected");
            }

            Log.DebugFormat("Total screens: {0}", System.Windows.Forms.Screen.AllScreens.Count());
            Log.DebugFormat("Total 2nd screens: {0}", System.Windows.Forms.Screen.AllScreens.Where(s => !s.Primary).Count());

            if (secScreen != null)
            {
                if (!window.IsLoaded)
                    window.WindowStartupLocation = WindowStartupLocation.Manual;

                var workingArea = secScreen.WorkingArea;
                window.Left = workingArea.X;
                window.Top = workingArea.Top;
                window.Width = workingArea.Width;
                window.Height = workingArea.Height;
                // If window isn't loaded then maxmizing will result in the window displaying on the primary monitor
                if (window.IsLoaded)
                {
                    Log.Warn("Window wasn't loaded - load on Primary monitor!");
                    window.WindowState = WindowState.Maximized;
                }
            }
        }
Exemplo n.º 60
0
 /// <summary>
 /// Logs the warning.
 /// </summary>
 /// <param name="type">The type.</param>
 /// <param name="message">The message.</param>
 /// <param name="ex">The ex.</param>
 public static void LogWarning( Type type, string message, Exception ex )
 {
     Log = LogManager.GetLogger ( type );
     Log.Warn ( message, ex );
 }