Example #1
0
        public void Write_methods_are_noops_when_null()
        {
            var handler = new LogHandler();

            handler.WriteWarning("Princess Celestia is in danger.");
            handler.WriteInformation("Princess Celestia is on her way.");
            handler.WriteVerbose("Princess Celestia is an alicorn.");
        }
Example #2
0
        public Parser(IList<Object> tokens, ref LogHandler rLogHandler)
        {
            _LogHandler = rLogHandler;
            _tokens = tokens;
            _index = 0;

            _treeExpressions = ParseExpression();
        }
        /// <summary>
        /// Creates a new logging configuration to call the given
        /// delegate when logging occurs at the given level.
        /// </summary>
        /// <param name="level">Level to log at</param>
        /// <param name="handler">Handler to call when logging occurs</param>
        public LogConfiguration(LogLevel level, LogHandler handler)
        {
            Ensure.ArgumentConformsTo<LogLevel>(level, (t) => { return (level != LogLevel.None); }, "level");
            Ensure.ArgumentNotNull(handler, "handler");

            Level = level;
            Handler = handler;
        }
Example #4
0
File: StClient.cs Project: ifzz/FDK
        /// <summary>
        /// Creates a new single-threaded client.
        /// </summary>
        /// <param name="localSignature">should be Signature.Value, where Signature is class generated by LRP generator.</param>
        /// <param name="address">address of remote LRP server.</param>
        /// <param name="port">port of remote LRP server.</param>
        /// <param name="username">an username</param>
        /// <param name="password">a password</param>
        /// <param name="logHandler">a single-threaded log handler; can not be null</param>
        public StClient(string localSignature, string address, Int32 port, string username, string password, LogHandler logHandler)
            : this(localSignature, address, port, username, password)
        {
            if (logHandler == null)
                throw new ArgumentNullException("logHandler", "Log handler can not be null");

            this.logger = new Logger(logHandler);
            this.logger.Output("Local signature = {0}", localSignature);
        }
Example #5
0
        public void WriteWarning_works()
        {
            string result = null;
            var handler = new LogHandler(writeWarning: m => result = m);
            var message = "Princess Celestia is in danger.";

            handler.WriteWarning(message);

            Assert.Equal(message, result);
        }
Example #6
0
        public void WriteInformation_works()
        {
            string result = null;
            var handler = new LogHandler(writeInformation: m => result = m);
            var message = "Princess Celestia is on her way.";

            handler.WriteInformation(message);

            Assert.Equal(message, result);
        }
Example #7
0
 public void Process(LogHandler logHandler)
 {
     if (logHandler != null)
     {
         logHandler(_log);
     }
     //if (logHandler != null)
     //{
     //    logHandler(_log);
     //}
 }
Example #8
0
 public MainGUI()
 {
     InitializeComponent();
     logHandler = new LogHandler(LogString);
     handler = QueueHandler.Instance;
     flowLayoutPanel1.Controls.Add(new EmptyQueue(this));
     server = new NewsServer();
     graphGUI = new GraphGUI();
     panelGraph.Controls.Add(graphGUI);
     Logging.Instance.maingui = this;
 }
        /// <summary>
        /// Creates a new logging configuration to call the given
        /// delegate when logging occurs at the given level.
        /// </summary>
        /// <param name="level">Level to log at</param>
        /// <param name="handler">Handler to call when logging occurs</param>
        public LogConfiguration(LogLevel level, LogHandler handler)
        {
            Ensure.ArgumentConformsTo<LogLevel>(level, (t) => { return (level != LogLevel.None); }, "level");
            Ensure.ArgumentNotNull(handler, "handler");

            Level = level;
            Handler = handler;

            // Explicitly create (and hold a reference to) a callback-delegate to wrap GitTraceHandler().
            GitTraceCallback = GitTraceHandler;
        }
Example #10
0
 private static void Log(LogHandler logHandler, object message, Exception exception)
 {
     try
     {
         if (HttpContext.Current != null && HttpContext.Current.Request != null)
         {
             message += " - URL:" + HttpContext.Current.Request.Url + ", Refer:" + HttpContext.Current.Request.UrlReferrer + ", Browser:" + HttpContext.Current.Request.Browser.Id + ", IP:" + HttpContext.Current.Request.UserHostAddress;
         }
         logHandler(message, exception);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
Example #11
0
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            #region 检查环境
            if ((System.Environment.Version.Major == 4) && (System.Environment.Version.Minor == 0))
            {
                if ((!SystemTools.IsSetupFrameworkUpdate("KB2468871v2")) && (!SystemTools.IsSetupFrameworkUpdate("KB2468871")))
                {
                    var result = MessageBox.Show(GetResourceString("String.Message.NoFrameworkUpdate2"),
                                                 GetResourceString("String.Message.NoFrameworkUpdate"),
                                                 MessageBoxButton.YesNo);
                    if (result == MessageBoxResult.Yes)
                    {
                        System.Diagnostics.Process.Start("https://github.com/Nsiso/NsisoLauncher/wiki/%E5%90%AF%E5%8A%A8%E5%99%A8%E6%8A%A5%E9%94%99%EF%BC%9A%E5%BD%93%E5%89%8D%E7%94%B5%E8%84%91%E7%8E%AF%E5%A2%83%E7%BC%BA%E5%B0%91KB2468871v2%E8%A1%A5%E4%B8%81");
                        System.Environment.Exit(0);
                    }
                }
            }
            #endregion

            #region DEBUG初始化
            //debug
            logHandler = new LogHandler(true);
            AggregateExceptionCatched += (a, b) => logHandler.AppendFatal(b.AggregateException);
            if (e.Args.Contains("-debug"))
            {
                Windows.DebugWindow debugWindow = new Windows.DebugWindow();
                debugWindow.Show();
                logHandler.OnLog += (s, log) => debugWindow?.AppendLog(s, log);
            }
            #endregion

            config = new ConfigHandler();

            #region DEBUG初始化(基于配置文件)
            if (config.MainConfig.Launcher.Debug && !e.Args.Contains("-debug"))
            {
                Windows.DebugWindow debugWindow = new Windows.DebugWindow();
                debugWindow.Show();
                logHandler.OnLog += (s, log) => debugWindow?.AppendLog(s, log);
            }
            #endregion

            #region 数据初始化
            Config.Environment env = config.MainConfig.Environment;

            javaList = Java.GetJavaList();

            //设置版本路径
            string gameroot = null;
            switch (env.GamePathType)
            {
            case GameDirEnum.ROOT:
                gameroot = Path.GetFullPath(".minecraft");
                break;

            case GameDirEnum.APPDATA:
                gameroot = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + "\\.minecraft";
                break;

            case GameDirEnum.PROGRAMFILES:
                gameroot = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ProgramFiles) + "\\.minecraft";
                break;

            case GameDirEnum.CUSTOM:
                gameroot = env.GamePath + "\\.minecraft";
                break;

            default:
                throw new ArgumentException("判断游戏目录类型时出现异常,请检查配置文件中GamePathType节点");
            }
            logHandler.AppendInfo("核心初始化->游戏根目录(默认则为空):" + gameroot);

            //设置JAVA
            Java java = null;
            if (env.AutoJava)
            {
                java = Java.GetSuitableJava(javaList);
            }
            else
            {
                java = javaList.Find(x => x.Path == env.JavaPath);
                if (java == null)
                {
                    java = Java.GetJavaInfo(env.JavaPath);
                }
            }
            if (java != null)
            {
                env.JavaPath = java.Path;
                logHandler.AppendInfo("核心初始化->Java路径:" + java.Path);
                logHandler.AppendInfo("核心初始化->Java版本:" + java.Version);
                logHandler.AppendInfo("核心初始化->Java位数:" + java.Arch);
            }
            else
            {
                logHandler.AppendWarn("核心初始化失败,当前电脑未匹配到JAVA");
            }

            //设置版本独立
            bool verIso = config.MainConfig.Environment.VersionIsolation;
            #endregion

            #region 启动核心初始化
            handler          = new LaunchHandler(gameroot, java, verIso);
            handler.GameLog += (s, log) => logHandler.AppendLog(s, new Log()
            {
                LogLevel = LogLevel.GAME, Message = log
            });
            #endregion

            #region  载核心初始化
            ServicePointManager.DefaultConnectionLimit = 10;
            Download downloadCfg = config.MainConfig.Download;
            downloader = new MultiThreadDownloader();
            if (!string.IsNullOrWhiteSpace(downloadCfg.DownloadProxyAddress))
            {
                WebProxy proxy = new WebProxy(downloadCfg.DownloadProxyAddress, downloadCfg.DownloadProxyPort);
                if (!string.IsNullOrWhiteSpace(downloadCfg.ProxyUserName))
                {
                    NetworkCredential credential = new NetworkCredential(downloadCfg.ProxyUserName, downloadCfg.ProxyUserPassword);
                    proxy.Credentials = credential;
                }
                downloader.Proxy = proxy;
            }
            downloader.ProcessorSize = App.config.MainConfig.Download.DownloadThreadsSize;
            downloader.DownloadLog  += (s, log) => logHandler?.AppendLog(s, log);
            #endregion

            #region NIDE8核心初始化
            if (!string.IsNullOrWhiteSpace(config.MainConfig.User.Nide8ServerID))
            {
                nide8Handler = new Core.Net.Nide8API.APIHandler(config.MainConfig.User.Nide8ServerID);
                nide8Handler.UpdateBaseURL();
            }
            #endregion

            #region 自定义主题初始化
            var custom = config.MainConfig.Customize;
            if (!string.IsNullOrWhiteSpace(custom.AccentColor) && !string.IsNullOrWhiteSpace(custom.AppThme))
            {
                logHandler.AppendInfo("自定义->更改主题颜色:" + custom.AccentColor);
                logHandler.AppendInfo("自定义->更改主题:" + custom.AppThme);
                ThemeManager.ChangeAppStyle(Current, ThemeManager.GetAccent(custom.AccentColor), ThemeManager.GetAppTheme(custom.AppThme));
            }
            #endregion

            //debug
            //throw new Exception();
        }
 public void OnLogHandler(LogHandler msgString)
 {
     if (msgString != null)
        {
     mvLogHandler = msgString;
     Console.WriteLine(msgString);
        }
 }
Example #13
0
        public static async Task GameResultAsync(Context context, GuildModel.GameResult game, GuildModel.GameResult._Result result)
        {
            try
            {
                var gameObject = context.Server.Results.FirstOrDefault(x => x.LobbyID == game.LobbyID && x.GameNumber == game.GameNumber);
                if (result == GuildModel.GameResult._Result.Canceled)
                {
                    gameObject.Result = result;
                    context.Save();
                    await context.Channel.SendMessageAsync("", false, new EmbedBuilder
                    {
                        Color       = Color.DarkOrange,
                        Description = "Success, game has been canceled."
                    }.Build());

                    return;
                }

                var userList = new List <ulong>();
                userList.AddRange(game.Team1);
                userList.AddRange(game.Team2);
                var winEmbed = new EmbedBuilder
                {
                    Color = Color.Green
                };
                var loseEmbed = new EmbedBuilder
                {
                    Color = Color.Red
                };
                foreach (var userID in userList)
                {
                    var user = context.Server.Users.FirstOrDefault(x => x.UserID == userID);
                    if (user == null)
                    {
                        continue;
                    }

                    var maxRank = UserManagement.MaxRole(context, user);
                    if ((result == GuildModel.GameResult._Result.Team1 && game.Team1.Contains(user.UserID)) || (result == GuildModel.GameResult._Result.Team2 && game.Team2.Contains(user.UserID)))
                    {
                        user.Stats.Points += maxRank.WinModifier;
                        user.Stats.Wins++;
                        winEmbed.AddField($"{user.Username} (+{maxRank.WinModifier})", $"Points: {user.Stats.Points}\n" +
                                          $"Wins: {user.Stats.Wins}");
                    }
                    else
                    {
                        user.Stats.Points -= maxRank.LossModifier;
                        if (user.Stats.Points < 0)
                        {
                            if (!context.Server.Settings.GameSettings.AllowNegativeScore)
                            {
                                user.Stats.Points = 0;
                            }
                        }

                        user.Stats.Losses++;

                        loseEmbed.AddField($"{user.Username} (-{maxRank.LossModifier})", $"Points: {user.Stats.Points}\n" +
                                           $"Losses: {user.Stats.Losses}");
                    }

                    var rename = Task.Run(() => UserManagement.UserRenameAsync(context, user));
                    var role   = Task.Run(() => UserManagement.UpdateUserRanksAsync(context, user));
                    user.Stats.GamesPlayed++;
                }

                gameObject.Result = result;
                context.Save();
                await context.Channel.SendMessageAsync("", false, winEmbed.Build());

                await context.Channel.SendMessageAsync("", false, loseEmbed.Build());
            }
            catch (Exception e)
            {
                LogHandler.LogMessage(context, e.ToString(), LogSeverity.Error);
            }
        }
Example #14
0
        ///////////////////////////////////////////////////////////////////////////////////
        public virtual bool DrawSPCChart()
        {
            try
            {
                if (this.DataManager.RawDataTable.Rows.Count < 1)
                {
                    return(false);
                }



                for (int i = 0; i < this.DataManager.RawDataTable.Columns.Count; i++)
                {
                    if (this.DataManager.RawDataTable.Columns[i].ColumnName.Contains("wafer"))
                    {
                        isWaferColumn = true;
                        break;
                    }
                }

                if (isWaferColumn)
                {
                    this._mllstContextType.Add("TIME", null);
                    this._mllstContextType.Add("RAW", null);
                    this._mllstContextType.Add("RAW_USL", null);
                    this._mllstContextType.Add("RAW_UCL", null);
                    this._mllstContextType.Add("RAW_TARGET", null);
                    this._mllstContextType.Add("RAW_LCL", null);
                    this._mllstContextType.Add("RAW_LSL", null);
                    this._mllstContextType.Add("PARAM_LIST", null);
                    this._mllstContextType.Add("RAW_DTTS", null);
                    if (!this._mllstContextType.Contains("EQP_ID"))
                    {
                        this._mllstContextType.Add("EQP_ID", null);
                    }
                    for (int i = 0; i < this.DataManager.RawDataTableOriginal.Columns.Count; i++)
                    {
                        if (!this._mllstContextType.Contains(this.DataManager.RawDataTableOriginal.Columns[i].ColumnName.ToUpper()))
                        {
                            this.DataManager.RawDataTableOriginal.Columns.Remove(this.DataManager.RawDataTableOriginal.Columns[i].ColumnName);
                            i--;
                        }
                    }

                    if (this.DataManager.RawDataTableOriginal.Rows.Count > 0)
                    {
                        this._dtDataSource = this.DataManager.RawDataTableOriginal.Clone();
                        DataTable dtTemp = new DataTable();
                        dtTemp = this.DataManager.RawDataTableOriginal.Clone();
                        foreach (DataRow dr in DataManager.RawDataTableOriginal.Rows)
                        {
                            dtTemp.Clear();
                            if (dr[COLUMN.RAW_DTTS].ToString().Length != 0)
                            {
                                if (dr[COLUMN.RAW_DTTS].ToString().Split(';').Length == dr["RAW"].ToString().Split(';').Length&& dr[COLUMN.RAW_DTTS].ToString().Split(';').Length == dr[COLUMN.PARAM_LIST].ToString().Split(';').Length)
                                {
                                    for (int i = 0; i < dr["RAW"].ToString().Split(';').Length; i++)
                                    {
                                        if (dr["RAW"].ToString().Split(';')[i].Length > 0)
                                        {
                                            dtTemp.ImportRow(dr);
                                        }
                                    }

                                    for (int j = 0; j < dtTemp.Rows.Count; j++)
                                    {
                                        dtTemp.Rows[j]["RAW"]             = dtTemp.Rows[j]["RAW"].ToString().Split(';')[j];
                                        dtTemp.Rows[j][COLUMN.PARAM_LIST] = dtTemp.Rows[j][COLUMN.PARAM_LIST].ToString().Split(';')[j];
                                        dtTemp.Rows[j][COLUMN.RAW_DTTS]   = dtTemp.Rows[j][COLUMN.RAW_DTTS].ToString().Split(';')[j];
                                        if (dtTemp.Rows[j]["SUBSTRATE_ID"] != null && dtTemp.Rows[j]["SUBSTRATE_ID"].ToString().Length > 0 && dtTemp.Rows[j]["SUBSTRATE_ID"].ToString().Split(';').Length > 1)
                                        {
                                            dtTemp.Rows[j]["SUBSTRATE_ID"] = dtTemp.Rows[j]["SUBSTRATE_ID"].ToString().Split(';')[j];
                                        }
                                    }

                                    this._dtDataSource.Merge(dtTemp);
                                }
                            }
                            else
                            {
                                if (dr["RAW"] != null && dr["RAW"].ToString().Length > 0)
                                {
                                    dr[COLUMN.RAW_DTTS] = dr["TIME"];
                                    dtTemp.ImportRow(dr);
                                    this._dtDataSource.Merge(dtTemp);
                                }
                            }
                        }

                        if (this._dtDataSource.Rows.Count > 0)
                        {
                            this._dtDataSource = DataUtil.DataTableImportRow(this._dtDataSource.Select(null, COLUMN.RAW_DTTS));
                        }

                        if (this._dtDataSource.Columns.Contains("TIME"))
                        {
                            this.dtDataSource.Columns.Remove("TIME");
                        }

                        this._dtDataSource.Columns.Add("TIME", typeof(DateTime));
                        this._dtDataSource.Columns.Add(Definition.CHART_COLUMN.TIME2, typeof(string));
                        this._dtDataSource.Columns.Add(CommonChart.COLUMN_NAME_SEQ_INDEX, typeof(int));


                        for (int i = 0; i < this._dtDataSource.Rows.Count; i++)
                        {
                            string sTime = this._dtDataSource.Rows[i]["raw_dtts"].ToString();
                            this._dtDataSource.Rows[i][Definition.CHART_COLUMN.TIME2] = sTime.Substring(0, 16);
                            this._dtDataSource.Rows[i]["TIME"] = sTime;
                            this._dtDataSource.Rows[i][CommonChart.COLUMN_NAME_SEQ_INDEX] = i;
                        }
                    }

                    SeriesInfo si = null;
                    if (this._dtDataSource.Rows.Count > 0)
                    {
                        for (int i = 0; i < this._dtDataSource.Columns.Count; i++)
                        {
                            string seriesName = this._dtDataSource.Columns[i].ColumnName.ToUpper();
                            if (seriesName == "RAW" || seriesName == "RAW_UCL" || seriesName == "RAW_LCL" || seriesName == "RAW_LSL" || seriesName == "RAW_USL" || seriesName == "RAW_TARGET")
                            {
                                si = new SeriesInfo(typeof(Line), seriesName.Replace("RAW_", ""), this._dtDataSource, CommonChart.COLUMN_NAME_SEQ_INDEX, seriesName.ToLower());
                                switch (seriesName)
                                {
                                case "RAW_UCL": si.SeriesColor = _chartUtil.GetSeriesColor((int)ChartUtility.CHAERT_SERIES_COLOR.UCL); break;

                                case "RAW_LCL": si.SeriesColor = _chartUtil.GetSeriesColor((int)ChartUtility.CHAERT_SERIES_COLOR.LCL); break;

                                case "RAW_LSL": si.SeriesColor = _chartUtil.GetSeriesColor((int)ChartUtility.CHAERT_SERIES_COLOR.LSL); break;

                                case "RAW_USL": si.SeriesColor = _chartUtil.GetSeriesColor((int)ChartUtility.CHAERT_SERIES_COLOR.USL); break;

                                case "RAW_TARGET": si.SeriesColor = _chartUtil.GetSeriesColor((int)ChartUtility.CHAERT_SERIES_COLOR.TARGET); break;

                                case "RAW": si.SeriesColor = _chartUtil.GetSeriesColor((int)ChartUtility.CHAERT_SERIES_COLOR.AVG); break;
                                }
                                this.SPCChart.AddSeries(si);
                            }
                        }

                        Series s = null;
                        for (int i = 0; i < this.SPCChart.Chart.Series.Count; i++)
                        {
                            s = this.SPCChart.Chart.Series[i];

                            ((Line)s).LinePen.Width   = 2;
                            ((Line)s).OutLine.Visible = false;
                            ((Line)s).ColorEachLine   = false;
                            ((Line)s).Pointer.Visible = false;
                            ((Line)s).Active          = true;

                            if (s.Title == "RAW")
                            {
                                ((Line)s).LinePen.Width   = 1;
                                ((Line)s).Pointer.Visible = true;
                            }
                        }

                        this.SPCChart.XAxisLabel = BTeeChart.XAxisLabelType.LABEL;
                        this.SPCChart.Chart.Axes.Bottom.Labels.ValueFormat = "yy-MM-dd";
                        this.SPCChart.ChangeXLabelColumnDefault("TIME2");
                        this.SPCChart.Chart.Axes.Bottom.Increment = Steema.TeeChart.Utils.DateTimeStep[(int)Steema.TeeChart.DateTimeSteps.OneDay];
                        this.SPCChart.Refresh();
                    }
                }
                else
                {
                    MakeDataSourceToDrawSPCChart();
                    DrawChartWithSeriesInfo();
                    ChangeSeriesStyle();
                }

                //added by enkim 2012.12.12 SPC-839
                if (!this.SPCChart.Chart.Axes.Left.Labels.ValueFormat.Contains("E"))
                {
                    this.SPCChart.Chart.Axes.Left.Labels.ValueFormat = "#,##0.###";
                }
                //added end

                MakeTipInfo();

                return(true);
            }
            catch (Exception ex)
            {
                MsgClose();
                this.SPCChart.ClearChart();
                LogHandler.ExceptionLogWrite(Definition.APPLICATION_NAME, ex);
                //MSGHandler.DisplayMessage(MSGType.Error, "There is an empty or non-numeric value.");
                return(false);
            }
        }
Example #15
0
        private void FrmMain_Load(object sender, EventArgs e)
        {
            this.transLeftA.Left = this.transAreaA.Width - this.transLeftA.Width;
            this.transLeftA.Visible = true;
            this.transRightA.Left = 0;
            this.transRightA.Visible = false;

            this.transLeftB.Left = this.transAreaB.Width - this.transLeftB.Width;
            this.transLeftB.Visible = true;
            this.transRightB.Left = 0;
            this.transRightB.Visible = false;

            this.toolStripStatusLabelUser.Text = "Operator: " + global::PMSInterface.Program._username;
            frmWorkstation = FrmWorkStation.getFrmWorkstation();
            frmWorkstation.Visible = false;

            frmCommLog = FrmCommunicationLog.getCommunicationLog();
            frmCommLog.MdiParent = this;
            frmCommLog.Left = 10;
            frmCommLog.Top = this.Height - frmCommLog.Height - 130;
            frmCommLog.Visible = true;

            UpdateEvent += new UpdateHandler(frmWorkstation.add);
            LogEvent += new LogHandler(frmCommLog.safeAdd);

            Safe safe = new Safe();
            Registe = safe.GetDateTimeFromDecrypt(true);

            StartListen();

            string specName;
            InstructMap = MyXml.GetInstructMap(out specName);
            if (InstructMap == null)
                return;
        }
Example #16
0
 public void Subscribe(LogHandler handler)
 {
     _handlers.Add(handler);
 }
Example #17
0
		private static async Task Run(string[] args, LogHandler logger, Stream stdout)
		{
			var login_cgi = GetEnvArg("SYNO_LOGIN_CGI", "/usr/syno/synoman/webman/login.cgi");
			var auth_cgi = GetEnvArg("SYNO_AUTHENTICATE_CGI", "/usr/syno/synoman/webman/modules/authenticate.cgi");
			var admin_only = !(GetEnvArg("SYNO_ALL_USERS", "0") == "1");
			var auto_xsrf = GetEnvArg("SYNO_AUTO_XSRF", "1") == "1";
			var skip_auth = GetEnvArg("SYNO_SKIP_AUTH", "0") == "1";
			var query_string = GetEnvArg("QUERY_STRING", "");
			var proxy_host = GetEnvArg("PROXY_HOST", "localhost");
			var proxy_port = GetEnvArg("PROXY_PORT", "8200");

			var xsrftoken = GetEnvArg("HTTP_X_SYNO_TOKEN");
			if (string.IsNullOrWhiteSpace(xsrftoken) && !string.IsNullOrWhiteSpace(query_string))
			{
				// Avoid loading a library just for parsing the token
				var tkre = new Regex(@"SynoToken=(<?token>[^&+])");
				var m = tkre.Match(query_string);
				if (m.Success)
					xsrftoken = m.Groups["token"].Value;
			}

			if (!skip_auth)
			{
				if (string.IsNullOrWhiteSpace(xsrftoken) && auto_xsrf)
				{
					var authre = new Regex(@"""SynoToken""\s?\:\s?""(?<token>[^""]+)""");
					var resp = await ShellExec(login_cgi);

					logger.WriteDebugMessage(string.Format("xsrf response is: {0}", resp));
					
					var m = authre.Match(resp);
					if (m.Success)
						xsrftoken = m.Groups["token"].Value;
					else
						throw new Exception("Unable to get XSRF token");
				}

				var tmpenv = new Dictionary<string, string>();
				tmpenv["QUERY_STRING"] = "SynoToken=" + xsrftoken;

				var username = GetEnvArg("SYNO_USERNAME");

				if (string.IsNullOrWhiteSpace(username))
				{
					username = await ShellExec(auth_cgi, shell: false, exitcode: 0, env: tmpenv);
					logger.WriteDebugMessage(string.Format("Username: {0}", username));				
				}

				if (string.IsNullOrWhiteSpace(username))
					throw new Exception("Not logged in");
				
				username = username.Trim();

				if (admin_only)
				{
					var groups = GetEnvArg("SYNO_GROUP_IDS");

					if (string.IsNullOrWhiteSpace(groups))						
						groups = await ShellExec("id", "-G '" + username.Trim().Replace("'", "\\'") + "'", exitcode: 0) ?? "";
					if (!groups.Split(new char[] { ' ' }).Contains("101"))
						throw new Exception(string.Format("User {0} is not an admin", username));

					logger.WriteDebugMessage("User is admin");
				}
			}

			var path = GetEnvArg("HTTP_X_PROXY_PATH");
			if (string.IsNullOrWhiteSpace(path))
			{
				var xpre = new Regex(@"x-proxy-path=(<?url>[^&+])");
				var m = xpre.Match(query_string);
				if (m.Success)
					path = Uri.UnescapeDataString(m.Groups["url"].Value);
			}

			logger.WriteDebugMessage(string.Format("Path is {0} and query string is {1}", path, query_string));

			if (string.IsNullOrWhiteSpace(path) || !path.StartsWith("/"))
				throw new Exception("Invalid path requested");

			if (!string.IsNullOrWhiteSpace(query_string))
				path += (query_string.StartsWith("?") ? "" : "?") + Uri.EscapeUriString(query_string);

			int port;
			if (!int.TryParse(proxy_port, out port))
				port = 8200;

			logger.WriteDebugMessage(string.Format("About to connect to {0}:{1}", proxy_host, port));

			using (var client = new System.Net.Sockets.TcpClient())
			{
				logger.WriteDebugMessage(string.Format("Connecting to {0}:{1}", proxy_host, port));
				client.Connect(proxy_host, port);
				logger.WriteDebugMessage("Connected");
				
				using (var ns = client.GetStream())
				{
					logger.WriteDebugMessage("Opened TCP stream");
					
					using (var sw = new StreamWriter(ns))
					{
						logger.WriteDebugMessage("Created StreamWriter");
						
						//await ForwardRequest(sw, path, logout);
						//await ForwardResponse(ns, stdout, logout);

						await Task.WhenAll(
							ForwardRequest(sw, path, logger),
							ForwardResponse(ns, stdout, logger)
						);

						logger.WriteDebugMessage("Done processing");
					}
				}
			}
		}
Example #18
0
 public TransferFileController(IMediator mediator, LogHandler logHandler)
 {
     _mediator   = mediator;
     _logHandler = logHandler;
 }
 /// <summary>
 /// Verifies if an element text content is contained inside the actual text.
 /// </summary>
 /// <param name="element">the actual text inside the web element</param>
 /// <param name="expectedText">the expected text part inside the web element</param>
 /// <param name="elementName">the element name</param>
 /// <param name="page">the element page name</param>
 protected void IsTextContained(IWebElement element, String expectedText, String elementName, String page)
 {
     WaitsHandler.WaitForElementToBeVisible(DriverManager.GetDriver(), element, elementName, page);
     Assert.True(element.Text.ToLower().Contains(expectedText.ToLower()), "The element '" + elementName + "' actual text '" + element.Text + "' does not contain '" + expectedText + "' on " + page);
     LogHandler.Info("IsTextContained::The element " + elementName + "text contains in actual text -'" + element.Text + "'");
 }
Example #20
0
 public void SetLogHandler(LogHandler log)
 {
     _log = log;
 }
Example #21
0
        public DataSet DecompressData(DataTable _dtData, LinkedList _llstCondition, LinkedList _llstContextType, bool bDataParsing, bool includingToggleOffData)
        {
            DataSet       dsRetrun = null;
            string        sRef     = string.Empty;
            CommonUtility _comUtil = new CommonUtility();

            string[] arrData         = null;
            string[] arrContext      = null;
            string   strData_List    = "";
            string   strContext_List = "";

            try
            {
                int idxTemp = 0;

                for (int i = 0; i < _dtData.Columns.Count; i++)
                {
                    if (_dtData.Columns[i].ToString().IndexOf(COLUMN.DATA_LIST) >= 0)
                    {
                        idxTemp++;
                    }
                }

                if (_dtData != null && _dtData.Rows.Count > 0)
                {
                    dsRetrun = new DataSet();

                    foreach (DataRow drData in _dtData.Rows)
                    {
                        strData_List = "";

                        if (idxTemp <= 1)
                        {
                            strData_List    = drData[COLUMN.DATA_LIST].ToString();
                            strContext_List = drData[COLUMN.CONTEXT_LIST].ToString();
                        }
                        else
                        {
                            strData_List    = drData[COLUMN.DATA_LIST].ToString();
                            strContext_List = drData[COLUMN.CONTEXT_LIST].ToString();

                            for (int i = 1; i < idxTemp; i++)
                            {
                                strData_List    += drData[COLUMN.DATA_LIST + i.ToString()].ToString();
                                strContext_List += drData[COLUMN.CONTEXT_LIST + i.ToString()].ToString();
                            }
                        }

                        arrContext = strContext_List.ToString().Split('\t');
                        arrData    = strData_List.ToString().Split('\t');

                        AddColumn(arrContext, _dtData, drData, _llstContextType, bDataParsing);
                        AddColumn(arrData, _dtData, drData, _llstContextType, bDataParsing);
                    }

                    if (!_dtData.Columns.Contains(Definition.CHART_COLUMN.TABLENAME))
                    {
                        _dtData.Columns.Add(Definition.CHART_COLUMN.TABLENAME);
                    }

                    for (int i = 0; i < _dtData.Rows.Count; i++)
                    {
                        _dtData.Rows[i][Definition.CHART_COLUMN.TABLENAME] = Definition.TableName.USERNAME_TEMPDATA_SHORT;
                    }

                    if (!includingToggleOffData)
                    {
                        DeleteToggleOffData(_dtData);
                    }

                    DataRow[] drSelectParams = _dtData.Select(_comUtil.NVL(_llstCondition[Definition.CONDITION_KEY_CONTEXT_KEY_LIST]));
                    dsRetrun.Merge(drSelectParams);
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                LogHandler.ExceptionLogWrite(Definition.APPLICATION_NAME, ex);
            }
            finally
            {
                if (_dtData != null)
                {
                    _dtData.Dispose();
                }
            }

            return(dsRetrun);
        }
Example #22
0
        public static async Task RegisterAsync(Context con, GuildModel server, IUser user, string name)
        {
            if (name.Length > 20)
            {
                throw new Exception("Name must be equal to or less than 20 characters long");
            }

            var newUser = new GuildModel.User
            {
                UserID   = user.Id,
                Username = name,
                Stats    = new GuildModel.User.Score
                {
                    Points = server.Settings.Registration.RegistrationBonus
                }
            };

            string userSelfUpdate = null;

            var eloUser = server.Users.FirstOrDefault(x => x.UserID == user.Id);

            if (eloUser != null)
            {
                if (!server.Settings.Registration.AllowMultiRegistration)
                {
                    throw new Exception("You are not allowed to re-register");
                }

                userSelfUpdate = $"{eloUser.Username} => {name}";
                newUser.Stats  = eloUser.Stats;
                newUser.Banned = eloUser.Banned;
                server.Users.Remove(eloUser);
            }
            else
            {
                if (server.Users.Count > 20 && (server.Settings.Premium.Expiry < DateTime.UtcNow || !server.Settings.Premium.IsPremium))
                {
                    throw new Exception($"Premium is required to register more than 20 users. {ConfigModel.Load().PurchaseLink}\n"
                                        + $"Get the server owner to purchase a key and use the command `{con.Prefix}Premium <key>`");
                }
            }

            server.Users.Add(newUser);

            await RegisterUpdatesAsync(con, server, newUser, user);

            await server.Save();

            if (userSelfUpdate == null)
            {
                await con.Channel.SendMessageAsync("", false, new EmbedBuilder { Title = $"Success, Registered as {name}", Description = server.Settings.Registration.Message }.Build());
            }
            else
            {
                await con.Channel.SendMessageAsync("", false, new EmbedBuilder
                {
                    Description = "You have re-registered.\n" +
                                  $"Name: {userSelfUpdate}\n" +
                                  "Role's have been updated\n" +
                                  "Stats have been saved."
                }.Build());
            }

            if (con.Guild.GetRole(server.Ranks.FirstOrDefault(x => x.IsDefault)?.RoleID ?? 0) is IRole RegRole)
            {
                try
                {
                    await(user as IGuildUser).AddRoleAsync(RegRole);
                }
                catch (Exception e)
                {
                    LogHandler.LogMessage(e.ToString(), LogSeverity.Error);
                }
            }
        }
Example #23
0
 /// <summary>
 /// Gets a DevelopmentManager with a certain sessionId
 /// </summary>
 /// <param name="sessionId"></param>
 /// <returns></returns>
 public static IDevelopmentManager GetDevelopmentManager(Guid sessionId)
 {
     LogHandler.LogInfo("************************ user session created " + DateTime.Now + " ************************", LogHandler.LogType.General);
     // Return a user specific DevelopmentManager
     return(_sessions[sessionId]);
 }
Example #24
0
        public override Task <PreconditionResult> CheckPermissionsAsync(ICommandContext iContext, CommandInfo command, IServiceProvider services)
        {
            var context = iContext as SocketCommandContext;

            if (context.Channel is IDMChannel)
            {
                return(Task.FromResult(PreconditionResult.FromError("This is a Guild command")));
            }

            try
            {
                var server = services.GetRequiredService <DatabaseHandler>().Execute <GuildModel>(DatabaseHandler.Operation.LOAD, null, context.Guild.Id.ToString());

                var originalLevel = defaultPermissionLevel;

                var resultInfo = new AccessResult();

                if (server.Settings.CustomCommandPermissions.CustomizedPermission.Any())
                {
                    // Check for a command match
                    var match = server.Settings.CustomCommandPermissions.CustomizedPermission.FirstOrDefault(x => x.IsCommand && x.Name.Equals(command.Name, StringComparison.OrdinalIgnoreCase));
                    if (match != null)
                    {
                        defaultPermissionLevel  = match.Setting;
                        resultInfo.IsCommand    = true;
                        resultInfo.IsOverridden = true;
                        resultInfo.MatchName    = match.Name;
                    }
                }

                if (defaultPermissionLevel == DefaultPermissionLevel.AllUsers)
                {
                    return(Task.FromResult(PreconditionResult.FromSuccess()));
                }

                if (defaultPermissionLevel == DefaultPermissionLevel.Registered)
                {
                    if (server.Users.Any(x => x.UserID == context.User.Id))
                    {
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                }
                else if (defaultPermissionLevel == DefaultPermissionLevel.Moderators)
                {
                    if (context.User.CastToSocketGuildUser().IsModeratorOrHigher(server.Settings.Moderation, context.Client))
                    {
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                }
                else if (defaultPermissionLevel == DefaultPermissionLevel.Administrators)
                {
                    if (context.User.CastToSocketGuildUser().IsAdminOrHigher(server.Settings.Moderation, context.Client))
                    {
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                }
                else if (defaultPermissionLevel == DefaultPermissionLevel.ServerOwner)
                {
                    if (context.User.Id == context.Guild.OwnerId ||
                        context.Client.GetApplicationInfoAsync().Result.Owner.Id == context.User.Id)
                    {
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                }
                else if (defaultPermissionLevel == DefaultPermissionLevel.BotOwner)
                {
                    if (context.Client.GetApplicationInfoAsync().Result.Owner.Id == context.User.Id)
                    {
                        return(Task.FromResult(PreconditionResult.FromSuccess()));
                    }
                }

                return(Task.FromResult(PreconditionResult.FromError($"You do not have the access level of {defaultPermissionLevel}, which is required to run this command\n" +
                                                                    $"Default: {originalLevel}\n" +
                                                                    $"New Level: {defaultPermissionLevel}\n" +
                                                                    $"IsCommand: {resultInfo.IsCommand}\n" +
                                                                    $"IsOverridden: {resultInfo.IsOverridden}\n" +
                                                                    $"Match Name: {resultInfo.MatchName}\n" +
                                                                    $"Command Name: {command.Name}")));
            }
            catch (Exception e)
            {
                LogHandler.LogMessage(e.ToString(), LogSeverity.Critical);
                return(Task.FromResult(PreconditionResult.FromError($"Permissions Error, please report this to Passive")));
            }
        }
Example #25
0
		/// <summary>
		/// Set things in motion so your service can do its work.
		/// </summary>
		protected override void OnStart(string[] args) {
			ChannelServices.RegisterChannel(new TcpServerChannel("HLRChannel", 65122));
			RemotingConfiguration.RegisterWellKnownServiceType(typeof(HLRLib.HLR), "HelloHLR", WellKnownObjectMode.Singleton);
			
			ChannelServices.RegisterChannel(new TcpServerChannel("WTSChannel", 65123));
			RemotingConfiguration.RegisterWellKnownServiceType(typeof(WTSLib.WTS), "HelloWTS", WellKnownObjectMode.Singleton);

			logHandler = new LogHandler(LogWriter);
			wtsHandler = new WTSHandler(ProcessWTS);
			delegateTicketDone = new DoneDelegate(SetTicketResult);

			strCon = string.Format("application name=TicketProcessor;persist security info=true;packet size=4096;data source={0};initial catalog={1};user id={2};password={3};", ConfigurationSettings.AppSettings["PspServer"], "Psp", ConfigurationSettings.AppSettings["DataUser"], DecryptPassword(ConfigurationSettings.AppSettings["DataPassword"]));
			

			sqlTicket = new SqlCommand("sp_GetTicket");
			sqlTicket.CommandType = CommandType.StoredProcedure;
			sqlTicket.Parameters.Add("@fromdate", SqlDbType.DateTime, 8);
			sqlTicket.CommandTimeout = 60;

			sqlSetResult = new SqlCommand("sp_SetTicketResult");
			sqlSetResult.CommandType = CommandType.StoredProcedure;
			sqlSetResult.Parameters.Add("@tno", SqlDbType.BigInt, 8);
			sqlSetResult.Parameters.Add("@state", SqlDbType.Int, 4);
			sqlSetResult.Parameters.Add("@trycount", SqlDbType.Int, 4);
			sqlSetResult.Parameters.Add("@result", SqlDbType.VarChar, 4000);
			sqlSetResult.Parameters.Add("@applydate", SqlDbType.DateTime, 8);
			sqlSetResult.CommandTimeout = 120;
			
			System.Threading.Thread.Sleep(1000);

			timer.Interval = 1000;
			timer.Enabled = (ConfigurationSettings.AppSettings["ProcessTicket"].Equals("true") ? true : false);
		}
Example #26
0
        /// <summary>
        /// 写日志(与UI线程同步)
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="font"></param>
        public void Log(string msg, Font font)
        {
            if (this._rtb.InvokeRequired)
            {
                LogHandler d = new LogHandler(Log);
                this._rtb.Invoke(d, new object[] { msg, font });
                d = null;
            }
            else
            {
                lock (_lockThis)
                {
                    if (font == Font.NoWrap)
                    {
                        this._rtb.AppendText(msg);
                    }
                    else
                    {
                        string str_date = "";
                        if (_showdate)
                        {
                            str_date += DateTime.Now.ToString("yyyy-MM-dd");
                        }

                        if (_showtime)
                        {
                            if (str_date != "")
                            {
                                str_date += " ";
                            }
                            str_date += DateTime.Now.ToString("HH:mm:ss.") + DateTime.Now.Millisecond.ToString("d3");
                        }

                        if (str_date != "")
                        {
                            str_date += " ";
                        }

                        int q_len = this._rtb.Text.Length + str_date.Length;
                        int h_len = this._rtb.Text.Length + str_date.Length + msg.Length - 1;

                        switch (font)
                        {
                        case Font.Content:
                            this._rtb.AppendText(str_date + msg + "\r\n");
                            this._rtb.Select(q_len, h_len);
                            this._rtb.SelectionColor = Color.Black;
                            break;

                        case Font.Pass:
                            this._rtb.AppendText(str_date + msg + "\r\n");
                            this._rtb.Select(q_len, h_len);
                            this._rtb.SelectionColor = Color.Green;
                            this._rtb.SelectionFont  = new System.Drawing.Font("宋体", 10.0f, FontStyle.Regular);
                            break;

                        case Font.Fail:
                            this._rtb.AppendText(str_date + msg + "\r\n");
                            this._rtb.Select(q_len, h_len);
                            this._rtb.SelectionColor = Color.Red;
                            this._rtb.SelectionFont  = new System.Drawing.Font("宋体", 10.0f, FontStyle.Regular);

                            if (_saveerror)
                            {
                                writelog(_savefolder + _name + "Error" + DateTime.Now.ToString("yyyyMMdd") + ".log", str_date + msg);
                            }
                            break;

                        case Font.Attention:
                            this._rtb.AppendText(str_date + msg + "\r\n");
                            this._rtb.Select(q_len, h_len);
                            this._rtb.SelectionColor = Color.Blue;
                            this._rtb.SelectionFont  = new System.Drawing.Font("宋体", 10.0f, FontStyle.Bold);
                            break;

                        default:
                            break;
                        }

                        this._rtb.SelectionStart = this._rtb.TextLength;
                        this._rtb.ScrollToCaret();

                        if (_save)
                        {
                            writelog(_savefolder + _name + DateTime.Now.ToString("yyyyMMdd") + ".log", str_date + msg);
                        }
                    }
                }
            }
        }
        protected void InternalLog(Color foreColor, string fmt, params object[] args)
        {
            if (LogViewer.InvokeRequired)
            {
                if (_Log == null)
                {
                    _Log = new LogHandler (InternalLog);
                }

                LogViewer.Invoke (_Log, new object [] {foreColor, fmt, args});
            }
            else
            {
                string msg = LogMessage (fmt, args);
                msg = DateTime.Now.ToString ("dd/MM/yyyy HH:mm:ss.fff") + " " + msg;

                FileWriter.Write (msg);
                FileWriter.Flush ();

                LogViewer.SelectionLength = 0;
                int start = LogViewer.TextLength;
                LogViewer.AppendText (msg);
                LogViewer.Select (start, msg.Length);
                LogViewer.SelectionColor = foreColor;
            }
        }
Example #28
0
 /// <summary>
 /// 写日志(与UI线程异步执行)
 /// </summary>
 /// <param name="msg"></param>
 /// <param name="font"></param>
 private void LogBeginInvoke(string msg, Font font)
 {
     LogHandler   d  = new LogHandler(Log);
     IAsyncResult ir = d.BeginInvoke(msg, font, new AsyncCallback(LogEndInvoke), null);//最后一个参数为回调函数的参数
 }
Example #29
0
		private static async Task ForwardRequest(StreamWriter sw, string path, LogHandler logger)
		{
			var canceltoken = new CancellationTokenSource();
			var env = Environment.GetEnvironmentVariables();

			/*foreach (var k in env.Keys)
				logger.WriteDebugMessage(string.Format("{0}: {1}", k, env[k]));*/

			await sw.WriteAsync(string.Format("{0} {1} HTTP/1.1{2}", GetEnvArg("REQUEST_METHOD", "").Trim(), path, CRLF));

			logger.WriteDebugMessage("Wrote request header line");

			foreach (var key in env.Keys.Cast<string>().Where<string>(x => x.StartsWith("HTTP_")))
				await sw.WriteAsync(string.Format("{0}: {1}{2}", key.Substring("HTTP_".Length).Replace("_", "-"), env[key], CRLF));

			if (!string.IsNullOrWhiteSpace(GetEnvArg("CONTENT_TYPE")))
				await sw.WriteAsync(string.Format("{0}: {1}{2}", "Content-Type", GetEnvArg("CONTENT_TYPE"), CRLF));
			if (!string.IsNullOrWhiteSpace(GetEnvArg("CONTENT_LENGTH")))
				await sw.WriteAsync(string.Format("{0}: {1}{2}", "Content-Length", GetEnvArg("CONTENT_LENGTH"), CRLF));

			await sw.WriteAsync(string.Format("{0}: {1}{2}", "Connection", "close", CRLF));

			await sw.WriteAsync(CRLF);
			await sw.FlushAsync();
				
			logger.WriteDebugMessage("Wrote all header lines");

			if (new string[] { "POST", "PUT", "PATCH" }.Contains(GetEnvArg("REQUEST_METHOD", "").Trim().ToUpper()))
			{
				logger.WriteDebugMessage(string.Format("Copying StdIn"));

				using(var stdin = Console.OpenStandardInput())
				{
					logger.WriteDebugMessage("Opened StdIn");

					long reqsize;
					if (!long.TryParse(GetEnvArg("CONTENT_LENGTH"), out reqsize))
						reqsize = long.MaxValue;

					var buf = new byte[4 * 1024 * 1024];
					var r = 0;
					while(reqsize > 0)
					{
						logger.WriteDebugMessage(string.Format("Remaining {0} bytes from stdin", reqsize));
						
						r = await stdin.ReadAsync(buf, 0, buf.Length, canceltoken.Token);
						logger.WriteDebugMessage(string.Format("Got {0} bytes from stdin", r));

						if (r == 0)
							break;
						
						reqsize -= r;
						await sw.BaseStream.WriteAsync(buf, 0, r, canceltoken.Token);
					}
				}

				logger.WriteDebugMessage("Copy stdin done");

			}

			logger.WriteDebugMessage("Completed writing request");

		}
Example #30
0
        public JsonResult Import()
        {
            //获取请求的文件
            HttpPostedFileBase file = Request.Files["file"];

            if (file.ContentLength <= 0)
            {
                return(Json(JsonHandler.CreateMessage(0, "文件大小为0")));
            }
            string fileSaveName = System.Guid.NewGuid().ToString("N");

            //文件保存路径
            if (Path.GetExtension(file.FileName) != ".xlsx" && Path.GetExtension(file.FileName) != ".xls")
            {
                return(Json(JsonHandler.CreateMessage(0, "请上传.xlsx文件")));
            }
            string fileSavePath = HttpRuntime.AppDomainAppPath + "/Uploads/" + fileSaveName + Path.GetExtension(file.FileName);
            Stream stream       = file.InputStream; //文件输入流

            byte[] buffer;
            //每次上传的字节
            int bufferSize = 4096;
            //总大小
            long totalLength = stream.Length;
            long writterSize = 0;//已上传文件大小

            using (FileStream fs = new FileStream(fileSavePath, FileMode.Create))
            {
                while (writterSize < totalLength)
                {
                    if (totalLength - writterSize >= bufferSize)
                    {
                        buffer = new byte[bufferSize];
                    }
                    else
                    {
                        buffer = new byte[totalLength - writterSize];
                    }
                    //读出上传文件到字节数组
                    stream.Read(buffer, 0, buffer.Length);
                    //写入文件流
                    fs.Write(buffer, 0, buffer.Length);
                    writterSize += buffer.Length;
                }
            }
            var personList = new List <MIS_PersonModel>();

            bool checkResult = m_BLL.CheckImportData(fileSavePath, personList, ref errors);

            if (checkResult)
            {
                m_BLL.SaveImportData(personList);
                LogHandler.WriteServiceLog(GetUserId(), "导入成功", "成功", "导入", "Spl_Person");
                return(Json(JsonHandler.CreateMessage(1, Suggestion.InsertSucceed)));
            }
            else
            {
                string ErrorCol = errors.Error;
                LogHandler.WriteServiceLog(GetUserId(), ErrorCol, "失败", "导入", "Spl_Person");
                return(Json(JsonHandler.CreateMessage(0, Suggestion.InsertFail + "<br/>" + ErrorCol)));
            }
        }
Example #31
0
 public DefaultListener(Levels level, LogHandler logfunc)
 {
     Parents = new List<ILogParent>();
     Level = level;
     LogFunc = logfunc;
 }
Example #32
0
 /// <summary>
 ///     ログ出力(致命的エラー)を実施します。
 /// </summary>
 /// <param name="tag">タグ名</param>
 /// <param name="message">メッセージ</param>
 public void Fatal(string tag, object message)
 {
     //TODO:フィルターの追加。というかそもそもこのクラスでやるかどうか。。。
     LogHandler.LogFormat(LogType.Log, null, _format, tag, GetString(message), MRLogType.Fatal);
 }
Example #33
0
        /// <summary>
        /// 删除流程表
        /// </summary>
        public bool DeleteWorkFlow(int autoIdInt)
        {
            using (SqlConnection conn = new SqlConnection(BaseSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        SqlCommand cmd = new SqlCommand("", conn, trans);

                        if (!CheckCurrentData_Delete(cmd, autoIdInt))
                        {
                            return(false);
                        }

                        //查询当前使用节点的记录
                        cmd.CommandText = string.Format("select Count(*) from BS_DataCurrentNode where CurrentNodeId in (select AutoId from BS_WorkFlowNode where WorkFlowId = {0})", autoIdInt);
                        if (DataTypeConvert.GetInt(cmd.ExecuteScalar()) > 0)
                        {
                            trans.Rollback();
                            MessageHandler.ShowMessageBox("有单据正在使用当前的流程信息,不可以删除。");
                            return(false);
                        }

                        //查询历史单据使用节点的记录
                        cmd.CommandText = string.Format("select COUNT(*) from BS_WorkFlowDataHandle where NodeId in (select AutoId from BS_WorkFlowNode where WorkFlowId = {0})", autoIdInt);
                        if (DataTypeConvert.GetInt(cmd.ExecuteScalar()) > 0)
                        {
                            trans.Rollback();
                            MessageHandler.ShowMessageBox("有历史单据使用当前的流程信息,不可以删除。");
                            return(false);
                        }

                        cmd.CommandText = string.Format("select * from BS_WorkFlow where AutoId = {0}", autoIdInt);
                        DataTable      tmpTable = new DataTable();
                        SqlDataAdapter adpt     = new SqlDataAdapter(cmd);
                        adpt.Fill(tmpTable);

                        if (tmpTable.Rows.Count > 0)
                        {
                            //保存日志到日志表中
                            LogHandler.RecordLog(cmd, string.Format("删除流程表信息:流程名称的原值为[{0}],备注的原值为[{1}]", DataTypeConvert.GetString(tmpTable.Rows[0]["WorkFlowText"]), DataTypeConvert.GetString(tmpTable.Rows[0]["Remark"])));
                        }

                        cmd.CommandText = string.Format("delete from BS_WorkFlowNodeHandle where NodeId in (select AutoId from BS_WorkFlowNode where WorkFlowId = {0})", autoIdInt);
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = string.Format("delete from BS_WorkFlowNodeToNode where NodeId in (select AutoId from BS_WorkFlowNode where WorkFlowId = {0})", autoIdInt);
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = string.Format("delete from BS_WorkFlowNode where WorkFlowId = {0}", autoIdInt);
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = string.Format("delete from BS_WorkFlow where AutoId = {0}", autoIdInt);
                        cmd.ExecuteNonQuery();

                        trans.Commit();
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
Example #34
0
 /// <summary>
 ///     ログフォーマットに従ってログ出力を実施します。
 /// </summary>
 /// <param name="mrLogType">
 ///     <see cref="MRLogType" />
 /// </param>
 /// <param name="format">ログフォーマット</param>
 /// <param name="args">パラメータ</param>
 public void LogFormat(MRLogType mrLogType, string format, params object[] args)
 {
     //TODO:フィルターの追加。というかそもそもこのクラスでやるかどうか。。。
     LogHandler.LogFormat(LogType.Log, null, format, args, mrLogType);
 }
 public KickUserRcon(SocketCommandContext context, InteractiveService interactive, DataService data, LogHandler log)
 {
     _context     = context;
     _interactive = interactive;
     _data        = data;
     _log         = log;
 }
Example #36
0
        /// <summary>
        /// The page is loading.
        /// </summary>
        /// <param name="pageContext">The page content.</param>
        public override void OnLoad(HttpPageContext pageContext)
        {
            try
            {
                string notesHtmlData = "";

                // Get the response data.
                Data.NotesFormService.notes noteHtml = new Data.NotesFormService.notes();

                // If post back
                if (base.IsPostBack)
                {
                    // If form data exists then
                    // wrire ti the file.
                    if (base.Form != null)
                    {
                        if (base.Form.Count > 0)
                        {
                            StreamWriter streamWriter = null;
                            try
                            {
                                // Get the 'NoteName' key name from the form.
                                string notename = base.Form.AllKeys.Where(u => u.ToLower() == "notename".ToLower()).First();

                                // Save path.
                                string savePath = base.UploadDirectory + "Notes\\" + base.Form[notename] + ".txt";

                                // If the directory does not exist
                                // then create the directory.
                                if (!Directory.Exists(Path.GetDirectoryName(savePath)))
                                {
                                    Directory.CreateDirectory(Path.GetDirectoryName(savePath));
                                }

                                // Create a new file or over write extisting file.
                                using (streamWriter = System.IO.File.CreateText(savePath))
                                {
                                    for (int i = 0; i < base.Form.Count; i++)
                                    {
                                        // Write the line of data.
                                        streamWriter.WriteLine(base.Form.Keys[i] + " : " + base.Form.Get(i));
                                    }

                                    // Close the stream.
                                    streamWriter.Flush();
                                    streamWriter.Close();
                                }
                            }
                            catch (Exception fex)
                            {
                                LogHandler.WriteTypeMessage(
                                    fex.Message,
                                    MethodInfo.GetCurrentMethod(),
                                    Helper.EventApplicationName());
                            }
                            finally
                            {
                                if (streamWriter != null)
                                {
                                    streamWriter.Close();
                                }
                            }

                            // Get the response data.
                            notesHtmlData = noteHtml.TransformText().
                                            Replace("value=\"NoteName\"", "value=\"" + base.Form.Get("NoteName") + "\"").
                                            Replace("value=\"01/01/01\"", "value=\"" + base.Form.Get("NoteDate") + "\"").
                                            Replace("value=\"ContextName\"", "value=\"" + base.Form.Get("ContextName") + "\"").
                                            Replace("value=\"NoteData\"", base.Form.Get("NoteData"));
                        }
                    }
                }
                else
                {
                    // Get the response data.
                    notesHtmlData = noteHtml.TransformText().
                                    Replace("value=\"NoteName\"", "").
                                    Replace("value=\"01/01/01\"", "").
                                    Replace("value=\"ContextName\"", "").
                                    Replace("value=\"NoteData\"", "");
                }

                // Send the new content.
                base.AlternativeContent = Encoding.UTF8.GetBytes(notesHtmlData);
            }
            catch (Exception ex)
            {
                LogHandler.WriteTypeMessage(
                    ex.Message,
                    MethodInfo.GetCurrentMethod(),
                    Helper.EventApplicationName());
            }
        }
Example #37
0
        //[SupportFilter]
        public JsonResult Create(Flow_FormContent model)
        {
            //当前的Form模版
            Flow_Form formModel = formBLL.m_Rep.Find(Convert.ToInt32(model.FormId));

            //初始化部分数据
            model.CreateTime = ResultHelper.NowTime.ToString("yyyy-MM-dd");
            model.UserId     = GetUserId();
            model.Title      = formModel.Name;
            model.TimeOut    = DateTime.Now.AddDays(30).ToString("yyyy-MM-dd");
            if (model != null)
            {
                if (formContentBLL.m_Rep.Create(model))
                {
                    //创建成功后把步骤取出
                    List <Flow_Step> stepModelList = stepBLL.m_Rep.FindPageList(ref setNoPagerAscBySort, a => a.FormId == model.FormId).ToList();
                    //查询步骤
                    int    listCount = stepModelList.Count();
                    string IsEnd     = "false";
                    for (int i = 0; i < listCount; i++)
                    {
                        string               nextStep          = "";
                        Flow_Step            stepModel         = stepModelList[i];
                        List <Flow_StepRule> stepRuleModelList = stepRuleBLL.m_Rep.FindList(a => a.StepId == stepModel.Id.ToString()).ToList();
                        //获取规则判断流转方向
                        foreach (Flow_StepRule stepRuleModel in stepRuleModelList)
                        {
                            string val = new FlowHelper().GetFormAttrVal(stepRuleModel.AttrId, formModel, model);
                            //有满足流程结束的条件
                            if (!JudgeVal(stepRuleModel.AttrId, val, stepRuleModel.Operator, stepRuleModel.Result))
                            {
                                if (stepRuleModel.NextStep != "0")
                                {
                                    //获得跳转的步骤
                                    nextStep = stepRuleModel.NextStep;
                                    //跳到跳转后的下一步
                                    for (int j = 0; j < listCount; j++)
                                    {
                                        if (stepModelList[j].Id.ToString() == nextStep)
                                        {
                                            i = j;//跳到分支后的下一步
                                        }
                                    }
                                }
                                else
                                {
                                    //nextStep=0流程结束
                                    IsEnd = "true";
                                }
                            }
                        }

                        #region 插入步骤
                        //插入步骤审核表
                        Flow_FormContentStepCheck stepCheckModel = new Flow_FormContentStepCheck();
                        stepCheckModel.ContentId  = model.Id.ToString();
                        stepCheckModel.StepId     = stepModel.Id.ToString();
                        stepCheckModel.State      = FlowStateEnum.Progress.ToString();
                        stepCheckModel.StateFlag  = "false";//true此步骤审核完成
                        stepCheckModel.CreateTime = ResultHelper.NowTime.ToString("yyyy-MM-dd");
                        if (nextStep != "" && nextStep != "0")
                        {
                            stepCheckModel.IsEnd = (i == listCount) ? "true" : IsEnd;//是否流程的最后一步
                        }
                        else
                        {
                            stepCheckModel.IsEnd = (i == listCount - 1) ? "true" : IsEnd;//是否流程的最后一步
                        }

                        stepCheckModel.IsCustom = stepModel.FlowRule == FlowRuleEnum.Customer.ToString() ? "true" : "false";
                        if (stepCheckBLL.m_Rep.Create(stepCheckModel))//新建步骤成功
                        {
                            InsertChecker(model, i, stepModel, stepCheckModel);
                        }
                        #endregion
                        #region 插入分支步骤
                        if (nextStep != "" && nextStep != "0")
                        {
                            //不是最后一个审核人
                            if (listCount < 1 || i != listCount - 1)
                            {
                                IsEnd = "false";
                            }
                            else
                            {
                                IsEnd = "true";
                            }

                            stepCheckModel            = new Flow_FormContentStepCheck();
                            stepCheckModel.ContentId  = model.Id.ToString();
                            stepCheckModel.StepId     = stepModel.Id.ToString();
                            stepCheckModel.State      = FlowStateEnum.Progress.ToString();
                            stepCheckModel.StateFlag  = "false"; //true此步骤审核完成
                            stepCheckModel.CreateTime = ResultHelper.NowTime.ToString("yyyy-MM-dd");
                            stepCheckModel.IsEnd      = IsEnd;   //是否流程的最后一步


                            stepCheckModel.IsCustom = stepModel.FlowRule == FlowRuleEnum.Customer.ToString() ? "true" : "false";
                            if (stepCheckBLL.m_Rep.Create(stepCheckModel))//新建步骤成功
                            {
                                InsertChecker(model, i, stepModel, stepCheckModel);
                            }
                        }
                        #endregion

                        if (IsEnd == "true")//如果是最后一步就无需要下面继续了
                        {
                            break;
                        }
                        IsEnd = "true";
                    }



                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",AttrA" + model.AttrA, "成功", "创建", "Flow_FormContent");
                    return(Json(JsonHandler.CreateMessage(1, Resource.InsertSucceed)));
                }
                else
                {
                    string ErrorCol = errors.Error;
                    LogHandler.WriteServiceLog(GetUserId(), "Id" + model.Id + ",AttrA" + model.AttrA + "," + ErrorCol, "失败", "创建", "Flow_FormContent");
                    return(Json(JsonHandler.CreateMessage(0, Resource.InsertFail + ErrorCol)));
                }
            }
            else
            {
                return(Json(JsonHandler.CreateMessage(0, Resource.InsertFail)));
            }
        }
Example #38
0
        /// <summary>
        /// 更新生产计划单的Bom信息的需求日期
        /// </summary>
        public void ProductionSchedule_BomListReqDate(string psNoStr, List <int> autoIdList, DateTime reqDate)
        {
            if (autoIdList.Count == 0)
            {
                return;
            }

            using (SqlConnection conn = new SqlConnection(BaseSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        SqlCommand cmd = new SqlCommand("", conn, trans);

                        //方案一 只更新选中的一条记录
                        //string sqlStr = "";
                        //foreach (int autoId in autoIdList)
                        //{
                        //    sqlStr += string.Format(" {0},", autoId);
                        //}
                        //cmd.CommandText = string.Format("Update PB_ProductionScheduleBom set ReqDate = '{1}' where AutoId in ({0})", sqlStr.Substring(0, sqlStr.Length - 1), reqDate.ToString("yyyy-MM-dd"));
                        //cmd.ExecuteNonQuery();


                        //方案二 更新选中的记录和它下面的子节点
                        int    resultInt = 0;
                        string errorText = "";
                        foreach (int autoIdInt in autoIdList)
                        {
                            SqlCommand   cmd_proc = new SqlCommand("", conn, trans);
                            SqlParameter p1       = new SqlParameter("@AutoId", SqlDbType.Int);
                            p1.Value = autoIdInt;
                            SqlParameter p2 = new SqlParameter("@ReqDate", SqlDbType.DateTime);
                            p2.Value = reqDate;
                            IDataParameter[] updateParas = new IDataParameter[] { p1, p2 };
                            BaseSQL.RunProcedure(cmd_proc, "P_PSBom_UpdateReqDate", updateParas, out resultInt, out errorText);
                            if (resultInt != 1)
                            {
                                trans.Rollback();
                                MessageHandler.ShowMessageBox("更新生产计划单的Bom信息的需求日期错误--" + errorText);
                            }

                            string logStr = string.Format("生产计划单[{0}]更新Bom零件节点的需求日期,ID为[{1}],需求日期为[{2}]", psNoStr, autoIdInt, reqDate.ToString("yyyy-MM-dd"));
                            LogHandler.RecordLog(cmd, logStr);
                        }

                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
Example #39
0
        /// <summary>
        /// 保存工位信息
        /// </summary>
        public int SaveStnSummaryList(string autoQuotationNoStr, DataRow headRow, ref int lastNewStnListAutoId)
        {
            using (SqlConnection conn = new SqlConnection(BaseSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        SqlCommand cmd      = new SqlCommand("", conn, trans);
                        DateTime   nowTime  = BaseSQL.GetServerDateTime();
                        bool       addState = false;
                        if (headRow.RowState == DataRowState.Added)//新增
                        {
                            if (DataTypeConvert.GetString(headRow["SSNo"]) == "")
                            {
                                string ssNoStr = BaseSQL.GetMaxCodeNo(cmd, "SS");
                                cmd.CommandText = string.Format("Insert into SA_StnSummary(SSNo, AutoQuotationNo, Prepared, PreparedIp, GetTime) values ('{0}', '{1}', '{2}', '{3}', '{4}')", ssNoStr, autoQuotationNoStr, SystemInfo.user.EmpName, SystemInfo.HostIpAddress, nowTime.ToString("yyyy-MM-dd HH:mm:ss"));
                                cmd.ExecuteNonQuery();

                                headRow["SSNo"] = ssNoStr;
                            }

                            headRow["Prepared"]   = SystemInfo.user.EmpName;
                            headRow["PreparedIp"] = SystemInfo.HostIpAddress;
                            headRow["GetTime"]    = nowTime;
                            addState = true;
                        }
                        else//修改
                        {
                            //int autoIdInt = DataTypeConvert.GetInt(headRow["AutoId"]);
                            //if (CheckStnList_IsModule(cmd, autoIdInt))
                            //{
                            //    headRow.Table.RejectChanges();
                            //    return -1;
                            //}
                        }

                        //保存日志到日志表中
                        string logStr = LogHandler.RecordLog_DataRow(cmd, "工位明细信息", headRow, "AutoId");

                        cmd.CommandText = "select * from SA_StnSummaryList where 1=2";
                        SqlDataAdapter adapterHead  = new SqlDataAdapter(cmd);
                        DataTable      tmpHeadTable = new DataTable();
                        adapterHead.Fill(tmpHeadTable);
                        BaseSQL.UpdateDataTable(adapterHead, headRow.Table);

                        if (addState)
                        {
                            cmd.CommandText      = "Select @@IDENTITY";
                            lastNewStnListAutoId = DataTypeConvert.GetInt(cmd.ExecuteScalar());
                        }

                        trans.Commit();
                        return(1);
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
Example #40
0
        /// <summary>
        /// 审批选中的多条生产计划单
        /// </summary>
        public bool ApproveProductionSchedule_Multi(DataTable headTable, int saveTypeInt)
        {
            string   psNoListStr = "";
            DateTime serverTime  = BaseSQL.GetServerDateTime();

            for (int i = 0; i < headTable.Rows.Count; i++)
            {
                if (DataTypeConvert.GetBoolean(headTable.Rows[i]["Select"]))
                {
                    psNoListStr += string.Format("'{0}',", DataTypeConvert.GetString(headTable.Rows[i]["PsNo"]));
                    headTable.Rows[i]["PsState"] = 2;
                }
            }

            psNoListStr = psNoListStr.Substring(0, psNoListStr.Length - 1);
            if (!CheckPSState(headTable, psNoListStr, false, true, true, false))
            {
                return(false);
            }

            using (SqlConnection conn = new SqlConnection(BaseSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        SqlCommand cmd = new SqlCommand("", conn, trans);
                        cmd.CommandText = string.Format("Update PB_ProductionSchedule set PsState={1} where PsNo in ({0})", psNoListStr, 2);
                        cmd.ExecuteNonQuery();

                        //保存日志到日志表中
                        DataRow[] headRows = headTable.Select("select=1");
                        for (int i = 0; i < headRows.Length; i++)
                        {
                            string logStr = LogHandler.RecordLog_OperateRow(cmd, "生产计划单", headRows[i], "PsNo", "审批", SystemInfo.user.EmpName, serverTime.ToString("yyyy-MM-dd HH:mm:ss"));

                            string psNoStr         = DataTypeConvert.GetString(headRows[i]["PsNo"]);
                            string codeFileNameStr = DataTypeConvert.GetString(headRows[i]["CodeFileName"]);
                            int    qtyInt          = DataTypeConvert.GetInt(headRows[i]["PlannedQty"]);
                            //根据BOM的定义生成物料明细
                            if (saveTypeInt == 1)//保存BOM的第一级节点
                            {
                                cmd.CommandText = string.Format("insert into PB_ProductionScheduleBom (PsNo, CodeFileName, Qty, TotalQty) select '{1}', LevelMaterielNo, Qty, Qty * {2} from BS_BomMateriel where MaterielNo = '{0}'", codeFileNameStr, psNoStr, qtyInt);
                                cmd.ExecuteNonQuery();
                            }
                            else//保存BOM的最末节点
                            {
                                SqlCommand cmd_proc  = new SqlCommand("", conn, trans);
                                string     errorText = "";
                                if (!Update_ProductionScheduleBom(cmd_proc, psNoStr, out errorText))
                                {
                                    trans.Rollback();
                                    MessageHandler.ShowMessageBox("更新生产计划单BOM信息错误--" + errorText);
                                    return(false);
                                }
                            }
                        }

                        trans.Commit();
                        headTable.AcceptChanges();
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        headTable.RejectChanges();
                        throw ex;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
Example #41
0
        /// <summary>
        /// 保存报价信息
        /// </summary>
        public int SaveQuotationInfo(DataRow headRow, DataTable listTable)
        {
            using (SqlConnection conn = new SqlConnection(BaseSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        SqlCommand cmd = new SqlCommand("", conn, trans);

                        //DateTime nowTime = BaseSQL.GetServerDateTime();
                        if (headRow.RowState == DataRowState.Added)//新增
                        {
                            headRow["AutoQuotationNo"] = BaseSQL.GetMaxCodeNo(cmd, "QN");
                            headRow["PreparedIp"]      = SystemInfo.HostIpAddress;
                            //headRow["RecordDate"] = nowTime;
                            for (int i = 0; i < listTable.Rows.Count; i++)
                            {
                                listTable.Rows[i]["AutoQuotationNo"] = headRow["AutoQuotationNo"];
                                //listTable.Rows[i]["QuotationDate"] = nowTime;
                            }
                        }
                        else//修改
                        {
                            string autoQuotationNoStr = DataTypeConvert.GetString(headRow["AutoQuotationNo"]);

                            if (!CheckState(headRow.Table, listTable, autoQuotationNoStr, false, true))
                            {
                                return(-1);
                            }

                            if (CheckQuotationInfo_IsSalesOrder(cmd, autoQuotationNoStr))
                            {
                                headRow.Table.RejectChanges();
                                listTable.RejectChanges();
                                return(-1);
                            }

                            //for (int i = 0; i < listTable.Rows.Count; i++)
                            //{
                            //    if (listTable.Rows[i].RowState == DataRowState.Deleted)
                            //        continue;
                            //    else if (listTable.Rows[i].RowState == DataRowState.Added)
                            //    {
                            //        listTable.Rows[i]["AutoQuotationNo"] = headRow["AutoQuotationNo"];
                            //        listTable.Rows[i]["QuotationDate"] = nowTime;
                            //    }
                            //}

                            headRow["ModifierId"] = SystemInfo.user.AutoId;
                            //headRow["Modifier"] = SystemInfo.user.EmpName;
                            headRow["ModifierIp"]   = SystemInfo.HostIpAddress;
                            headRow["ModifierTime"] = BaseSQL.GetServerDateTime();
                        }

                        //保存日志到日志表中
                        string logStr = LogHandler.RecordLog_DataRow(cmd, "报价信息", headRow, "AutoQuotationNo");

                        cmd.CommandText = "select * from SA_QuotationBaseInfo where 1=2";
                        SqlDataAdapter adapterHead  = new SqlDataAdapter(cmd);
                        DataTable      tmpHeadTable = new DataTable();
                        adapterHead.Fill(tmpHeadTable);
                        BaseSQL.UpdateDataTable(adapterHead, headRow.Table);

                        cmd.CommandText = "select * from SA_QuotationPriceInfo where 1=2";
                        SqlDataAdapter adapterList  = new SqlDataAdapter(cmd);
                        DataTable      tmpListTable = new DataTable();
                        adapterList.Fill(tmpListTable);
                        BaseSQL.UpdateDataTable(adapterList, listTable);

                        trans.Commit();

                        return(1);
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        headRow.Table.RejectChanges();
                        listTable.RejectChanges();
                        throw ex;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
Example #42
0
 public void SetDebugLogHandler(LogHandler Logger)
 {
     this.DebugLogger = Logger;
     DEBUG = (Logger != null);
     DUMPPACKETS = (Logger != null);
 }
Example #43
0
 public static void Reset()
 {
     _loggers.Clear();
     _appenders = null;
 }
Example #44
0
 public static LogHandler getLogger()
 {
     if (theLogger == null) theLogger = new ConsoleLogger(UsuallyDebugging);
     return theLogger;
 }
Example #45
0
        /// <summary>
        /// 读取txt日志文件
        /// </summary>
        /// <param name="filepath">文件路径</param>
        public static void ReadLog(string filepath, LogHandler delHandleLog)
        {
            if (!File.Exists(filepath))
                return;
            StreamReader sr = null;
            try
            {
                sr = new StreamReader(filepath, System.Text.Encoding.UTF8);
                string EveryLineLog = string.Empty;

                while (!sr.EndOfStream)
                {
                    EveryLineLog = sr.ReadLine();

                    if (EveryLineLog != null)
                    {
                        delHandleLog(EveryLineLog);
                    }
                }
                sr.Close();
                sr.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                if (sr != null)
                {
                    sr.Close();
                    sr.Dispose();
                }
            }
        }
Example #46
0
        /// <summary>
        /// 审批信息上移顺序号
        /// </summary>
        public void ApprovalList_UpSequence(string typeNoStr, int opSeqInt)
        {
            using (SqlConnection conn = new SqlConnection(BaseSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        SqlCommand cmd = new SqlCommand("", conn, trans);
                        cmd.CommandText = string.Format("select * from PUR_ApprovalList where typeNo='{0}' and AppSequence={1}", typeNoStr, opSeqInt);
                        DataTable      listTable = new DataTable();
                        SqlDataAdapter adpt      = new SqlDataAdapter(cmd);
                        adpt.Fill(listTable);
                        if (listTable.Rows.Count == 0)
                        {
                            return;
                        }
                        if (listTable.Rows.Count == 1)
                        {
                            opSeqInt = DataTypeConvert.GetInt(listTable.Rows[0]["AppSequence"]);
                            if (opSeqInt == 1)
                            {
                                return;
                            }
                            int opAutoId   = DataTypeConvert.GetInt(listTable.Rows[0]["AutoId"]);
                            int opApprover = DataTypeConvert.GetInt(listTable.Rows[0]["Approver"]);

                            listTable.Rows.Clear();
                            cmd.CommandText = string.Format("select * from PUR_ApprovalList where typeNo='{0}' and AppSequence={1}", typeNoStr, opSeqInt - 1);
                            adpt            = new SqlDataAdapter(cmd);
                            adpt.Fill(listTable);
                            if (listTable.Rows.Count == 0)
                            {
                                DeleteApprovalList_AddSequence(cmd, typeNoStr, opSeqInt - 1);
                            }
                            else
                            {
                                int upAutoId = DataTypeConvert.GetInt(listTable.Rows[0]["AutoId"]);
                                cmd.CommandText = string.Format("Update PUR_ApprovalList set AppSequence={1} where AutoId={0}", opAutoId, opSeqInt - 1);
                                cmd.ExecuteNonQuery();
                                cmd.CommandText = string.Format("Update PUR_ApprovalList set AppSequence={1} where AutoId={0}", upAutoId, opSeqInt);
                                cmd.ExecuteNonQuery();
                            }

                            //保存日志到日志表中
                            string logStr = string.Format("对[审批信息]表进行[上移]操作:主键的值为[{0}],审批类型的值为[{1}],审批人的值为[{2}]", opAutoId, typeNoStr, opApprover);
                            LogHandler.RecordLog(cmd, logStr);
                        }
                        else
                        {
                            ApprovalList_Reset(cmd, typeNoStr);
                        }
                        trans.Commit();
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        throw ex;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
Example #47
0
		public static void Main(string[] args)
		{
			var debug = GetEnvArg("PROXY_DEBUG", "0") == "1";
			var logfile = GetEnvArg("PROXY_LOGFILE", "/var/log/duplicat-proxy.log");

			using (var logout = new StreamWriter(File.Open(logfile, System.IO.FileMode.Append, FileAccess.Write, FileShare.ReadWrite)))
			using(var stdout = Console.OpenStandardOutput())
			{
				if (logout != null)
					logout.AutoFlush = true;


				var logger = new LogHandler(logout, debug);
				
				try
				{
					//stdout.WriteTimeout = (int)ACTIVITY_TIMEOUT.TotalMilliseconds;
					logger.WriteDebugMessage("Started!");
					logger.WriteDebugMessage(string.Format("Processing request for target url: {0}", GetEnvArg("HTTP_X_PROXY_PATH")));

					logger.WriteDebugMessage(string.Format("Redirects: {0},{1},{2}", Console.IsInputRedirected, Console.IsOutputRedirected, Console.IsErrorRedirected));

					if (args == null)
						args = new string[0];
					
					foreach(var a in args)
						logger.WriteDebugMessage(string.Format("arg: {0}", a));

					Run(args, logger, stdout).Wait();
				}
				catch (Exception ex)
				{
					var rex = ex;
					if (rex is AggregateException && (rex as AggregateException).Flatten().InnerExceptions.Count == 1)
						rex = (rex as AggregateException).Flatten().InnerExceptions.First();

					if (debug)
						logger.WriteMessage(string.Format("Failed: {0}", rex));
					else
						logger.WriteMessage(string.Format("Failed: {0}", rex.Message));
					
					try 
					{
						stdout.Write(ERROR_MESSAGE, 0, ERROR_MESSAGE.Length);
					}
					catch (Exception ex2) 
					{
						logger.WriteDebugMessage(string.Format("Failed to set error status: {0}", ex2));
					}
				}
			}
		}
Example #48
0
 private void pbGo_Click(object sender, EventArgs e)
 {
     myLogger = new GuiLogger(false);
     myLogger.CFSLog += new CFSLogHandler(GuiLogger_CFSLog);
     this.tbLog.Text = "starting to restore from " + tbFirstFile.Text + " to " + tbOutPath.Text;
     yourLogger = Logger.setLogger(myLogger);
     restorer = new CFSRestore(tbFirstFile.Text, tbOutPath.Text);
     restorer.CFSRestoreCompletion += new CFSRestoreCompletionHandler(CFSRestore_CFSRestoreCompletion);
     restoThread = new Thread(new ThreadStart(restorer.Restore));
     busy = true;
     restoThread.Start();
     Thread.Sleep(500);
     manageGuiState();
 }
Example #49
0
		private static async Task ForwardResponse(Stream source, Stream target, LogHandler logger)
		{
			var buf = new byte[8 * 1024];
			int r = 0;
			int offset = 0;
			var lastmatch = 0;
			var status = false;
			long contentlength = -1;
			var canceltoken = new CancellationTokenSource();

			logger.WriteDebugMessage("Forward response");

			while ((r = await source.ReadAsync(buf, offset, buf.Length - offset, canceltoken.Token)) != 0)
			{
				logger.WriteDebugMessage(string.Format("Read {0} bytes", r));
				
				offset += r;
				var ix = Array.IndexOf(buf, (byte)13, 0, offset);

				while (ix >= 0 && ix < offset - 1)
				{
					if (buf[ix + 1] == 10)
					{
						if (!status)
						{
							status = true;
							logger.WriteDebugMessage("Writing: Status: " + System.Text.Encoding.ASCII.GetString(buf, lastmatch + HTTP_HEAD_LEN, ix - lastmatch - HTTP_HEAD_LEN));

							await target.WriteAsync(STATUS_PREFIX, 0, STATUS_PREFIX.Length, canceltoken.Token);
							await target.WriteAsync(buf, lastmatch + HTTP_HEAD_LEN, (ix - lastmatch - HTTP_HEAD_LEN) + 2, canceltoken.Token);

							logger.WriteDebugMessage("Wrote status line");
						}
						else
						{
							// Blank line and we are done
							if (ix - lastmatch == 0)
							{
								logger.WriteDebugMessage(string.Format("Completed header, writing remaining {0} bytes", offset - lastmatch));

								await target.WriteAsync(buf, lastmatch, offset - lastmatch, canceltoken.Token);

								// Adjust remaining data length
								if (contentlength > 0)
									contentlength -= offset - lastmatch - 2;
							

								logger.WriteDebugMessage(string.Format("Body has remaining {0} bytes", contentlength));

								while(contentlength > 0)
								{
									r = await source.ReadAsync(buf, 0, (int)Math.Min(buf.Length, contentlength), canceltoken.Token);
									if (r == 0)
										break;

									contentlength -= r;


									await target.WriteAsync(buf, 0, r, canceltoken.Token);

									logger.WriteDebugMessage(string.Format("Body has remaining {0} bytes", contentlength));
								}

								await target.FlushAsync(canceltoken.Token);

								//await logout.WriteDebugMessageAsync(string.Format("Last body chunck: {0}", System.Text.Encoding.ASCII.GetString(buf, 0, r)));
								logger.WriteDebugMessage(string.Format("Completed response forward"));

								target.Close();

								return;
							}
							else
							{

								var header = System.Text.Encoding.ASCII.GetString(buf, lastmatch, ix - lastmatch) ?? string.Empty; 
								if (header.StartsWith("Content-Length: ", StringComparison.OrdinalIgnoreCase))
								if (!long.TryParse(header.Substring("Content-Length: ".Length), out contentlength))
									contentlength = -1;
									
								logger.WriteDebugMessage("Writing: " + header);

								await target.WriteAsync(buf, lastmatch, (ix - lastmatch) + 2, canceltoken.Token);
							}
							
						}

						lastmatch = ix + 2;
					}

					//await logger.WriteDebugMessageAsync(string.Format("Buf stats: {0},{1},{2},{3}", buf.Length, ix, offset, lastmatch));
					
					ix = Array.IndexOf(buf, (byte)13, ix + 1, offset - ix - 1);
				}
			}

		}
Example #50
0
 public static void Remove(string keyName)
 {
     LogHandler.Info($"Cache - Removeing {keyName}");
     cache.Remove(keyName);
 }
Example #51
0
        public void WriteVerbose_works()
        {
            string result = null;
            var handler = new LogHandler(writeVerbose: m => result = m);
            var message = "Princess Celestia is an alicorn.";

            handler.WriteVerbose(message);

            Assert.Equal(message, result);
        }
Example #52
0
        ///// <summary>
        ///// 查询流程表中的文件信息
        ///// </summary>
        //public string QueryWorkFlow_Document(int autoIdInt, string workFlowTextStr, string tempFilePath)
        //{
        //    string sqlStr = string.Format("select AutoId, FileByte from BS_WorkFlow where AutoId = {0}", autoIdInt);
        //    DataTable docTable = BaseSQL.GetTableBySql(sqlStr);
        //    if (docTable.Rows.Count == 0)
        //        return "";
        //    Byte[] fileByte = (byte[])docTable.Rows[0]["FileByte"];

        //    FileHandler fileHandler = new FileHandler();
        //    fileHandler.ByteArrayToFile(fileByte, tempFilePath);
        //    return tempFilePath;
        //}

        ///// <summary>
        ///// 更新某个单据模板
        ///// </summary>
        //public bool UpdateWorkFlow(SqlCommand cmd, int autoIdInt, string iniPath)
        //{
        //    long streamLength = 0;
        //    Byte[] buffer = new FileHandler().FileToByteArray(iniPath, ref streamLength);

        //    SqlParameter p1 = new SqlParameter("@filebyte", SqlDbType.Image);
        //    p1.Value = buffer;
        //    SqlParameter p2 = new SqlParameter("@AutoId", SqlDbType.Int);
        //    p2.Value = autoIdInt;
        //    cmd.Parameters.Add(p1);
        //    cmd.Parameters.Add(p2);
        //    cmd.CommandText = "Update BS_WorkFlow Set FileByte = @filebyte where AutoId = @AutoId";
        //    cmd.ExecuteNonQuery();


        //    return true;
        //}

        /// <summary>
        /// 保存流程表
        /// </summary>
        public int SaveWorkFlow(DataRow headRow, List <DiagramConnector> connectorList, List <DiagramShape> shapeList)
        {
            using (SqlConnection conn = new SqlConnection(BaseSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        SqlCommand cmd = new SqlCommand("", conn, trans);

                        DateTime nowTime   = BaseSQL.GetServerDateTime();
                        int      autoIdInt = 0;

                        if (CheckWorkFlowType(cmd, DataTypeConvert.GetInt(headRow["AutoId"]), DataTypeConvert.GetInt(headRow["WorkFlowTypeAutoId"])))
                        {
                            return(0);
                        }

                        if (headRow.RowState == DataRowState.Added)//新增
                        {
                            headRow["GetTime"] = nowTime;
                            //新增保存流程主表
                            cmd.CommandText = string.Format("Insert into BS_WorkFlow (WorkFlowText, Remark, GetTime) values ('{0}', '{1}', '{2}')", DataTypeConvert.GetString(headRow["WorkFlowText"]), DataTypeConvert.GetString(headRow["Remark"]), nowTime.ToString("yyyy-MM-dd HH:mm:ss"));
                            autoIdInt       = cmd.ExecuteNonQuery();
                            if (autoIdInt != 1)
                            {
                                trans.Rollback();
                                headRow.Table.RejectChanges();
                                MessageHandler.ShowMessageBox("保存流程表信息错误,请重新新增操作。");
                                return(-1);
                            }
                            cmd.CommandText   = "select @@IDENTITY";
                            autoIdInt         = DataTypeConvert.GetInt(cmd.ExecuteScalar());
                            headRow["AutoId"] = autoIdInt;

                            InsertWorkFlowNodeInfo(cmd, autoIdInt, connectorList, shapeList);
                        }
                        else//修改
                        {
                            if (!CheckCurrentData(cmd, DataTypeConvert.GetInt(headRow["AutoId"])))
                            {
                                return(0);
                            }

                            //修改保存流程主表
                            cmd.CommandText = "select * from BS_WorkFlow where 1=2";
                            SqlDataAdapter adapterHead  = new SqlDataAdapter(cmd);
                            DataTable      tmpHeadTable = new DataTable();
                            adapterHead.Fill(tmpHeadTable);
                            BaseSQL.UpdateDataTable(adapterHead, headRow.Table);
                            autoIdInt = DataTypeConvert.GetInt(headRow["AutoId"]);

                            UpdateWorkFlowNodeInfo(cmd, autoIdInt, connectorList, shapeList);
                        }

                        //保存日志到日志表中
                        string logStr = LogHandler.RecordLog_DataRow(cmd, "流程表信息", headRow, "AutoId");

                        //UpdateWorkFlow(cmd, autoIdInt, tempFilePath);

                        trans.Commit();
                        headRow.AcceptChanges();

                        return(1);
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        headRow.Table.RejectChanges();
                        throw ex;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
Example #53
0
        /// <summary>
        /// 取消审批选中的多条生产计划单
        /// </summary>
        public bool CancelApproveProductionSchedule_Multi(DataTable headTable)
        {
            string psNoListStr = "";

            for (int i = 0; i < headTable.Rows.Count; i++)
            {
                if (DataTypeConvert.GetBoolean(headTable.Rows[i]["Select"]))
                {
                    psNoListStr += string.Format("'{0}',", DataTypeConvert.GetString(headTable.Rows[i]["PsNo"]));
                    headTable.Rows[i]["PsState"] = 1;
                }
            }

            psNoListStr = psNoListStr.Substring(0, psNoListStr.Length - 1);
            if (!CheckPSState(headTable, psNoListStr, true, false, true, false))
            {
                return(false);
            }

            using (SqlConnection conn = new SqlConnection(BaseSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        SqlCommand cmd = new SqlCommand("", conn, trans);
                        cmd.CommandText = string.Format("Update PB_ProductionSchedule set PsState={1} where PsNo in ({0})", psNoListStr, 1);
                        cmd.ExecuteNonQuery();
                        cmd.CommandText = string.Format("Delete from PB_ProductionScheduleBom where PsNo in ({0})", psNoListStr);
                        cmd.ExecuteNonQuery();

                        DateTime serverTime = BaseSQL.GetServerDateTime();

                        //保存日志到日志表中
                        DataRow[] headRows = headTable.Select("select=1");
                        for (int i = 0; i < headRows.Length; i++)
                        {
                            ////检查是否有下级的入库单
                            //if (CheckApplyWarehouseWarrant(cmd, DataTypeConvert.GetString(orderHeadRows[i]["OrderHeadNo"])))
                            //{
                            //    trans.Rollback();
                            //    headTable.RejectChanges();
                            //    //MessageHandler.ShowMessageBox("采购订单已经有适用的入库单记录,不可以操作。");
                            //    MessageHandler.ShowMessageBox(f.tsmiCgddyj.Text);
                            //    return false;
                            //}

                            string logStr = LogHandler.RecordLog_OperateRow(cmd, "生产计划单", headRows[i], "PsNo", "取消审批", SystemInfo.user.EmpName, serverTime.ToString("yyyy-MM-dd HH:mm:ss"));
                        }

                        trans.Commit();
                        headTable.AcceptChanges();
                        return(true);
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        headTable.RejectChanges();
                        throw ex;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
Example #54
0
 public static LogHandler setLogger(LogHandler lh)
 {
     LogHandler rv = theLogger;
     theLogger = lh;
     return rv;
 }
Example #55
0
 public void SetLogHandler(LogHandler Logger)
 {
     this.Logger = Logger;
 }
Example #56
0
        /// <summary>
        /// 保存生产计划单
        /// </summary>
        public int SaveProductionSchedule(DataRow headRow)
        {
            using (SqlConnection conn = new SqlConnection(BaseSQL.connectionString))
            {
                conn.Open();
                using (SqlTransaction trans = conn.BeginTransaction())
                {
                    try
                    {
                        SqlCommand cmd = new SqlCommand("", conn, trans);

                        //if (!CheckPrReqApplyBeyondCount(cmd, DataTypeConvert.GetString(orderHeadRow["OrderHeadNo"]), orderListTable))
                        //{
                        //    return 0;
                        //}

                        //if (DataTypeConvert.GetString(headRow["PsNo"]) == "")//新增
                        if (headRow.RowState == DataRowState.Added)//新增
                        {
                            string orderHeadNo = BaseSQL.GetMaxCodeNo(cmd, "PN");
                            headRow["PsNo"]       = orderHeadNo;
                            headRow["PreparedIp"] = SystemInfo.HostIpAddress;
                            headRow["GetTime"]    = BaseSQL.GetServerDateTime();
                        }
                        else//修改
                        {
                            if (!CheckPSState(headRow.Table, string.Format("'{0}'", DataTypeConvert.GetString(headRow["PsNo"])), false, true, true, true))
                            {
                                return(-1);
                            }

                            headRow["Modifier"]     = SystemInfo.user.EmpName;
                            headRow["ModifierIp"]   = SystemInfo.HostIpAddress;
                            headRow["ModifierTime"] = BaseSQL.GetServerDateTime();
                        }

                        //保存日志到日志表中
                        string logStr = LogHandler.RecordLog_DataRow(cmd, "生产计划单", headRow, "PsNo");

                        cmd.CommandText = "select * from PB_ProductionSchedule where 1=2";
                        SqlDataAdapter adapterHead  = new SqlDataAdapter(cmd);
                        DataTable      tmpHeadTable = new DataTable();
                        adapterHead.Fill(tmpHeadTable);
                        BaseSQL.UpdateDataTable(adapterHead, headRow.Table);

                        //Set_PrReqHead_End(cmd, orderListTable);

                        trans.Commit();
                        return(1);
                    }
                    catch (Exception ex)
                    {
                        trans.Rollback();
                        headRow.Table.RejectChanges();
                        throw ex;
                    }
                    finally
                    {
                        conn.Close();
                    }
                }
            }
        }
Example #57
0
        // This is called from the main form to tell us where the application was launched from (where to look for the .conf files)
        // and also gives us the LogHandler method so we can send debug messages to the main form.
        public bool Init(string ConfDirectory, LogHandler Logger)
        {
            // Pass the LogHandler on down to the PacketManager

            Packets.SetLogHandler(Logger);

            string ErrorMessage = "";

            // Here we init all the patch version specific decoders. The only reason one should fail to init is if it can't
            // find it's patch_XXXX.conf.
            //
            // If at least one initialises successfully, then return true  to the caller, otherwise return false
            bool AllDecodersFailed = true;

            PatchDecoder.Init(ConfDirectory, ref ErrorMessage);

            foreach (PatchSpecficDecoder p in PatchList)
            {
                Logger("Initialising patch " + p.GetVersion());
                if (!p.Init(ConfDirectory, ref ErrorMessage))
                    Logger(ErrorMessage);
                else
                    AllDecodersFailed = false;
            }

            return !AllDecodersFailed;
        }
Example #58
0
 public UIAccessProcessor(LogHandler log)
 {
     header = new HandlerNode();
     priviousNode = header;
     printLog = log;
     IsStop = false;
     conditionNode = preNode = postNode = nodeAtFirstTime = null;
     HandlerTimeOuts = 5000;
 }
Example #59
0
 public static List <T> GetItemList(string keyName)
 {
     LogHandler.Info($"Cache - Getting {keyName}");
     return(cache.Get <List <T> >(keyName));
 }
Example #60
-1
        public Scanner(TextReader input, ref LogHandler rLogHandler)
        {
            _logHandler = rLogHandler;
            _tokenList = new List<Object>();

            Scan(input);
        }