private static void DisplayError(string error, NLog.Logger logger = null)
 {
     if (null != logger)
     {
         logger.Error(error);
     }
     else
     {
         Console.Error.WriteLine(error);
     }
 }
Esempio n. 2
0
 public static void WriteLog(String content)
 {
     if (IsDebug == "true")
     {
         NLog.WriteLog(content);
     }
 }
 public LumberjackMessageBuilder(NLog.Logger logger, string source, string appId, string component)
 {
     Logger = logger;
     Source = source;
     AppId = appId;
     Component = component;
 }
Esempio n. 4
0
        public static int GetRateCard(int[] rate, RandomCardSelectorDelegate del, int funcInfo)
        {
            while (true)
            {
                int sum = 0;
                foreach (var r in rate)
                {
                    sum += r;
                }
                int roll    = MathTool.GetRandom(sum);
                int quality = 0;
                sum = 0;
                for (int i = 0; i < rate.Length; i++)
                {
                    sum += rate[i];
                    if (roll < sum)
                    {
                        quality = i;
                        break;
                    }
                }

                var cardId = del(funcInfo, quality);
                if (cardId > 0)
                {
                    return(cardId);
                }
                else
                {
                    NLog.Debug("GetRateCard cardId = 0 funcInfo " + funcInfo);
                }
            }

            return(0);
        }
Esempio n. 5
0
        private void TimeGo()
        {
            while (true)
            {
                TalePlayer.Oneloop();

                timeTick++;
                if (timeTick > 1000)
                {
                    timeTick -= 1000;
                }
                if (page == 0)
                {
                    var logWid    = tabPageLogin.Width / 4;
                    var logHeight = tabPageLogin.Height / 5;
                    var logX      = (tabPageLogin.Width - logWid) / 2;
                    var logY      = (tabPageLogin.Height - logHeight) / 2 + Math.Sin((double)timeTick / 12) * 6;
                    tabPageLogin.Invalidate(new Rectangle(logX, (int)logY - 6, logWid, logHeight + 12)); //logo区域
                }
                else if (page == 1)
                {
                    try
                    {
                        foreach (var control in tabPageGame.Controls)
                        {
                            if (control is BasePanel)
                            {
                                (control as BasePanel).OnFrame(timeTick, 0.05f);
                            }
                        }

                        if (SystemMenuManager.IsHotkeyEnabled && (timeTick % 5) == 0)
                        {
                            SystemMenuManager.UpdateAll(tabPageGame);

                            if (MainTipManager.OnFrame())
                            {
                                tabPageGame.Invalidate();
                            }
                        }

                        if (SystemMenuManager.GMMode)
                        {
                            GMCodeZone.OnFrame();
                        }

                        if (flowController != null)
                        {
                            flowController.CheckTick();
                        }
                    }
                    catch (Exception e)
                    {
                        NLog.Error(e);
                        throw;
                    }
                }
                Thread.Sleep(50);
            }
        }
Esempio n. 6
0
        public Result Close(string token)
        {
            if (token != ConfigurationManager.AppSettings["CloseToken"])
            {
                return(Result(ApiResultEnum.InvalidRequest));
            }

            int status_trade = MonitorRA.GetStatusTrade();

            UserRA.FlushDatabase(new List <int>()
            {
                7, 8, (int)DateTime.Now.AddDays(1).DayOfWeek
            });
            if (status_trade != 0)
            {
                if (LogTradeDA.Close("系统"))
                {
                    MonitorRA.SetStatusTrade((int)StatusTradeEnum.Closed);
                    OpenCloseBiz.Close();
                    NLog.Info("系统自动收盘");
                    return(Result(ApiResultEnum.Success));
                }
            }
            return(Result(ApiResultEnum.Order_Closed));
        }
        protected override void Write(NLog.Common.AsyncLogEventInfo logEvent)
        {
            base.Write(logEvent);

            if (RecieveLog != null)
                RecieveLog(logEvent);
        }
Esempio n. 8
0
 /// <summary>
 /// 构造函数
 /// </summary>
 /// <param name="DDA">获得一个实例化了的DbDataAdapter的派生类</param>
 public Database(DbDataAdapter DDA, DBType DBType)
 {
     mDataAdapter = DDA;
     mCommand     = DDA.SelectCommand;
     thisDBType   = DBType;
     log          = NLog.Init();
 }
Esempio n. 9
0
        public void DoSpell(LiveMonster target, ActiveCard card, Point location)
        {
            if (!BeforeUseCard(card, location))
            {
                return;
            }

            try
            {
                Spell spell = new Spell(card.CardId);
                spell.Addon = SpellEffectAddon;
                spell.UpgradeToLevel(card.Level);
                if (!card.IsHeroSkill)
                {
                    BattleManager.Instance.StatisticData.GetPlayer(IsLeft).SpellAdd++;
                }

                SpellAssistant.CheckSpellEffect(spell, IsLeft, target, location);

                if (SpikeManager.HasSpike("mirrorspell"))
                {
                    Rival.AddCard(null, card.CardId, card.Level);
                }
            }
            catch (Exception e)
            {
                NLog.Warn(e);
                BattleManager.Instance.FlowWordQueue.Add(new FlowWord("未知错误", location, 0, "Red", 26, 0, 0, 2, 15), false);
                return;
            }
            AfterUseCard(card);
            CardManager.DeleteCardAt(SelectId);
        }
Esempio n. 10
0
 protected override void Write(NLog.Common.AsyncLogEventInfo logEvent)
 {
     if ( logEvent.LogEvent.Level > LogLevel.Warn && logEvent.LogEvent.Exception != null )
     {
         Elmah.ErrorSignal.FromCurrentContext().Raise(logEvent.LogEvent.Exception);
     }
 }
 protected override void Write(NLog.Common.AsyncLogEventInfo[] logEvents)
 {
     foreach (var ev in logEvents)
     {
         NumEvents++;
     }
 }
Esempio n. 12
0
        /// <summary>
        /// This expects a web context; without it, the method will exit early.
        /// </summary>
        /// <param name="logEvent"></param>
        /// <returns></returns>
        public static string GetExceptionDetails(NLog.LogEventInfo logEvent)
        {
            if (HttpContext.Current == null
                || HttpContext.Current.Request == null
                || HttpContext.Current.Server == null) { return ""; }

            var serverVariables = HttpContext.Current.Request.ServerVariables;
            var lastError = HttpContext.Current.Server.GetLastError();

            string errorMessage = (lastError == null) ? logEvent.FormattedMessage : lastError.InnerException.ToString();

            var errorDetails = new StringBuilder();

            errorDetails.AppendFormat("{0}<br /><br />", errorMessage);
            // This helps give meaningful data in the case of "File does not exist" errors
            errorDetails.AppendFormat("File Path: {0}<br /><br />", HttpContext.Current.Request.FilePath);

            // Stack trace
            if (logEvent.StackTrace != null)
                errorDetails.AppendFormat("<i>Stack Trace:</i><br />{0}<br /><br />", logEvent.StackTrace.ToString());
            else if (logEvent.Exception != null)
                errorDetails.AppendFormat("<i>Stack Trace:</i><br />{0}<br /><br />", logEvent.Exception.Message + logEvent.Exception.StackTrace.ToString());

            // Server variables
            errorDetails.AppendFormat("<i>Server Variables:</i><br />");

            foreach (String s in serverVariables.AllKeys)
                errorDetails.AppendFormat("<p><span>{0,-10}<span>: <b>{1}</b></p>", s, serverVariables[s]);

            return errorDetails.ToString();
        }
Esempio n. 13
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            string version = FileVersionInfo.GetVersionInfo(Application.ExecutablePath).FileVersion;

            Text = string.Format("风月传说 v{0}", version);

            try
            {
                ConfigData.LoadData();
                SystemMenuManager.Load(tabPageGame.Width, tabPageGame.Height);
                MainTipManager.Init(tabPageGame.Height);
                PanelManager.Init(tabPageGame.Width, tabPageGame.Height);
                DbSerializer.Init();
            }
            catch (Exception ex)
            {
                NLog.Warn(ex);
                Close();
            }

            tabPageLogin.BackgroundImage = PicLoader.Read("System", "logback.jpg");
            passport          = WorldInfoManager.LastAccountName;
            labelAccount.Text = string.Format("账户 {0}", passport);
            ChangePage(0);
            myCursor.ChangeCursor("default");

            workThread = new Thread(TimeGo);
            workThread.IsBackground = true;
            workThread.Start();
        }
Esempio n. 14
0
        /// <summary>
        ///使用现有的SQL事务执行一串sql命令(不返回数据集)
        /// </summary>
        /// <param name="sqls">一个现有的事务</param>
        /// <returns>执行命令所影响的行数</returns>
        internal static bool ExecuteNonQuery(List <string> sqls)
        {
            MySqlConnection conn = GetConnection();
            MySqlCommand    cmd  = new MySqlCommand();

            cmd.Connection = conn;
            MySqlTransaction trans = conn.BeginTransaction();

            cmd.Transaction = trans;
            bool flag = true;

            try
            {
                foreach (string sql in sqls)
                {
                    cmd.CommandText = sql;
                    cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                NLog.Error("执行事务失败", ex);
                flag = false;
            }
            if (flag)
            {
                trans.Commit();
            }
            else
            {
                trans.Rollback();
            }
            conn.Close();
            return(flag);
        }
Esempio n. 15
0
        public void Transform(int monId)
        {
            if (IsHero)
            {
                NLog.Warn("hero cannot be Transform");
                return;
            }

            int cardId      = Weapon == null ? 0 : Weapon.CardId;
            var savedWeapon = Weapon == null ? null : Weapon.GetCopy();

            DeleteWeapon();
            int lifp = Life * 100 / Avatar.Hp;

            MonsterCoverBox.RemoveAllCover();
            SkillManager.CheckRemoveEffect();
            OwnerPlayer.State.CheckMonsterEvent(false, this);
            Avatar = new Monster(monId);
            Avatar.UpgradeToLevel(Level);
            OwnerPlayer.State.CheckMonsterEvent(true, this);
            SetBasicData();
            MonsterCoverBox.CheckCover();
            SkillManager.CheckInitialEffect();
            if (cardId > 0)
            {
                AddWeapon(savedWeapon);
            }
            HpBar.SetHp(Avatar.Hp * lifp / 100);
        }
Esempio n. 16
0
        private LogEventInfo CreateLogEventInfo(NLog.LogLevel level, string message, IDictionary<string, object> dictionary, Exception exception)
        {
            LogEventInfo logEvent = new LogEventInfo(level, _logger.Name, message);

            foreach (var item in dictionary)
            {
                logEvent.Properties[item.Key] = item.Value;
            }

            if (exception != null)
            {
                logEvent.Properties["error-source"] = exception.Source;
                if (exception.TargetSite != null)
                {
                    if (exception.TargetSite.DeclaringType != null)
                    {
                        logEvent.Properties["error-class"] = exception.TargetSite.DeclaringType.FullName;
                    }
                    logEvent.Properties["error-method"] = exception.TargetSite.Name;

                }
                logEvent.Properties["error-message"] = exception.Message;

                if (exception.InnerException != null)
                {
                    logEvent.Properties["inner-error-message"] = exception.InnerException.Message;
                }
            }

            return logEvent;
        }
Esempio n. 17
0
        private static void PlayInThread(byte[] file, bool isBGM)
        {//子线程中的处理
            if (isBGM)
            {
                if (_channelBGM != null)
                {
                    bool isPlaying;
                    _channelBGM.isPlaying(out isPlaying);

                    if (isPlaying)
                    {
                        _channelBGM.stop();
                    }
                }
            }

            var info = new CREATESOUNDEXINFO();

            info.length = (uint)file.Length;
            Sound s;

            if (isBGM)
            {
                var result2 = _fmod.createSound(file, MODE.OPENMEMORY | MODE.LOOP_NORMAL, ref info, out s);
                if (result2 != RESULT.OK)
                {
                    NLog.Error("fmod createSound " + result2);
                }
            }
            else
            {
                var result2 = _fmod.createSound(file, MODE.OPENMEMORY, ref info, out s);
                if (result2 != RESULT.OK)
                {
                    NLog.Error("fmod createSound " + result2);
                }
            }

            Channel channel;
            var     result = _fmod.playSound(s, null, false, out channel);

            _fmod.update();
            int index;

            channel.getIndex(out index);
            if (result != RESULT.OK)
            {
                NLog.Error("fmod playSound " + result);
            }

            if (isBGM)
            {
                channel.setVolume(BGMVolume * WorldInfoManager.BGVolumn);
                _channelBGM = channel;
            }
            else
            {
                channel.setVolume(EffectVolume * WorldInfoManager.SoundVolumn);
            }
        }
Esempio n. 18
0
        public static Image GetWeaponImage(int id, int width, int height)
        {
            WeaponConfig weaponConfig = ConfigData.GetWeaponConfig(id);
            string       fname        = string.Format("Weapon/{0}{1}x{2}", weaponConfig.Icon, width, height);

            if (!ImageManager.HasImage(fname))
            {
                Image image = PicLoader.Read("Weapon", string.Format("{0}.JPG", weaponConfig.Icon));
                if (image == null)
                {
                    NLog.Error(string.Format("GetWeaponImage {0} {1} not found", id, fname));
                    return(null);
                }
#if DEBUG
                if (weaponConfig.Remark.Contains("未完成"))
                {
                    Graphics g    = Graphics.FromImage(image);
                    var      icon = PicLoader.Read("System", "NotFinish.PNG");
                    g.DrawImage(icon, 0, 0, 180, 180);
                    g.Save();
                }
#endif

                if (image.Width != width || image.Height != height)
                {
                    image = image.GetThumbnailImage(width, height, null, new IntPtr(0));
                }
                ImageManager.AddImage(fname, image);
            }
            return(ImageManager.GetImage(fname));
        }
Esempio n. 19
0
        public void UseSideKick(LiveMonster lm, ActiveCard card)
        {
            if (!BeforeUseCard(card, lm.Position))
            {
                return;
            }

            try
            {
                Monster mon = new Monster(card.CardId);
                mon.UpgradeToLevel(card.Level);
                if (!card.IsHeroSkill)
                {
                    BattleManager.Instance.StatisticData.GetPlayer(IsLeft).MonsterAdd++;
                }

                var tWeapon = new SideKickWeapon(lm, card.Level, mon);
                lm.AddWeapon(tWeapon);
            }
            catch (Exception e)
            {
                NLog.Warn(e);
                BattleManager.Instance.FlowWordQueue.Add(new FlowWord("未知错误", lm.Position, 0, "Red", 26, 0, 0, 2, 15), false);
                return;
            }
            AfterUseCard(card);
            CardManager.DeleteCardAt(SelectId);
        }
        protected override void Write(NLog.Common.AsyncLogEventInfo logEvent)
        {
            base.Write(logEvent);

            if (LogReceived != null)
                LogReceived(logEvent);
        }
Esempio n. 21
0
		/// <summary>
		/// Instantiates an instance of the LoggerMark class.
		/// </summary>
		/// <param name="location">The location of the mark.</param>
		/// <param name="logger">The logger to log the mark to.</param>
		public LoggerMark(string location, NLog.Logger logger)
		{
			_id = _nextId++;
			_location = location;
			_logger = logger;
			_logger.Trace("Enter " + location + " : " + _id);
			_watch = Stopwatch.StartNew();
		}
Esempio n. 22
0
		public PackageService(
			IServerPackageRepository repository,
			IPackageAuthenticationService authenticationService,
			NLog.ILogger logger)
		{
			_serverRepository = repository;
			_authenticationService = authenticationService;
			_logger = logger;
		}
Esempio n. 23
0
 public static void Write(object element, int depth, NLog.Logger log)
 {
     if (log.IsTraceEnabled)
     {
         ObjectDumper dumper = new ObjectDumper(depth);
         dumper.WriteObject(null, element);
         log.Trace(dumper.builder);
     }
 }
Esempio n. 24
0
		protected override void Write(NLog.LogEventInfo logEvent) {
			var	msg = AppendException(logEvent.FormattedMessage, logEvent.Exception);
			
			_buffer.Add(new LogMessage {
				Level = logEvent.Level,
				Message = msg,
				Source = logEvent.LoggerName,
				Timestamp = logEvent.TimeStamp
			});	
		}
Esempio n. 25
0
        private void ExcuteSourcePathCmd()
        {
            string path = OpenFileDialog();

            if (!string.IsNullOrEmpty(path))
            {
                ImgSourc = Cv.ReadBitmapImage(path);
                NLog.Info(LOG_IDENTITY, "打开图片 {0}", path);
            }
        }
Esempio n. 26
0
 public void OnEventEnd(int id, string type)
 {
     UserProfile.InfoRecord.AddRecordById(RecordInfoConfig.Indexer.TotalEvent, 1);
     if (DungeonId > 0)
     {
         EventList.Add(new DbGismoState(id, type));
         UserProfile.InfoGismo.CheckEventList();
         NLog.Debug("OnEventEnd {0} {1}", id, type);
     }
 }
		public DeployBatchRunner(NLog.Logger logger, ISystemSettings systemSettings, IDeployStateManager deployStateManager, IDeployRunner deployRunner, IDeployQueueManager deployQueueManager, IDeployRequestManager deployRequestManager, ICleanupManager cleanupManager)
		{
			_logger = DIHelper.VerifyParameter(logger);
			_systemSettings = DIHelper.VerifyParameter(systemSettings);
			_deployStateManager = DIHelper.VerifyParameter(deployStateManager);
			_deployRunner = DIHelper.VerifyParameter(deployRunner);
			_deployQueueManager = DIHelper.VerifyParameter(deployQueueManager);
			_deployRequestManager = DIHelper.VerifyParameter(deployRequestManager);
			_cleanupManager = DIHelper.VerifyParameter(_cleanupManager);
		}
Esempio n. 28
0
 static void Main()
 {
     NLog.Start(LogTargets.File);
     DataLoader.Init();
     PicLoader.Init();
     SoundManager.Init();
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new MainForm());
 }
Esempio n. 29
0
        protected override void Append(StringBuilder builder, NLog.LogEventInfo logEvent)
        {
            var actionName = string.Empty;
            if (HttpContext.Current != null)
            {
                actionName = HttpContext.Current.Request.RequestContext.RouteData.Values["action"].ToString();
            }

            builder.Append(actionName);
        }
Esempio n. 30
0
 public LogEvent(NLog.LogEventInfo logEventInfo)
 {
     LoggerName = logEventInfo.LoggerName;
     TimeStamp = logEventInfo.TimeStamp;
     Level = logEventInfo.Level.ToString();
     LogMessage = logEventInfo.FormattedMessage;
     ToolTip = logEventInfo.FormattedMessage;
     Exception = logEventInfo.Exception;
     SetColors(logEventInfo);
 }
Esempio n. 31
0
 public static void RunUnitCapitalMonitor()
 {
     string[] keys = TradeRA.KeySearch("U_*");
     foreach (string key in keys)
     {
         Unit unit = UnitRA.Get(key);
         if (unit.user_id > 0 && unit.ratio_warning > 0)
         {
             if (unit.capital_total < unit.ratio_warning * unit.capital_scale && unit.status_order_enum == StatusOrderEnum.Allowed)
             {
                 StatusOrder model = new StatusOrder(unit.id, StatusOrderEnum.NoBuying);
                 UnitDA.UpdateStatusOrder(model);
                 UnitRA.UpdateStatusOrder(model.status, "U_" + model.id);
                 UserDA.ListParents(unit.user_id).ForEach(user_id =>
                 {
                     MessageBiz.Send(user_id.ToString(), MessageTypeEnum.Unit_Warning, "单元[" + unit.code + "]资产已低于预警线,被禁止买入");
                 });
                 NLog.Info(string.Format("单元[{0}]资产已低于预警线,被禁止买入。总资产:{1}", unit.code, unit.capital_total));
             }
             else if (unit.capital_total > unit.ratio_warning * unit.capital_scale && unit.status_order_enum == StatusOrderEnum.NoBuying)
             {
                 StatusOrder model = new StatusOrder(unit.id, StatusOrderEnum.Allowed);
                 UnitDA.UpdateStatusOrder(model);
                 UnitRA.UpdateStatusOrder(model.status, "U_" + model.id);
                 MessageBiz.Send(unit.user_id.ToString(), MessageTypeEnum.Unit_Recovery, "单元[" + unit.code + "]资产已高于预警线,恢复交易");
             }
         }
         if (unit.user_id > 0 && unit.ratio_close_position > 0 && unit.capital_total < unit.ratio_close_position * unit.capital_scale)
         {
             List <Position> list = PositionRA.List4Unit(unit.id).Where(p => p.count_sellable > 0).ToList();
             if (list.Count > 0)
             {
                 list.ForEach(p =>
                 {
                     Order order = new Order()
                     {
                         code      = p.code,
                         count     = p.count_sellable,
                         type_enum = OrderTypeEnum.Sell,
                         unit_id   = unit.id,
                         price     = DataBiz.GetPriceByPriceType(p.code, OrderPriceEnum.Buy5),
                         user_id   = 1,
                         platform  = 1
                     };
                     Order(order);
                 });
                 UserDA.ListParents(unit.user_id).ForEach(user_id =>
                 {
                     MessageBiz.Send(unit.id.ToString(), MessageTypeEnum.Unit_Close_Position, "单元[" + unit.code + "]资产已低于平仓线,被强制平仓");
                 });
                 NLog.Info(string.Format("单元[{0}]资产已低于平仓线,被强制平仓。总资产:{1}", unit.code, unit.capital_total));
             }
         }
     }
 }
 private void ConfigureLogger(NLog.LogLevel nlogLogLevel)
 {
     var config = new LoggingConfiguration();
     _target = new MemoryTarget {Layout = "${level:uppercase=true}|${message}|${exception}"};
     config.AddTarget("memory", _target);
     var loggingRule = new LoggingRule("*", NLog.LogLevel.Trace, _target);
     loggingRule.DisableLoggingForLevel(nlogLogLevel);
     config.LoggingRules.Add(loggingRule);
     LogManager.Configuration = config;
     _sut = new NLogLogProvider().GetLogger("Test");
 }
		public DeployBatchParallelRunner(NLog.Logger logger, ISystemSettings systemSettings, IDeployStateManager deployStateManager, IDeployQueueManager deployQueueManager, IDeployRequestManager deployRequestManager, IDeploymentPlanBuilder deploymentPlanBuilder, IDIFactory diFactory, ICleanupManager cleanupManager)
		{
			_logger = DIHelper.VerifyParameter(logger);
			_systemSettings = DIHelper.VerifyParameter(systemSettings);
			_deployStateManager = DIHelper.VerifyParameter(deployStateManager);
			_deployQueueManager = DIHelper.VerifyParameter(deployQueueManager);
			_deployRequestManager = DIHelper.VerifyParameter(deployRequestManager);
			_deploymentPlanBuilder = DIHelper.VerifyParameter(deploymentPlanBuilder);
			_diFactory = DIHelper.VerifyParameter(diFactory);
			_cleanupManager = DIHelper.VerifyParameter(cleanupManager);
		}
 private static void DisplayInfo(string info, NLog.Logger logger = null)
 {
     if (null != logger)
     {
         logger.Info(info);
     }
     else
     {
         Console.WriteLine(info);
     }
 }
        public UsersController(IUOW uow, NLog.ILogger logger, ApplicationRoleManager roleManager, ApplicationSignInManager signInManager, ApplicationUserManager userManager, IAuthenticationManager authenticationManager)
        {
            _logger = logger;
            _roleManager = roleManager;
            _signInManager = signInManager;
            _userManager = userManager;
            _authenticationManager = authenticationManager;
            _uow = uow;

            _logger.Debug("InstanceId: " + _instanceId);
        }
        /// <summary>
        /// Indicates that new log information has been received.
        /// </summary>
        /// <param name="log">The log.</param>
        public void IndicateNewActivity(NLog.Common.AsyncLogEventInfo log)
        {
            this.logs.Add(log.LogEvent);
            NotifyOfPropertyChange(() => Logs);

            if (!this.IsActive)
            {
                HasUncheckedActivity = true;
                NotifyOfPropertyChange(() => HasUncheckedActivity);
            }
        }
 public void CheckPoint(NLog.Logger logger, string name = null)
 {
     CheckPoint(name);
     DateTime lastTime;
     if (currentPointsList.Count > 1)
         lastTime = currentPointsList[currentPointsList.Count - 2].Time;
     else
         lastTime = currentGroupLevels.Last().GroupStartTime.Value;
     logger.Debug("Замер производительности [{0}] +{1} секунд.", currentPointsList.Last().Name,
                 (currentPointsList.Last().Time - lastTime).TotalSeconds);
 }
Esempio n. 38
0
        protected void LogReceived(NLog.Common.AsyncLogEventInfo log)
        {
            LogEventViewModel vm = new LogEventViewModel(log.LogEvent);

            Dispatcher.BeginInvoke(new Action(() =>
            {
                if (LogEntries.Count >= 50)
                    LogEntries.RemoveAt(0);
                
                LogEntries.Add(vm);
            }));
        }
Esempio n. 39
0
 public Task <IActionResult> Edit(NLog model)
 {
     return(Task.Factory.StartNew <IActionResult>(() =>
     {
         if (!ModelState.IsValid)
         {
             return Json(ExcutedResult.FailedResult("数据验证失败"));
         }
         NLogRepository.Edit(model, false);
         return Json(ExcutedResult.SuccessResult());
     }));
 }
Esempio n. 40
0
 public async Task <Knowledge> Delete(Knowledge knowledge)
 {
     try
     {
         knowledge = await repository.Delete(knowledge.Id);
     }
     catch (Exception ex)
     {
         NLog.Write(ex);
         knowledge = null;
     }
     return(knowledge);
 }
Esempio n. 41
0
        public void RecostSelectCard()
        {
            var selectCard = CardManager.GetDeckCardAt(SelectId);

            if (selectCard == null)
            {
                NLog.Error(string.Format("RecostSelectCard id={0} not Found", SelectId));
                return;
            }
            AddMp(-selectCard.Mp);
            AddLp(-selectCard.Lp);
            AddPp(-selectCard.Pp);
        }
 private void ConfigureLogger(NLog.LogLevel nlogLogLevel)
 {
     NLogLogManager.ProviderIsAvailableOverride = true;
     var config = new LoggingConfiguration();
     target = new MemoryTarget();
     target.Layout = "${level:uppercase=true}|${message}|${exception}";
     config.AddTarget("memory", target);
     var loggingRule = new LoggingRule("*", LogLevel.Trace, target);
     loggingRule.DisableLoggingForLevel(nlogLogLevel);
     config.LoggingRules.Add(loggingRule);
     NLog.LogManager.Configuration = config;
     sut = new NLogLogManager().GetLogger("Test");
 }
Esempio n. 43
0
        public LogEventViewModel(NLog.LogEventInfo logEventInfo)
        {
            // TODO: Complete member initialization
            this.logEventInfo = logEventInfo;

            ToolTip = logEventInfo.FormattedMessage;
            Level = logEventInfo.Level.ToString();
            FormattedMessage = logEventInfo.FormattedMessage;
            Exception = logEventInfo.Exception;
            LoggerName = logEventInfo.LoggerName;

            SetupColors(logEventInfo);
        }
Esempio n. 44
0
        internal static MemoryTarget AssignMemoryTarget(string name, string layout, NLog.LogLevel minLogLevel = null)
        {
            var target = new MemoryTarget { Layout = layout };

            lock (config)
            {
                config.AddTarget(name, target);
                config.LoggingRules.Add(new LoggingRule("*", minLogLevel ?? NLog.LogLevel.Debug, target));

                NLog.LogManager.Configuration = config;
            }

            return target;
        }
Esempio n. 45
0
 public void Draw(Graphics g)
 {
     try
     {
         foreach (var colorTextCompt in textList)
         {
             colorTextCompt.Draw(g, tickTime);
         }
     }
     catch (Exception e)
     {//遇到过枚举器被修改的异常
         NLog.Debug(e.ToString());
     }
 }
Esempio n. 46
0
        protected override string GetFormattedMessage(NLog.LogEventInfo logEvent)
        {
            var obj = new
            {
                Timestamp = logEvent.TimeStamp.ToUniversalTime(),
                Message = logEvent.FormattedMessage,
                Level = logEvent.Level.Name,
                Exception = logEvent.Exception,
                Logger = logEvent.LoggerName,
                FullEvent = logEvent
            };

            return JsonConvert.SerializeObject(obj, Formatting.None, SerializerSettings);
        }
Esempio n. 47
0
        protected override void Write(NLog.Common.AsyncLogEventInfo logEvent)
        {
            try
            {
                var document = ToDocument(logEvent.LogEvent);
                logCollection.Insert(document);

                logEvent.Continuation(null);
            }
            catch (Exception ex )
            {
                logEvent.Continuation(ex);
            }
        }
Esempio n. 48
0
 /// <summary>
 /// Logs the message to debug.
 /// </summary>
 public override void LogMessage(NLog.LogLevel aLevel)
 {
     // Default value to debug
     if (aLevel == null)
         aLevel = NLog.LogLevel.Debug;
     // if the level is not logged directly return
     if (!_logger.IsEnabled(aLevel))
         return;
     _logger.Log(aLevel, "Data message");
     if (Data == null)
         _logger.Log(aLevel, "Data : null");
     else
         _logger.Log(aLevel, "Data length :-{0}-", Data.Length);
 }
Esempio n. 49
0
        public void Log_levels_are_correctly_converted(LogLevel level, NLog.LogLevel expected)
        {
            var sut = CreateSystemUnderTest();

            var message = fixture.Create<string>();

            IDictionary<string, object> dictionary = new Dictionary<string, object>
            {
                ["message"] = message
            };

            sut.Log(level, dictionary, exception: null);

            mockLogger.Verify(p => p.Log(It.Is<LogEventInfo>(lei => lei.Level == expected)), Times.Once);
        }
        static public bool ShouldAdd(ElasticsearchClient client, ref CandidateFile candidate)
        {
            var searchQuery = new { query = new { term = new { _id = candidate.AliasedPath } } };
            ElasticsearchResponse<string> response;
            var timer = new ScopedTimer();
            using (timer)
            {
                response = client.Search<string>(Media.IndexName, JsonConvert.SerializeObject(searchQuery));
            }

            if (!FirstSearchMsec.HasValue)
            {
                FirstSearchMsec = timer.TotalMilliseconds;
            }

            if (!response.Success)
            {
                response.LogFailure(logger);
                return false;
            }

            candidate.Signature = CalculateSignature(candidate.FullFilename);
            candidate.LengthInBytes = new FileInfo(candidate.FullFilename).Length;


            var searchResponse = JsonConvert.DeserializeObject<SearchResponse>(response.Response);

//            if ((timer.TotalMilliseconds - searchResponse.Took) > 200)
//            {
//                logger.Warn("Search took {1} milliseconds for: {0}", candidate.AliasedPath, timer.TotalMilliseconds);
//            }

            // If there's more than one matching path or the signature is different, go through the add process
            // If it's not already in the index, add it.
            if (searchResponse.Hits.Total != 1)
                return true;

            var media = searchResponse.Hits.Hits.First().Media;
            if (media.Signature != candidate.Signature || media.LengthInBytes != candidate.LengthInBytes)
            {
                logger.Error("Add {0} due to mis-match ({0}, {1} -- {2}, {3})", candidate.AliasedPath,
                    media.Signature, media.LengthInBytes,
                    candidate.Signature, candidate.LengthInBytes);
                return true;
            }

            return false;
        }
Esempio n. 51
0
 public static void RunAccountCapitalMonitor()
 {
     string[] keys = TradeRA.KeySearch("A_*");
     foreach (string key in keys)
     {
         Account account = AccountRA.Get(key);
         if (account.ratio_capital_warning > 0 && account.capital_total > 0 && account.capital_total < account.ratio_capital_warning * account.capital_initial)
         {
             UserDA.ListParents(account.created_by).ForEach(user_id =>
             {
                 MessageBiz.Send(user_id.ToString(), MessageTypeEnum.Account_Warning, "主账户[" + account.code + "]资产已低于预警线");
             });
             NLog.Info(string.Format("主账户[{0}]资产已低于预警线。总资产:{1}", account.code, account.capital_total));
         }
     }
 }
Esempio n. 52
0
 /// <summary>
 /// 给定连接的数据库用假设参数执行一个sql命令(不返回数据集)
 /// </summary>
 /// <param name="cmdText">存储过程名称或者sql命令语句</param>
 /// <param name="commandParameters">执行命令所用参数的集合</param>
 /// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
 /// <returns>执行命令所影响的行数</returns>
 internal static int ExecuteNonQuery(string cmdText, MySqlParameter[] commandParameters, CommandType cmdType = CommandType.Text)
 {
     try
     {
         MySqlCommand cmd = new MySqlCommand();
         PrepareCommand(cmd, cmdType, cmdText, commandParameters);
         int val = cmd.ExecuteNonQuery();
         cmd.Parameters.Clear();
         return(val);
     }
     catch (Exception ex)
     {
         NLog.Error("执行非查询语句失败", ex);
         return(0);
     }
 }
Esempio n. 53
0
 /// <summary>
 /// 用指定的数据库连接字符串执行一个命令并返回一个数据集的第一列
 /// </summary>
 /// <param name="cmdText">存储过程名称或者sql命令语句</param>
 /// <param name="commandParameters">执行命令所用参数的集合</param>
 /// <param name="cmdType">命令类型(存储过程, 文本, 等等)</param>
 internal static object ExecuteScalar(string cmdText, MySqlParameter[] commandParameters, CommandType cmdType = CommandType.Text)
 {
     try
     {
         MySqlCommand cmd = new MySqlCommand();
         PrepareCommand(cmd, cmdType, cmdText, commandParameters);
         object val = cmd.ExecuteScalar();
         cmd.Parameters.Clear();
         return(val);
     }
     catch (Exception ex)
     {
         NLog.Error("执行Scalar查询失败", ex);
         return(null);
     }
 }
Esempio n. 54
0
        public void AddWeapon(IBattleWeapon tw)
        {
            if (Avatar.MonsterConfig.IsBuilding)
            {
                NLog.Warn(string.Format("AddWeapon to building {0}", Avatar.Id));
                return;
            }

            if (Weapon != null)
            {
                Weapon.CheckWeaponEffect(this, -1);
            }
            Weapon = tw;
            //  EAddonBook.UpdateWeaponData(Weapon, OwnerPlayer.State.Weaponskills.Keys(), OwnerPlayer.State.Weaponskills.Values());
            Weapon.CheckWeaponEffect(this, 1);
        }
Esempio n. 55
0
        public async Task <Knowledge> Get(Knowledge knowledge)
        {
            try
            {
                knowledge = await repository.Get(knowledge.Id);

                var tech = await techRepository.Get(knowledge.TechId);

                knowledge.Tech = tech;
            }
            catch (Exception ex)
            {
                NLog.Write(ex);
                knowledge = null;
            }
            return(knowledge);
        }
Esempio n. 56
0
 public static int GetDungeonItemId(string ename)
 {
     if (itemNameIdDict == null)
     {
         itemNameIdDict = new Dictionary <string, int>();
         foreach (var hItemConfig in ConfigData.DungeonItemDict.Values)
         {
             if (itemNameIdDict.ContainsKey(hItemConfig.Ename))
             {
                 NLog.Warn("GetDungeonItemId key={0} exsited", hItemConfig.Ename);
                 continue;
             }
             itemNameIdDict[hItemConfig.Ename] = hItemConfig.Id;
         }
     }
     return(itemNameIdDict[ename]);
 }
Esempio n. 57
0
 public void CheckTrapOnSummon(IMonster mon, IPlayer rival)
 {
     foreach (var trap in trapList)
     {
         var trapConfig = ConfigData.GetSpellTrapConfig(trap.Id);
         if (trapConfig.EffectSummon != null)
         {
             if (self.Mp >= trapConfig.ManaCost && trapConfig.EffectSummon(self, rival, trap, mon, trap.Level))
             {
                 RemoveTrap(trap, trapConfig);
                 NLog.Debug(string.Format("RemoveTrap Summon id={0} cardId={1}", trap.Id, mon.Id));
                 BattleManager.Instance.EffectQueue.Add(new ActiveEffect(EffectBook.GetEffect(trapConfig.UnitEffect), mon as LiveMonster, false));
                 return;
             }
         }
     }
 }
Esempio n. 58
0
        private void tabPageGame_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                SystemMenuManager.DrawAll(e.Graphics);
                MainTipManager.DrawAll(e.Graphics);
                flowController.DrawAll(e.Graphics);

                if (SystemMenuManager.GMMode) //希望在最上层,所以必须最后绘制
                {
                    GMCodeZone.Paint(e.Graphics, tabPageGame.Width, tabPageGame.Height);
                }
            }
            catch (Exception err)
            {
                NLog.Error(err);
            }
        }
Esempio n. 59
0
        public static void Init()
        {
            NLVFS.NLVFS.LoadVfsFile("./SoundResource.vfs");

            Factory.System_Create(out _fmod);
            _fmod.setDSPBufferSize(4096, 2);
            var result = _fmod.init(16, FMOD.INITFLAGS.NORMAL, (IntPtr)null);//16个频道

            if (result != RESULT.OK)
            {
                NLog.Error("fmod SoundManager " + result);
            }
            bgmHistory = new Stack <string>();

            soundThread = new Thread(SoundWork);
            soundThread.Start();
            soundThread.IsBackground = true;
        }
            protected internal override void Execute()
            {
                var functionList = new List <string>
                {
                    "CLRCreateInstance"
                };

                foreach (var functionName in functionList)
                {
                    var functionAddress = NativeImports.GetProcAddress(NativeImports.GetModuleHandle("mscoree"),
                                                                       functionName);

                    if (!this.ProtectNative(functionAddress))
                    {
                        NLog.Error("Failed to protect CLRCreateInstance. FunctionAddress: {0:X}", functionAddress);
                    }
                }
            }