Beispiel #1
0
        private string Test(HttpContext context)
        {
            string        strJsonResult = string.Empty;
            string        userAccount   = string.Empty;
            ErrorCodeInfo error         = new ErrorCodeInfo();
            Guid          transactionid = Guid.NewGuid();
            string        funname       = "Test";

            try
            {
                do
                {
                    //string strCommand = "set-Mailbox -Identity \"CN=cs6121,OU=B集团控股,OU=佳兆业集团,DC=bnc2,DC=cn\" -ExtensionCustomAttribute3 \"11111\"";
                    string strCommand = $"Search-Mailbox -Identity \"CN=cs6121,OU=B集团控股,OU=佳兆业集团,DC=bnc2,DC=cn\" " +
                                        $"-SearchQuery 'subject:\"test111\"  AND sent>=\"2019-07-04 00:00:01\" AND sent<=\"2019-07-06 00:00:01\"'  -DeleteContent -Force";
                    Log4netHelper.Info(strCommand);
                    SensitiveMailManager manager = new SensitiveMailManager(ClientIP);
                    manager.test(transactionid, strCommand, out strJsonResult);
                } while (false);
            }
            catch (Exception ex)
            {
                error.Code = ErrorCode.Exception;
                LoggerHelper.Error("SensitiveMail.ashx调用接口test异常", context.Request.RawUrl, ex.ToString(), transactionid);
                LoggerHelper.Info(userAccount, funname, context.Request.RawUrl, Convert.ToString(error.Code), false, transactionid);
                strJsonResult = JsonHelper.ReturnJson(false, Convert.ToInt32(error.Code), error.Info);
            }

            return(strJsonResult);
        }
Beispiel #2
0
 //暂测试保存功能
 public static void Deal_DifDgdValue(string FormName, DataTable aftersave_dt, DataGridViewX dgd, string descrip_str)
 {
     try
     {
         DataTable Judge_dt = ((DataTable)dgd.DataSource).Copy();
         if (aftersave_dt != null && aftersave_dt.Rows.Count == Judge_dt.Rows.Count)
         {
             for (int i = 0; i < aftersave_dt.Rows.Count; i++)
             {
                 for (int j = 0; j < aftersave_dt.Columns.Count; j++)
                 {
                     if (aftersave_dt.Rows[i][j] != Judge_dt.Rows[i][j])
                     {
                         Log4netHelper.Info(new DgdDealHelper().GetType(), string.Format("编辑表:{0}-{1},编辑项:{2},原值:{3},变化值:{4},修改者:{5}", FormName, descrip_str, Judge_dt.Rows[i][0], aftersave_dt.Rows[i][j], Judge_dt.Rows[i][j], Constant.CurUserName()));
                         SQliteHelper.ExecuteDataTable(Constant.strConnectSQLite, CommandType.Text, string.Format("insert into {0} (tablename,tableitem,oldvalue,newvalue,modifiedby,modifieddate,descrip)values('{1}','{2}','{3}','{4}','{5}','{6}','{7}')", Constant.RecordLog_sqlname, FormName, Judge_dt.Rows[i][0], aftersave_dt.Rows[i][j], Judge_dt.Rows[i][j], Constant.CurUserName(), DateTime.Now, descrip_str), null);
                     }
                     continue;
                 }
             }
         }
         else
         {
             Log4netHelper.Warn(new DgdDealHelper().GetType(), string.Format("检查编辑表:{0}时发生错误,修改前后行数不一致,修改者:{1}", FormName, Constant.CurUserName()));
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Beispiel #3
0
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            base.OnActionExecuted(context);
            if (IsLog)
            {
                Stopwatch.Stop();

                string url    = context.HttpContext.Request.Path + context.HttpContext.Request.QueryString;
                string method = context.HttpContext.Request.Method;

                string qs = ActionArguments;

                var user = "";
                //检测是否包含'Authorization'请求头,如果不包含则直接放行
                if (context.HttpContext.Request.Headers.ContainsKey("Authorization"))
                {
                    var tokenHeader = context.HttpContext.Request.Headers["Authorization"];
                    tokenHeader = tokenHeader.ToString().Substring("Bearer ".Length).Trim();

                    TokenModel tm = JwtHelper.SerializeToken(tokenHeader);
                    user = tm.UserName;
                }

                var str = $"\n 方法:{Controller}:{Action} \n " +
                          $"地址:{url} \n " +
                          $"方式:{method} \n " +
                          $"参数:{qs}\n " +
                          $"用户:{user}\n " +
                          $"耗时:{Stopwatch.Elapsed.TotalMilliseconds} 毫秒";
                Log4netHelper.Info(typeof(string), str);
            }
        }
Beispiel #4
0
        /// <summary>
        /// 初始化数据库连接
        /// </summary>
        /// <returns></returns>
        public static SqlSugarClient GetInstance()
        {
            SqlSugarClient db = new SqlSugarClient(
                new ConnectionConfig()
            {
                ConnectionString      = AppSettingHelper.MysqlConnection,
                DbType                = DbType.MySql,
                IsAutoCloseConnection = true,
                InitKeyType           = InitKeyType.Attribute
            });

            //db.Ado.IsEnableLogEvent = true;
            //db.Ado.LogEventStarting = (sql, pars) =>
            //{

            //};
            db.Aop.OnLogExecuted = (sql, pars) => //SQL执行完事件
            {
                Log4netHelper.Info("SQL执行完事件:" + sql + "\r\n" +
                                   db.Utilities.SerializeObject(pars.ToDictionary(s => s.ParameterName, s => s.Value))
                                   );
            };
            db.Aop.OnLogExecuting = (sql, pars) => //SQL执行前事件
            {
            };
            db.Aop.OnError = (exp) =>//执行SQL 错误事件
            {
            };
            db.Aop.OnExecutingChangeSql = (sql, pars) => //SQL执行前 可以修改SQL
            {
                return(new KeyValuePair <string, SugarParameter[]>(sql, pars));
            };
            return(db);
        }
        /// <summary>
        /// 关闭连接
        /// </summary>
        public void Stop()
        {
            if (socket == null)
            {
                isRunning = false;
                return;
            }

            try
            {
                //This ensures that all data is sent and received on the connected socket before it is closed.
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
                Log4netHelper.Info(string.Format("关闭{0}:{1}成功", ip, port));
            }
            catch (Exception ex)
            {
                socket.Close();
                Log4netHelper.Error(string.Format("关闭{0}:{1}时发生异常:{2}。", ip, port, ex));
            }
            finally
            {
                socket    = null;
                isRunning = false;
            }
        }
        public static void AddNode_Func(TreeNode Addnode, string change_str)
        {
            try
            {
                string formname = Addnode.Text;
                if (change_str == "添加传感器BOM")
                {
                    string lcbom_meaid_value = Guid.NewGuid().ToString();
                    string Mainbom           = AddBOM_Module(Addnode, change_str, lcbom_meaid_value);
                    if (Mainbom == "")
                    {
                        return;
                    }
                    string lcbominfo_str = DgdDealHelper.GetCombineInfo(Constant.Maingage_dt).ToString();

                    //插入数据库
                    sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("insert into {0} (lcbom_meaid,lcbom,lcassembly,lcproductclass,lcproductmodel,lcbominfo,lcbominfo_test,modifiedby,modifieddate)values('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')", Constant.MainBom_sqlname, lcbom_meaid_value, Constant.Add_Bom, Addnode.Text, Addnode.Parent.Parent.Text, Addnode.Parent.Text, lcbominfo_str, lcbominfo_str, Constant.CurUserName(), DateTime.Now), null);
                    SQliteHelper.ExecuteDataTable(Constant.strConnectSQLite, CommandType.Text, string.Format("insert into {0} (tablename,oldvalue,newvalue,modifiedby,modifieddate,descrip)values('{1}','{2}','{3}','{4}','{5}','{6}')", Constant.RecordLog_sqlname, formname, "", Constant.Add_Bom, Constant.CurUserName(), DateTime.Now, change_str), null);
                }
                else
                {
                    string Add_str = AddBOM_Module(Addnode, change_str);
                    if (Add_str == "")
                    {
                        return;
                    }
                    if (change_str == "添加产品容量")
                    {
                        sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("insert into {0} (lcbom_meaid,lcbom,lcassembly,lcproductclass,lcproductmodel,lcbominfo,lcbominfo_test,modifiedby,modifieddate)values('{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')", Constant.MainBom_sqlname, Guid.NewGuid(), "0", Constant.Add_Bom, Addnode.Parent.Text, Addnode.Text, "", "", Constant.CurUserName(), DateTime.Now), null);
                        SQliteHelper.ExecuteDataTable(Constant.strConnectSQLite, CommandType.Text, string.Format("insert into {0} (tablename,oldvalue,newvalue,modifiedby,modifieddate,descrip)values('{1}','{2}','{3}','{4}','{5}','{6}')", Constant.RecordLog_sqlname, formname, "", Constant.Add_Bom, Constant.CurUserName(), DateTime.Now, change_str), null);
                    }
                    else if (change_str == "添加弹性体BOM")
                    {
                        StringBuilder Strconn = DgdDealHelper.GetCombineInfo(Constant.Elastic_dt);
                        sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("insert into {0}(generic_assembly,sgelasticbom,sgelasticinfo,sgelasticinfo_test)values('{1}','{2}','{3}','{4}')", Constant.Elastic_sqlname, Addnode.Parent.Text, Constant.Add_Bom, Strconn, Strconn), null);
                        SQliteHelper.ExecuteDataTable(Constant.strConnectSQLite, CommandType.Text, string.Format("insert into {0} (tablename,oldvalue,newvalue,modifiedby,modifieddate,descrip)values('{1}','{2}','{3}','{4}','{5}','{6}')", Constant.RecordLog_sqlname, formname, "", Constant.Add_Bom, Constant.CurUserName(), DateTime.Now, change_str), null);
                    }
                    else if (change_str == "添加应变片BOM")
                    {
                        StringBuilder Strconn = DgdDealHelper.GetCombineInfo(Constant.Sgseries_dt);
                        sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("insert into {0} (sgseriesbom,sgseriesinfo,sgseriesinfo_test) values ('{1}','{2}','{3}')", Constant.SGseries_sqlname, Constant.Add_Bom, Strconn, Strconn), null);
                        SQliteHelper.ExecuteDataTable(Constant.strConnectSQLite, CommandType.Text, string.Format("insert into {0} (tablename,oldvalue,newvalue,modifiedby,modifieddate,descrip)values('{1}','{2}','{3}','{4}','{5}','{6}')", Constant.RecordLog_sqlname, formname, "", Constant.Add_Bom, Constant.CurUserName(), DateTime.Now, change_str), null);
                    }
                    else if (change_str == "添加应变胶BOM")
                    {
                        StringBuilder Strconn = DgdDealHelper.GetCombineInfo(Constant.Sgglue_dt);
                        sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("insert into {0} (sggluebom,sgglueinfo,sgglueinfo_test) values ('{1}','{2}','{3}')", Constant.Sgglue_sqlname, Constant.Add_Bom, Strconn, Strconn), null);
                        SQliteHelper.ExecuteDataTable(Constant.strConnectSQLite, CommandType.Text, string.Format("insert into {0} (tablename,oldvalue,newvalue,modifiedby,modifieddate,descrip)values('{1}','{2}','{3}','{4}','{5}','{6}')", Constant.RecordLog_sqlname, formname, "", Constant.Add_Bom, Constant.CurUserName(), DateTime.Now, change_str), null);
                    }
                }
                Log4netHelper.Info(new TreeNodeHelper().GetType(), string.Format("{0}:{1}", change_str, Constant.Add_Bom));
                UIHelper.DesktopNotify(true, string.Format("{0}:{1}", change_str, Constant.Add_Bom));
            }
            catch (Exception ex)
            {
                MessageBox.Show("添加节点时发生异常:" + ex.Message);
            }
        }
Beispiel #7
0
        public List <StudentModel> GetList()
        {
            string sql = "select top 1 * from student order by NEWID()";

            Log4netHelper.Info("SQL:" + sql);
            List <StudentModel> smList = DapperHelper <StudentModel> .Query(sql);

            return(smList);
        }
Beispiel #8
0
        public bool WorkerOperation(UserSensitiveMailQueueInfo info)
        {
            ErrorCodeInfo error         = new ErrorCodeInfo();
            string        message       = string.Empty;
            string        resultmessage = string.Empty;
            Guid          transactionid = Guid.NewGuid();
            string        paramstr      = string.Empty;

            paramstr += $"SensitiveID:{info.ID}";
            paramstr += $"||Keywords:{info.Keywords}";
            paramstr += $"||StartTime:{info.StartTime}";
            paramstr += $"||EndTime:{info.EndTime}";
            paramstr += $"||UserID:{info.UserID}";
            bool bResult = true;

            try
            {
                do
                {
                    Log4netHelper.Info($"RemoveSensitiveMail Begin: {paramstr}");
                    CommonProvider          commonProvider = new CommonProvider();
                    DirectoryEntry          userEntry      = new DirectoryEntry();
                    SensitiveMailDBProvider provider       = new SensitiveMailDBProvider();
                    if (!commonProvider.GetADEntryByGuid(info.UserID, out userEntry, out message))
                    {
                        Log4netHelper.Error($"RemoveSensitiveMail GetADEntryByGuid ID:{info.UserID}, Error:{message}");
                        info.Status   = SensitiveMailStatus.Failed;
                        resultmessage = "用户不存在。";
                        provider.UpdateUserSensitiveMailQueue(transactionid, info, resultmessage, out error);
                        bResult = false;
                        break;
                    }
                    string userMail = userEntry.Properties["mail"].Value == null ? "" : Convert.ToString(userEntry.Properties["mail"].Value);
                    ADManagerWebService.ManagerWebService webService = new ADManagerWebService.ManagerWebService();
                    webService.Timeout = -1;
                    if (!webService.RemoveSensitiveMail(transactionid, userMail, info.Keywords, info.StartTime, info.EndTime, out resultmessage, out message))
                    {
                        info.Status = SensitiveMailStatus.Failed;
                        provider.UpdateUserSensitiveMailQueue(transactionid, info, resultmessage, out error);
                        Log4netHelper.Error($"RemoveSensitiveMail ID:{info.ID}, Error:{message}");
                        bResult = false;
                        break;
                    }
                    //记录执行日志
                    info.Status = SensitiveMailStatus.Success;
                    provider.UpdateUserSensitiveMailQueue(transactionid, info, resultmessage, out error);
                    Log4netHelper.Info($"RemoveSensitiveMail End: {paramstr}");
                } while (false);
            }
            catch (Exception ex)
            {
                Log4netHelper.Error("RemoveSensitiveMail异常", paramstr, ex.ToString(), transactionid);
                bResult = false;
            }
            return(bResult);
        }
Beispiel #9
0
        protected override void OnStart(string[] args)
        {
            // TODO: 在此处添加代码以启动服务。
            SensitiveMailManager serviceManager = new SensitiveMailManager(ip);

            //Thread.Sleep(12000);
            Log4netHelper.Info($"Thread Start: {DateTime.Now}");
            main_Thread = new Thread(new ThreadStart(serviceManager.RemoveSensitiveMailQueue));
            main_Thread.Start();
        }
Beispiel #10
0
        public void OnException(ExceptionContext filterContext)
        {
            //获取异常信息
            Exception Error   = filterContext.Exception;
            string    Message = Error.Message;                      //错误信息
            string    Url     = HttpContext.Current.Request.RawUrl; //错误发生地址

            filterContext.ExceptionHandled = true;                  //标记异常已处理
            //filterContext.Result = new RedirectResult("/Error/Show/");//跳转至错误提示页面
            Log4netHelper.Info(Url + "\n" + Message);
        }
Beispiel #11
0
        private void AsyncCallback(IAsyncResult ar)
        {
            IPEndPoint remoteIpEndPoint = null;

            byte[] buffer = _udpClient.EndReceive(ar, ref remoteIpEndPoint);
            if (buffer != null)
            {
                Log4netHelper.Info(_encoding.GetString(buffer));
            }
            _udpClient.BeginReceive(new AsyncCallback(AsyncCallback), null);
        }
Beispiel #12
0
            public override void OnException(HttpActionExecutedContext context)
            {
                var exception = context.Exception;

                while (exception.InnerException != null)
                {
                    exception = exception.InnerException;
                }

                // 异常过滤
                switch (exception)
                {
                default:
                    break;

                case AppException appException:
                case TaskCanceledException taskCanceledException:
                case OperationCanceledException operationCanceledException:
                    context.Response = context.Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest, exception.Message);

                    Log4netHelper.Info(exception.Message, exception);
                    return;
                }

                var parameters = new Dictionary <string, object>();

                // 添加路由参数
                if (context.ActionContext.RequestContext.RouteData.Values.ContainsKey("id"))
                {
                    parameters.Add("id", context.ActionContext.RequestContext.RouteData.Values["id"]);
                }

                var actionArguments = context.ActionContext.ActionArguments.Select(m => new KeyValuePair <string, string>(m.Key, JsonConvert.SerializeObject(m.Value)));

                // 添加请求参数
                var request = HttpContext.Current?.Request;

                var queryParams =
                    request?.QueryString.Count > 0 ? request?.QueryString : request?.Form;

                foreach (var key in queryParams?.AllKeys ?? new string[0])
                {
                    parameters.Add(key, queryParams[key]);
                }

                // 将参数加入到异常数据中
                foreach (var item in parameters)
                {
                    exception.Data.Add(item.Key, item.Value);
                }

                // 记录日志
                Log4netHelper.Error("Global", exception);
            }
Beispiel #13
0
 public void Save(object sender, EventArgs e)
 {
     try
     {
         SendKeys.SendWait("{ENTER}");
         for (int i = 0; i < dataGridViewX1.Rows.Count; i++)
         {
             if (!string.IsNullOrEmpty(dataGridViewX1.Rows[i].Cells[1].ErrorText))
             {
                 UIHelper.ToastNotify(false, "保存失败,正式生产表中存在不合理数据,请重新检查!", tabControl1);
                 Log4netHelper.Error(this.GetType(), string.Format("正式生产表中存在不合理数据,请重新检查!第{0}行,第{1}列,原因是:{2}", i, 1, dataGridViewX1.Rows[i].Cells[1].ErrorText));
                 return;
             }
         }
         //获取盒子名称;
         Boxtype_str = GetBoxtypeName();
         if (Boxtype_str == "NULL")
         {
             BoxType_TextBox.Focus();
             return;
         }
         //先判断是否已存在
         DataTable sql_dt = sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("select sgboxtype from {0} where sgboxtype='{1}'", Constant.Boxtype_sqlname, Boxtype_str), null);
         if (sql_dt.Rows.Count > 0 && !submit_flag)
         {
             UIHelper.ToastNotify(false, "该型号已存在,请不要重复创建!--" + Boxtype_str, tabControl1);
             return;
         }
         DataTable     formal_dt      = ((DataTable)dataGridViewX1.DataSource).Copy();
         StringBuilder Formal_strconn = DgdDealHelper.GetCombineInfo(formal_dt);
         if (submit_flag)
         {
             sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("update {0} set sgboxinfo='{1}',sgboxinfo_test='{2}' where sgboxtype='{3}'", Constant.Boxtype_sqlname, Formal_strconn, Formal_strconn, Boxtype_str), null);
             DgdDealHelper.Deal_DifDgdValue(this.Text, NotModify_dt1, dataGridViewX1, "正式表");
             UIHelper.ToastNotify(true, "表数据修改保存成功!", tabControl1);
         }
         else
         {
             sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("insert into {0} (sgboxtype,sgboxinfo,sgboxinfo_test)values('{1}','{2}','{3}')", Constant.Boxtype_sqlname, Boxtype_str, Formal_strconn, Formal_strconn), null);
             SQliteHelper.ExecuteDataTable(Constant.strConnectSQLite, CommandType.Text, string.Format("insert into {0} (tablename,modifiedby,modifieddate,descrip)values('{1}','{2}','{3}','{4}')", Constant.RecordLog_sqlname, Boxtype_str, Constant.CurUserName(), DateTime.Now, "创建Boxtype"), null);
             //创建节点
             CreateTypeNode(parent_str, Boxtype_str);
             UIHelper.ToastNotify(true, "表数据创建成功!", tabControl1);
             Log4netHelper.Info(this.GetType(), Boxtype_str + "表数据创建成功!");
         }
         NotModify_dt1 = formal_dt;
         submit_flag   = true;
         CloseCreatForm(this.Text);
     }
     catch (Exception ex)
     {
         MessageBox.Show("保存时发生异常:" + ex.Message);
     }
 }
Beispiel #14
0
        public async Task Invoke(HttpContext context)
        {
            var strAccept = context.Request.Headers["Accept"].ToString().ToLower();

            if (strAccept.Contains("image") || strAccept.Contains("html") || strAccept.Contains("css"))
            {
                await _next(context);

                return;
            }
            var strRequestUrl = $"{context.Request.Scheme}://{context.Request.Host}{context.Request.Path}{context.Request.QueryString}";

            if (strRequestUrl.Contains(".js") || strRequestUrl.Contains(".html") || strRequestUrl.Contains(".css"))
            {
                await _next(context);

                return;
            }
            context.Request.EnableBuffering();
            _stopwatch.Restart();
            _data = new SortedDictionary <string, object>();
            var requestReader  = new StreamReader(context.Request.Body);
            var requestContent = requestReader.ReadToEnd();

            //记录请求信息
            _data.Add("request.url", strRequestUrl);
            _data.Add("request.headers", context.Request.Headers.ToDictionary(x => x.Key, v => string.Join(";", v.Value.ToList())));
            _data.Add("request.method", context.Request.Method);
            _data.Add("request.executeStartTime", DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
            _data.Add("request.body", requestContent);
            context.Request.Body.Position = 0;
            var originalBodyStream = context.Response.Body;

            using (var responseBody = new MemoryStream())
            {
                context.Response.Body = responseBody;
                await _next(context);

                var response = context.Response;
                response.Body.Seek(0, SeekOrigin.Begin);
                //转化为字符串
                string text = await new StreamReader(response.Body).ReadToEndAsync();
                //从新设置偏移量0
                response.Body.Seek(0, SeekOrigin.Begin);
                await responseBody.CopyToAsync(originalBodyStream);

                //记录返回值
                _stopwatch.Stop();
                _data.Add("elaspedTime", _stopwatch.ElapsedMilliseconds + "ms");
                _data.Add("response.body", text);
                _data.Add("response.executeEndTime", DateTimeOffset.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                Log4netHelper.Info(typeof(LogReqResponseMiddleware), JsonConvert.SerializeObject(_data));
            }
        }
Beispiel #15
0
        // GET: YourDiary
        public ActionResult Index()
        {
            Log4netHelper.Info("ip:" + Request.UserHostAddress + ";时间:" + DateTime.Now);
            List <string> dateLs   = new List <string>();
            List <string> dateIDLs = new List <string>();


            ViewBag.dateLs   = dateLs;
            ViewBag.dateIDLs = dateIDLs;

            return(View());
        }
Beispiel #16
0
        protected override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);

            //获取异常信息
            Exception Error   = filterContext.Exception;
            string    Message = Error.Message;                            //错误信息
            string    Url     = filterContext.HttpContext.Request.RawUrl; //错误发生地址

            filterContext.ExceptionHandled = true;
            //filterContext.Result = new RedirectResult("/Error");//跳转至错误提示页面
            Log4netHelper.Info(DateTime.Now + ":" + Url + "\n" + Message);
        }
Beispiel #17
0
 public static void ModifyNode_Func(TreeNode Modifynode, string change_str, TabControl tabcontrol)
 {
     try
     {
         string formname = Modifynode.Parent.Text + "-" + Modifynode.Text;
         string Old_BOM  = Modifynode.Text;
         if (change_str == "修改传感器BOM")
         {
             string ModifyBOM_str = ModityBOM_Module(tabcontrol, Modifynode, change_str);
             if (ModifyBOM_str == "")
             {
                 return;
             }
             //从数据库中更新;
             sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("update {0} set lcbom='{1}'  where lcbom_meaid='{2}'", Constant.MainBom_sqlname, ModifyBOM_str, Modifynode.Tag), null);
             SQliteHelper.ExecuteDataTable(Constant.strConnectSQLite, CommandType.Text, string.Format("insert into {0} (tablename,oldvalue,newvalue,modifiedby,modifieddate,descrip)values('{1}','{2}','{3}','{4}','{5}','{6}')", Constant.RecordLog_sqlname, formname, Old_BOM, Constant.Add_Bom, Constant.CurUserName(), DateTime.Now, change_str), null);
         }
         else
         {
             if (ChangeConflict_Check(Modifynode, change_str))
             {
                 string New_BOM = ModityBOM_Module(tabcontrol, Modifynode, change_str);
                 if (New_BOM == "")
                 {
                     return;
                 }
                 if (change_str == "修改弹性体BOM")
                 {
                     sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("update {0} set sgelasticbom='{1}'  where sgelasticbom='{2}' and generic_assembly='{3}'", Constant.Elastic_sqlname, New_BOM, Old_BOM, Modifynode.Parent.Parent.Text), null);
                     SQliteHelper.ExecuteDataTable(Constant.strConnectSQLite, CommandType.Text, string.Format("insert into {0} (tablename,oldvalue,newvalue,modifiedby,modifieddate,descrip)values('{1}','{2}','{3}','{4}','{5}','{6}')", Constant.RecordLog_sqlname, formname, Old_BOM, Constant.Add_Bom, Constant.CurUserName(), DateTime.Now, change_str), null);
                 }
                 else if (change_str == "修改应变片BOM")
                 {
                     sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("update  {0} set sgseriesbom='{1}' where sgseriesbom='{2}'", Constant.SGseries_sqlname, New_BOM, Old_BOM), null);
                     SQliteHelper.ExecuteDataTable(Constant.strConnectSQLite, CommandType.Text, string.Format("insert into {0} (tablename,oldvalue,newvalue,modifiedby,modifieddate,descrip)values('{1}','{2}','{3}','{4}','{5}','{6}')", Constant.RecordLog_sqlname, formname, Old_BOM, Constant.Add_Bom, Constant.CurUserName(), DateTime.Now, change_str), null);
                 }
                 else if (change_str == "修改应变胶BOM")
                 {
                     sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("update {0} set sggluebom='{1}' where sggluebom='{2}'", Constant.Sgglue_sqlname, New_BOM, Old_BOM), null);
                     SQliteHelper.ExecuteDataTable(Constant.strConnectSQLite, CommandType.Text, string.Format("insert into {0} (tablename,oldvalue,newvalue,modifiedby,modifieddate,descrip)values('{1}','{2}','{3}','{4}','{5}','{6}')", Constant.RecordLog_sqlname, formname, Old_BOM, Constant.Add_Bom, Constant.CurUserName(), DateTime.Now, change_str), null);
                 }
             }
         }
         Log4netHelper.Info(new TreeNodeHelper().GetType(), string.Format("{0}:{1}", change_str, Constant.Add_Bom));
         UIHelper.DesktopNotify(true, string.Format("{0}:{1}", change_str, Constant.Add_Bom));
     }
     catch (Exception ex)
     {
         MessageBox.Show("修改节点时发生异常:" + ex.Message);
     }
 }
Beispiel #18
0
        public override void OnActionExecuted(ActionExecutedContext context)
        {
            base.OnActionExecuted(context);
            if (!customConfiguration.IsLog)
            {
                return;
            }
            try
            {
                Stopwatch.Stop();
                StringBuilder builder = new StringBuilder();
                string        url     = context.HttpContext.Request.Host + context.HttpContext.Request.Path + context.HttpContext.Request.QueryString;
                string        method  = context.HttpContext.Request.Method;

                string qs = ActionArguments;

                string controllerName = context.RouteData.Values["Controller"].ToString();//通过ActionContext类的RouteData属性获取Controller的名称:Home
                string actionName     = context.RouteData.Values["Action"].ToString();

                dynamic result = context.Result.GetType().Name == "EmptyResult" ? new { Value = "无返回结果" } : context.Result as dynamic;

                var clientIP = context.HttpContext.GetClientUserIp();

                string res = "在返回结果前发生了异常";
                try
                {
                    if (result != null)
                    {
                        res = Newtonsoft.Json.JsonConvert.SerializeObject(result.Value);
                    }
                }
                catch (System.Exception)
                {
                    res = "日志未获取到结果,返回的数据无法序列化";
                }
                builder.AppendLine($"");
                builder.AppendLine($"Controller:{controllerName},Action:{actionName}");
                builder.AppendLine($"客户端IP:{clientIP}");
                builder.AppendLine($"地址:{url}");
                builder.AppendLine($"方式:{method}");
                builder.AppendLine($"请求体:{RequestBody}");
                builder.AppendLine($"参数:{qs}");
                builder.AppendLine($"结果:{res}");
                builder.AppendLine($"耗时:{Stopwatch.Elapsed.TotalMilliseconds} 毫秒(指控制器内对应方法执行完毕的时间)");
                Log4netHelper.Info(this, builder.ToString());
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// 广播消息给所有的客户端
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="userWebSocket"></param>
        /// <param name="wsFactory"></param>
        /// <returns></returns>
        public async Task BroadcastAll(byte[] buffer, CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory)
        {
            var all = wsFactory.All();

            foreach (var uws in all)
            {
                if (uws.WebSocket.State != WebSocketState.Open)
                {
                    Log4netHelper.Info(this, "此websocket的状态为:" + uws.Username + "<>" + uws.WebSocket.State.ToString());
                    continue;
                }
                await uws.WebSocket.SendAsync(new ArraySegment <byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }
        /// <summary>
        /// 发送消息给指定的客户端
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="userWebSocket"></param>
        /// <param name="wsFactory"></param>
        /// <returns></returns>
        public async Task SendMessageToSingle(string msg, CustomWebSocket userWebSocket, ICustomWebSocketFactory wsFactory)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(msg);
            var    client = wsFactory.Client(userWebSocket);

            if (client != null)
            {
                if (client.WebSocket.State != WebSocketState.Open)
                {
                    Log4netHelper.Info(this, "此websocket的状态为:" + client.Username + "<>" + client.WebSocket.State.ToString());
                    return;
                }
                await client.WebSocket.SendAsync(new ArraySegment <byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);
            }
        }
Beispiel #21
0
        /// <summary>
        /// 异步调用会掉
        /// </summary>
        /// <param name="ar"></param>
        private void AsyncCallback(IAsyncResult ar)
        {
            //Object obj = ar.AsyncState;//获取传递的数据,本例中为UdpClient
            IPEndPoint remoteIpEp = new IPEndPoint(IPAddress.Any, 0);

            //虽然端口指定了0,表示任意端口,但该server只能接收构造函数中绑定的端口中的数据
            //构造函数中指定的端口是唯一的端口用来发送和接收数据的
            byte[] buffer = _udpClient.EndReceive(ar, ref remoteIpEp);
            if (remoteIpEp != null)
            {
                Log4netHelper.Info(_encoding.GetString(buffer));
                _udpClient.Send(buffer, buffer.Length, remoteIpEp);
            }

            //重新开始异步调用
            _udpClient.BeginReceive(new AsyncCallback(AsyncCallback), _udpClient);
        }
Beispiel #22
0
            public static ICollection <PSObject> ExecuteCmdlet(string strscope, string strSearchQuery, DateTime startTime, DateTime endTime)
            {
                string cmd  = string.Empty;
                int    type = 2;

                //string a = string.Format("Get-Mailbox  -OrganizationalUnit \"{0}\" -ResultSize Unlimited | Search-Mailbox -SearchQuery '{1}  AND Sent:>{2} AND Sent:<{3}'  -DeleteContent -Force", strOUscope, strSearchQuery, startTime, endTime);
                if (type == 1)
                {
                    cmd = string.Format("Get-Mailbox  -OrganizationalUnit \"{0}\" -ResultSize Unlimited | Search-Mailbox -SearchQuery '{1}  AND sent>=\"{2}\" AND sent<=\"{3}\"'  -DeleteContent -Force", strscope, strSearchQuery, startTime, endTime);
                    Log4netHelper.Info("RemoveSensitiveMail : " + cmd);
                }
                else
                {
                    cmd = string.Format("Search-Mailbox -Identity \"{0}\" -SearchQuery '{1}  AND sent>=\"{2}\" AND sent<=\"{3}\"'  -DeleteContent -Force", strscope, strSearchQuery, startTime, endTime);
                    Log4netHelper.Info("RemoveSensitiveMail : " + cmd);
                }
                return(PSCommandBase.ExecuteCmdlet(cmd));
            }
Beispiel #23
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            string actionArguments = Newtonsoft.Json.JsonConvert.SerializeObject(context.ActionArguments);

            var resultContext = await next();

            string url = resultContext.HttpContext.Request.Host + resultContext.HttpContext.Request.Path + resultContext.HttpContext.Request.QueryString;

            string method = resultContext.HttpContext.Request.Method;

            //dynamic result = resultContext.Result.GetType().Name == "EmptyResult" ? new { Value = "EmptyResult" } : resultContext.Result as dynamic;

            string response = JsonConvert.SerializeObject(resultContext.Result);

            Log4netHelper.Info($"URL:{url} \n " +
                               $"Method:{method} \n " +
                               $"ActionArguments:{actionArguments}\n " +
                               $"Response:{response}\n ");
        }
Beispiel #24
0
        private bool ADSynchronization(string dcName, string ldap, out List <CBOU> ouList, out List <CBUserEntity> userList, out string strError)
        {
            bool bResult = true;

            strError = string.Empty;
            ouList   = new List <CBOU>();
            userList = new List <CBUserEntity>();
            DirectoryEntry Ad_DC = null;

            try
            {
                Ad_DC = new DirectoryEntry(string.Format("LDAP://{0}/{1}", dcName, ldap));
                Log4netHelper.Info(string.Format("dc name:{0}, dc ldap:{1}, dc guid:{2} ", dcName, string.Format("LDAP://{0}/{1}", dcName, ldap), Ad_DC.Guid));

                if (SearchProfessionalGroupOus(Ad_DC, out strNamedOUArray, out strError))
                {
                    bResult = SearchOUByldap(Ad_DC, dcName, SearchScope.OneLevel, ref ouList, ref userList);
                }
            }
            catch (Exception error)
            {
                strError = error.ToString();
                Log4netHelper.Error(string.Format("ADSynchronization Exception:{0} ", error.ToString()));
                bResult = false;
            }
            finally
            {
                if (Ad_DC != null)

                {
                    Ad_DC.Close();
                    Ad_DC.Dispose();
                    Ad_DC = null;
                }
            }

            return(bResult);
        }
Beispiel #25
0
 /// <summary>
 /// 发送消息
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="content"></param>
 public void Send <T>(T obj)
 {
     try
     {
         var    msg       = JsonHelper.SerializeObject(obj);
         byte[] buffer    = Encoding.UTF8.GetBytes($"{msg.EncryptBase64(encode: Encoding.UTF8)}{SocketCommand.MessageSeparator}");
         var    send_byte = Socket.Send(buffer, buffer.Length, SocketFlags.None);
         if (send_byte < buffer.Length)
         {
             throw new Exception($"send_byte={send_byte}<buffer.length={buffer.Length}");
         }
         Log4netHelper.Info($"发送{buffer.Length}字节,实际发送{send_byte}字节{Environment.NewLine}{msg}");
     }
     catch (Exception ex)
     {
         if (this.SendExceptionCallback != null)
         {
             this.SendExceptionCallback(ex, obj);
         }
         Log4netHelper.Debug($"发送消息异常:{obj.ToJson()}", ex);
         throw ex;
     }
 }
Beispiel #26
0
        // GET: Dapper
        public ActionResult Index()
        {
            Stopwatch timer = new Stopwatch();

            timer.Start();

            StudentBLL          sBLL   = new StudentBLL();
            List <StudentModel> smList = sBLL.GetList();

            timer.Stop();
            TimeSpan ts = timer.Elapsed;

            Log4netHelper.Info("sql读取学生数据耗时:" + ts.TotalMilliseconds);

            //将数据写入redis
            for (int i = 0; i < smList.Count; i++)
            {
                RedisHelper.HashSet <StudentModel>("Students", i.ToString(), smList[i]);
            }



            Stopwatch timer2 = new Stopwatch();

            timer2.Start();

            List <StudentModel> smList2 = RedisHelper.HashGetAll <StudentModel>("Students");

            timer2.Stop();
            TimeSpan ts2 = timer2.Elapsed;

            Log4netHelper.Info("redis读取学生数据耗时:" + ts2.TotalMilliseconds);



            return(View());
        }
Beispiel #27
0
 //模糊搜索 需在末尾添加“&”标志位匹配正确搜索--Undoe
 private static bool ChangeConflict_Check(TreeNode changenode, string change_str)
 {
     try
     {
         DataTable ExistFormal_dt   = sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("select lcbom from {0} where lcbominfo like '%{1}%'", Constant.MainBom_sqlname, changenode.Text), null);
         DataTable ExistTest_dt     = sqlconnection.ExecuteDataTable(Constant.strConnectSQL_T, CommandType.Text, string.Format("select lcbom from {0} where lcbominfo_test like '%{1}%'", Constant.MainBom_sqlname, changenode.Text), null);
         string    Used_Mainbom_str = "";
         if (ExistFormal_dt.Rows.Count > 0)
         {
             for (int i = 0; i < ExistFormal_dt.Rows.Count; i++)
             {
                 Used_Mainbom_str += string.Format("({0})", ExistFormal_dt.Rows[i][0]);
             }
             Log4netHelper.Info(new TreeNodeHelper().GetType(), string.Format("冲突,{0}:{1},主表正式表BOM:{2}", change_str, changenode.Text, Used_Mainbom_str));
             UIHelper.DesktopNotify(false, "主表正式表BOM冲突,请检查日志信息!");
             return(false);
         }
         if (ExistTest_dt.Rows.Count > 0)
         {
             Used_Mainbom_str = "";
             for (int i = 0; i < ExistTest_dt.Rows.Count; i++)
             {
                 Used_Mainbom_str += string.Format("({0})", ExistTest_dt.Rows[i][0]);
             }
             Log4netHelper.Info(new TreeNodeHelper().GetType(), string.Format("删除冲突,{0}:{1},主表样机表BOM:{2}", change_str, changenode.Text, Used_Mainbom_str));
             UIHelper.DesktopNotify(false, "主表样机表BOM冲突,请检查日志信息!");
             return(false);
         }
         return(true);
     }
     catch (Exception ex)
     {
         UIHelper.DesktopNotify(false, "检查主表改变是否冲突时发生异常:" + ex.Message);
         return(false);
     }
 }
        /// <summary>
        /// 发送消息给指定的客户端(用户名相同的所有客户端)
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="username"></param>
        /// <param name="wsFactory"></param>
        /// <returns></returns>
        public async Task SendMessage(string msg, string username, ICustomWebSocketFactory wsFactory)
        {
            var clients = wsFactory.Clients(username);

            if (clients != null)
            {
                foreach (var client in clients)
                {
                    if (client.WebSocket.State != WebSocketState.Open)
                    {
                        Log4netHelper.Info(this, "此websocket的状态为:" + client.Username + "<>" + client.WebSocket.State.ToString());
                        continue;
                    }
                    byte[] buffer = Encoding.UTF8.GetBytes(msg);
                    await client.WebSocket.SendAsync(new ArraySegment <byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text, true, CancellationToken.None);

                    //Log4netHelper.Info(this, client.Username + "-->推送消息成功:" + msg);
                }
            }
            else
            {
                Log4netHelper.Info(this, username + "-->客户端不存在!");
            }
        }
Beispiel #29
0
        static void Main(string[] args)
        {
            string error = string.Empty;

            try
            {
                SyncADManager sync = new SyncADManager();
                sync.Load(out error);
                //test0228
                if (string.IsNullOrEmpty(error))
                {
                    Log4netHelper.Info("Sync AD Control Result Succeeded");
                }
                else
                {
                    Log4netHelper.Error("Sync AD Control Result:" + error);
                }
            }
            catch (Exception ex)
            {
                Log4netHelper.Error("Sync AD Control Exception:" + ex.ToString());
                Console.WriteLine(error);
            }
        }
        /// <summary>
        /// 创建连接
        /// </summary>
        /// <returns></returns>
        public bool Start()
        {
            if (socket != null)
            {
                //开始前如果已经存在连接,先释放以前的连接,然后重新建立新连接
                Stop();
            }
            try
            {
                IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse(ip), port);
                socket             = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                socket.SendTimeout = socket.ReceiveTimeout = timeout;
                socket.Connect(ipEndPoint);
                isRunning = true;
                Log4netHelper.Info(string.Format("建立到{0}:{1}连接成功", ip, port));
            }
            catch (Exception ex)
            {
                isRunning = false;
                Log4netHelper.Error(string.Format("建立到{0}:{1}连接失败,exception={2}", ip, port, ex));
            }

            return(isRunning);
        }