Пример #1
0
        public AlipayTradePrecreateResponse BuildNew(EAliPayApplication app, EStoreInfo store, EUserInfo AgentUI, string TotalAmt, bool needNotifyUrl = true, bool needControl = true)
        {
            string NotifyUrl = ConfigurationManager.AppSettings["Main_SiteUrl"] + "AliPay/PayNotify";

            _OrderNo = StringHelper.GenerateOrderNo();

            IAopClient aliyapClient = new DefaultAopClient("https://openapi.alipay.com/gateway.do", app.AppId,
                                                           app.Merchant_Private_Key, "json", "1.0", "RSA2", app.Merchant_Public_key, "GBK", false);

            AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
            AlipayTradePrecreateModel   model   = new AlipayTradePrecreateModel();

            model.SellerId = store.AliPayAccount;
            NLogHelper.InfoTxt("当面付OrderNo:" + _OrderNo);
            model.OutTradeNo   = _OrderNo;
            model.TotalAmount  = TotalAmt;
            model.Subject      = "#" + AgentUI.Name + " 收银台";
            model.Body         = app.AppName + "-商品";
            model.ExtendParams = new Aop.Api.Domain.ExtendParams();
            model.ExtendParams.SysServiceProviderId = app.AppId;
            if (needControl)
            {
                model.DisablePayChannels = "balance,moneyFund,creditCard,creditCardExpress,creditCardCartoon,debitCardExpress,point,bankPay";
            }

            request.SetBizModel(model);
            if (needNotifyUrl)
            {
                request.SetNotifyUrl(NotifyUrl);
            }

            AlipayTradePrecreateResponse response = aliyapClient.Execute(request, null, store.AliPayAuthToke);

            return(response);
        }
        public IActionResult OnPostCheckUserAccount()
        {
            ResultObject <EUserAccount> result = new ResultObject <EUserAccount>();

            try
            {
                var us = base.GetUserSession(false);
                if (us != null)
                {
                    var userAccount = _UserSrv.GetUserAccount(us.OpenId);
                    if (string.IsNullOrEmpty(userAccount.AliPayAccount))
                    {
                        result.IntMsg   = -2;
                        result.ErrorMsg = "请设置转账支付宝账户";
                    }
                    else
                    {
                        result.Entity = userAccount;
                    }
                }
                else
                {
                    result.IntMsg   = -1;
                    result.ErrorMsg = "需要您重新登录!";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMsg = "没有获取数据";
                NLogHelper.ErrorTxt(ex.Message);
            }
            return(new JsonResult(result));
        }
Пример #3
0
        public IActionResult OnPostQueryTecDayCourse(string date)
        {
            ResultList <RTecCourse> result = new ResultList <RTecCourse>();

            try
            {
                var us = GetUserSession(false);
                if (us != null)
                {
                    NLogHelper.InfoTxt($"QueryTecDayCourse TecCode:{us.TecCode}");
                    result.List = _TecSrv.GetOneDayCourse(us.TecCode, date);
                }
                else
                {
                    result.IntMsg   = -1;
                    result.ErrorMsg = "请重新登陆";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMsg = "未能获取数据!请联系管理员或稍后再试";
                NLogHelper.ErrorTxt(ex.Message);
            }
            return(new JsonResult(result));
        }
Пример #4
0
        /// <summary>
        /// 定时器回调
        /// </summary>
        private void OneRunTimerCallBack()
        {
            if (!IsMqAlive())
            {
                if (_isFirstTimeToStart)
                {
                    _isFirstTimeToStart = false;

                    NLogHelper.Debug($"首次尝试启动mq");
                    StartMq(ex =>
                    {
                        NLogHelper.Error($"首次尝试启动mq失败:{ex}");
                    });
                }
                else
                {
                    bool needToStartMq = false;
                    _timerNonAliveCount++;
                    if (_timerNonAliveCount > 1 || _rmqConfigList.Count == 1)
                    {
                        //count == 1表示单机版
                        if (_timerNonAliveCount > 1000000)
                        {
                            //避免溢出
                            _timerNonAliveCount = 100;
                        }

                        needToStartMq = true;
                    }

                    if (needToStartMq)
                    {
                        RabbitMqConfig oldConfig = GetCurrentUsedRmq();

                        //取下一个机器
                        lock (_locker)
                        {
                            _currentUsedRmqIndex++;
                        }

                        RabbitMqConfig newConfig = GetCurrentUsedRmq();



                        //第二次才尝试启动
                        StartMq(ex =>
                        {
                            NLogHelper.Error($"尝试启动mq失败:{ex}");
                        });

                        //mq切机
                        _mqChangeCallback?.Invoke(oldConfig, newConfig);
                    }
                }
            }
            else
            {
                _timerNonAliveCount = 0;
            }
        }
Пример #5
0
        /// <summary>
        /// 定时器回调
        /// </summary>
        /// <param name="state"></param>
        private static void SerialPortCallBack(object state)
        {
            lock (locker)
            {
                if (isRunning)
                {
                    return;
                }
                isRunning = true;
            }

            try
            {
                if (!portUtils.IsAlive())
                {
                    portUtils.Start();
                }
            }
            catch (Exception ex)
            {
                NLogHelper.Error("串口定时器异常:" + ex);
            }
            finally
            {
                lock (locker)
                {
                    isRunning = false;
                }
            }
        }
Пример #6
0
        /// <summary>
        /// 关闭连接
        /// </summary>
        public static void Stop()
        {
            if (socket != null)
            {
                try
                {
                    socket.Shutdown(SocketShutdown.Both);
                }
                catch (Exception ex)
                {
                    NLogHelper.Error("Socket的ShutDown失败:" + ex);
                }

                try
                {
                    socket.Close();
                }
                catch (Exception ex)
                {
                    NLogHelper.Error("Socket的Close失败:" + ex);
                }
                //连接断开
                _isDisconnect = true;
                socket        = null;
            }
        }
        /// <summary>
        /// 停止消费者
        /// </summary>
        public static void StopConsumer()
        {
            //Disposing channel and connection objects is not enough, they must be explicitly closed
            if (_channel != null)
            {
                SafeInvokeUtils.Safe(() =>
                {
                    _channel.Close();
                }, ex =>
                {
                    NLogHelper.Error($"关闭RabbitMQ的channel失败:{ex}");
                });

                _channel = null;
            }

            if (_connection != null)
            {
                SafeInvokeUtils.Safe(() =>
                {
                    _connection.Close();
                }, ex =>
                {
                    NLogHelper.Error($"关闭RabbitMQ的connection失败:{ex}");
                });
                _connection = null;
            }

            lock (SLocker)
            {
                _isAlive = false;
            }
        }
Пример #8
0
        public void SetUserDeviceToken(string DeviceToken, string IDFV, DeviceChannel DeviceChannel, string appName = "YJOO")
        {
            try
            {
                if (!string.IsNullOrEmpty(DeviceToken) && !string.IsNullOrEmpty(IDFV))
                {
                    using (OOContent db = new OOContent())
                    {
                        EUserDevice userDevice = db.DBUserDevice.Where(a => a.IDFV == IDFV).FirstOrDefault();
                        if (userDevice == null)
                        {
                            userDevice = new EUserDevice();
                            userDevice.CreateDateTime = DateTime.Now;
                            db.DBUserDevice.Add(userDevice);
                        }


                        userDevice.DeviceToken = DeviceToken;
                        userDevice.IDFV        = IDFV;

                        userDevice.DeviceChannel     = DeviceChannel;
                        userDevice.AppName           = appName;
                        userDevice.LastLoginDateTime = DateTime.Now;
                        userDevice.LoginCount++;

                        db.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                NLogHelper.ErrorTxt("GetUserDeviceToken Error:" + ex.Message);
            }
        }
Пример #9
0
        public OutAPIResult GameUserLogin_WX(GameModel.EUserInfo wxUser)
        {
            NLogHelper.GameInfo("Login_WX In");
            if (Request.Method.Method.ToLower() == "options")
            {
                return(null);
            }

            OutAPIResult result = new OutAPIResult();

            try
            {
                using (GameContent db = new GameContent())
                {
                    var user = db.DBUserInfo.Where(a => a.openId == wxUser.openId).FirstOrDefault();
                    if (user == null)
                    {
                        result = GameUserRegister_WX(wxUser);
                    }
                    else
                    {
                        user.LastLogin = DateTime.Now;
                        user.LoginCount++;
                        db.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                result.ErrorMsg = ex.Message;
            }
            return(result);
        }
Пример #10
0
        public int GetNodeValue(string nodeStrGuid, out object nodeValue)
        {
            int rtc = -1;

            nodeValue = null;
            try
            {
                OPCDATASOURCE opcDataSource = OPCDATASOURCE.OPC_DS_DEVICE;

                OPCItemState opcItemState = new OPCItemState();

                DriveNodeEntity driveNode = allOPCItemNodes.Find(p => nodeStrGuid.Equals(p.nodeId));

                ItemDef itemdef = syncIOGroup.Item(driveNode.nodeName);

                rtc = syncIOGroup.Read(opcDataSource, itemdef, out opcItemState);

                if (HRESULTS.Succeeded(rtc))
                {
                    nodeValue = opcItemState.DataValue;
                    //txtItemQuality.Text = syncIOGroup.GetQualityString(opcItemState.Quality);
                    //txtTimeStamp.Text = DateTime.FromFileTime(opcItemState.TimeStamp).ToString();
                }
            }
            catch (Exception ex)
            {
                NLogHelper.ExceptionInfo(ex, "GetNodeValue param:'{1}' ,exception:{0}", ex.Message, nodeStrGuid);
            }

            return(rtc);
        }
Пример #11
0
 public bool Start()
 {
     try
     {
         bool bRet = InitOPCService();
         if (!bRet)
         {
             return(false);
         }
         if (null == opcSerNodes || null == allOPCItemNodes)
         {
             NLogHelper.DefalutError("OPCBUSService.Start error,未配置opc服务");
             return(false);
         }
         opcSer.Connect(host, guid);
         syncIOGroup         = new SyncIOGroup(opcSer);
         refreshEventHandler = new RefreshEventHandler(RefreshEvent);
         refreshGroup        = new RefreshGroup(opcSer, 10, refreshEventHandler);
         foreach (DriveNodeEntity item in allOPCItemNodes)
         {
             int iRet = refreshGroup.Add(item.nodeName);
             if (HRESULTS.Succeeded(iRet))
             {
                 Console.WriteLine(" true " + iRet);
             }
         }
         return(true);
     }
     catch (Exception ex)
     {
         NLogHelper.ExceptionInfo(ex, "Start StartOPCService exception: {0}", ex.Message);
         return(false);
     }
 }
Пример #12
0
        public IActionResult OnPostGetCourseByDate(string date)
        {
            ResultList <RUserCourseLog> result = new ResultList <RUserCourseLog>();
            var us = base.GetUserSession(false);

            try
            {
                date = DateTime.Parse(date).ToString("yyyy-MM-dd");

                if (us != null)
                {
                    result.List = _UserSrv.GetUserCourseByDate(us.OpenId, date, us.CurrentScheduleType);
                }
                else
                {
                    result.IntMsg   = -1;
                    result.ErrorMsg = "请重新登陆!";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMsg = "数据获取失败,请联系工作人员";
                if (us != null)
                {
                    NLogHelper.ErrorTxt($"用户请假OpenId:{us.OpenId}");
                }
                NLogHelper.ErrorTxt($"MyLeaveModel[OnPostGetCourseByDate]:{ex.Message}");
            }
            return(new JsonResult(result));
        }
Пример #13
0
        public static AccessToken GetOAuth2AccessTokenFromCode(string code)
        {
            try
            {
                //构造获取openid及access_token的url
                WxPayData data = new WxPayData();
                data.SetValue("appid", WxConfig.APPID);
                data.SetValue("secret", WxConfig.APPSECRET);

                //data.SetValue("appid", EduConfig.WXAppId);
                //data.SetValue("secret", EduConfig.WXSecret);

                data.SetValue("code", code);
                data.SetValue("grant_type", "authorization_code");
                string url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + data.ToUrl();

                AccessToken token = HttpHelper.Get <AccessToken>(url);

                return(token);
            }
            catch (Exception ex)
            {
                NLogHelper.ErrorTxt("GetOAuth2AccessTokenFromCode:" + ex.Message);
                throw new WxPayException(ex.ToString());
            }
        }
        private async Task HandleException(HttpContext httpContext, Exception ex)
        {
            httpContext.Response.StatusCode  = 500;
            httpContext.Response.ContentType = "text/json;charset=utf-8";
            string error = string.Empty;

#if DEBUG
            var json = new { message = ex.Message, trace = ex.StackTrace };
            error = JsonConvert.SerializeObject(json);
#elif RELEASE
            error = "出错了";
            var json = new { message = ex.Message, trace = ex.StackTrace };
#endif

            NLogHelper.GetLogger().Info(error);
            //rabbitmq就绪 json
            var post = new SendEmailOptions
            {
                title   = "位置异常",
                content = JsonConvert.SerializeObject(json)
            };
            if (ex.Message == "NotAllowed")
            {
                await httpContext.Response.WriteAsync(ex.Message);
            }
            else
            {
                this.SendErrorEmail(post);
                await httpContext.Response.WriteAsync(error);
            }
        }
Пример #15
0
        /// <summary>
        /// 消息处理的线程
        /// </summary>
        /// <param name="obj"></param>
        private static void MsgHandleCallback(object obj)
        {
            MessageItem item = null;

            while (isRunning)
            {
                if (RecvBlockingQueue.TryTake(out item, 1000))
                {
                    if (item == null || string.IsNullOrWhiteSpace(item.Message))
                    {
                        continue;
                    }

                    try
                    {
                        string message = item.Message.Trim();
                        NLogHelper.Info("开始处理消息:" + message);
                        //TODO: 处理消息

                        #region 处理消息


                        #endregion
                    }
                    catch (Exception ex)
                    {
                        NLogHelper.Info("处理消息失败:" + ex);
                    }
                }
            }
        }
Пример #16
0
        /// <summary>
        /// 邀请码进入
        /// </summary>
        private void InviteQRHandler()
        {
            try
            {
                //教师邀请
                if (_EventKey.StartsWith(WxConfig.QR_Invite_TecPre))
                {
                    var wxUser = WXApi.GetWXUserInfo(_wxMessage.FromUserName);
                    var user   = _UserSrv.AddOrUpdateFromWXUser(wxUser);
                    _TecSrv.NewTecFromUser(user);
                    _ResultMsg = _wxMessage.toText(WXReplyContent.NewTec(user.Name));
                }
                else if (_EventKey.StartsWith(WxConfig.QR_Invite_User))
                {
                    var ownOpenId = _EventKey.Split("_")[2];

                    var user = _BusinessSrv.InvitedUserComing(_wxMessage.FromUserName, ownOpenId);

                    _ResultMsg = _wxMessage.toText(WXReplyContent.NewUserAdd(user.Name));
                }
            }
            catch (Exception ex)
            {
                NLogHelper.ErrorTxt($"[InviteQRHandler]-FromUserName:{_wxMessage.FromUserName}| 信息:{ex.Message}");
            }
        }
Пример #17
0
        /// <summary>
        /// 发送消息的线程
        /// </summary>
        /// <param name="obj"></param>
        private static void SendCallBack(object obj)
        {
            MessageItem item = null;

            while (IsRunning)
            {
                //阻塞1s
                if (SendBlockingQueue.TryTake(out item, 1000))
                {
                    if (item == null || string.IsNullOrWhiteSpace(item.Message))
                    {
                        //空消息
                        continue;
                    }

                    try
                    {
                        NLogHelper.Info("开始发送消息" + item.Message);
                        byte[] buffer = Encoding.GetEncoding(EncodingStr).GetBytes(item.Message);

                        int sendCount = socket.Send(buffer, 0, buffer.Length, SocketFlags.None);
                        lastSendRecvTime = DateTime.Now;
                        _isDisconnect    = false;
                    }
                    catch (Exception ex)
                    {
                        NLogHelper.Error("发送消息失败:" + ex);
                    }
                }
            }
        }
Пример #18
0
        public bool Run(GameServer GameServer)
        {
            _GameServer = GameServer;
            if (_GameServer != null)
            {
                try
                {
                    if (_ErrorQueue != null && _ErrorQueue.Count > 0)
                    {
                        RunQueue(_ErrorQueue, true);
                        return(false);
                    }

                    if (_MessageQueue != null && _MessageQueue.Count > 0)
                    {
                        RunQueue(_MessageQueue);
                        return(true);
                    }
                }
                catch (Exception ex)
                {
                    NLogHelper.GameError("[Message Run] Error:" + ex.Message);
                }
                finally
                {
                    ErrorQueue.Clear();
                }
            }
            return(false);
        }
Пример #19
0
        /// <summary>
        /// 获取设备唯一id  32位 小写英文字母
        /// 此函数第1次调用耗时1-2秒
        /// </summary>
        /// <returns></returns>
        public static string UniqueDeviceId()
        {
            lock (locker)
            {
                if (!String.IsNullOrWhiteSpace(cacheDeviceId))
                {
                    return(cacheDeviceId);
                }
            }


            //bios是固化到主板的程序,有了主板id,可以忽略biosid
            //string deviceId = CpuId() + "_"+ BiosId() + "_" + DiskId() + "_" + MotherboardId();
            //现实中可能更换机器但不更换ip
            string deviceId = CpuId() + "_" + BiosId() + "_" + MotherboardId();

            NLogHelper.Info("DeviceId=" + deviceId);
            string tempDeviceId = GetMD5HashFromString(deviceId);

            lock (locker)
            {
                cacheDeviceId = tempDeviceId;
            }

            return(tempDeviceId);
        }
Пример #20
0
        public void Intercept(IInvocation invocation)
        {
            try
            {
                invocation.Proceed();
            }
            catch (BusinessException ex)
            {
                StringBuilder parms = new StringBuilder(JsonHelper.SerializeObject(invocation.Arguments));
                if (string.IsNullOrWhiteSpace(parms.ToString()))
                {
                    foreach (var a in invocation.Arguments)
                    {
                        parms.Append(string.Format("{0}&", JsonHelper.SerializeObject(a)));
                    }
                }

                var message = string.Format("Message:{0} /n/r Arguments:{1} "
                                            , ex.Message, parms.ToString());

                NLogHelper.Error(string.Format("Method:{0} /n/r  Message:{1}  /n/r Arguments:{2}  "
                                               , ex.ToString()
                                               , invocation.Method.ToString()
                                               , MessageCodesConfig.GetMessageContent(message)));
            }
            catch (Exception ex)
            {
                NLogHelper.Error(ex.ToString(), invocation.Method.ToString()
                                 , string.Format("Message:{0} /n/r Arguments:{1} "
                                                 , ex.Message, JsonHelper.SerializeObject(invocation.Arguments)));
            }
        }
Пример #21
0
        /// <summary>
        /// 消息接收事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private static void ConsumerOnReceived(object sender, BasicDeliverEventArgs args)
        {
            try
            {
                //获取消息
                byte[] body = args?.Body;


                if (body == null || body.Length == 0)
                {
                    NLogHelper.Warn($"接收到空消息");
                    return;
                }

                RMqMessage msg = new RMqMessage()
                {
                    Id           = Guid.NewGuid().ToString(),
                    ContentBytes = body,
                    CreateTime   = DateTime.Now
                };

                RMqMessageHandler.Add(msg);
            }
            catch (Exception e)
            {
                NLogHelper.Error($"mq处理消息失败:{e}");
            }
        }
Пример #22
0
        public IActionResult OnPostQueryList(int pageIndex, int pageSize)
        {
            ResultList <RUserCourseLog> result = new ResultList <RUserCourseLog>();

            try
            {
                var us = base.GetUserSession(false);
                if (us != null)
                {
                    int totalPages;

                    result.List      = _UserSrv.GetUserCourseLogList(us.OpenId, UserCourseLogStatus.SignIn, out totalPages, pageIndex, pageSize);
                    result.TotlaPage = totalPages;
                }
                else
                {
                    result.IntMsg   = -1;
                    result.ErrorMsg = "需要您重新登录!";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMsg = "获取数据失败!";
                NLogHelper.ErrorTxt($"签到列表[OnPostQueryList]:{ex.Message}");
            }
            return(new JsonResult(result));
        }
Пример #23
0
        public IActionResult OnPostQRGen(double payAmount, int courseTime = 0)
        {
            ResultNormal result = new ResultNormal();

            try
            {
                var           url      = $"{Request.Scheme}://{Request.Host}/WX/PayQRMoney?amt={payAmount}&ct={courseTime}";
                var           fileName = $"{payAmount}_{DateTime.Now.ToString("yyyyMMdd_hhmmss")}.png";
                var           savePath = EduEnviroment.DicPath_QRPay + fileName;
                List <string> desc     = new List <string>();
                desc.Add($"请用户扫码付款,支付金额【{payAmount}】元");
                if (courseTime > 0)
                {
                    desc.Add($"共计: 【{courseTime}】节课时");
                }
                QRHelper.GenQR(url, savePath, desc);
                result.SuccessMsg = EduEnviroment.VirPath_QRPay + fileName;
            }
            catch (Exception ex)
            {
                result.ErrorMsg = "生成失败:" + ex.Message;
                NLogHelper.ErrorTxt($"二维码生成失败:{ex.Message}");
            }
            return(new JsonResult(result));
        }
Пример #24
0
        /// <summary>
        /// 发送奖励金
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public IActionResult OnPostSendReward(long invitelogId, string invitedOpenId, string ownOpenId)
        {
            ResultNormal result = new ResultNormal();

            try
            {
                AmountTransType amountTransType = AmountTransType.Invited_TrialReward;
                EUserAccount    ownAccount;
                bool            needWx = _SalesSrv.CreateRewardTrans(invitelogId, ownOpenId, amountTransType, out ownAccount);

                if (ownAccount != null)
                {
                    var ui = _UserSrv.GetUserInfo(invitedOpenId);
                    NLogHelper.InfoTxt($"wxMessage:OpenId-{ownOpenId}");
                    //微信提醒
                    UserAccountChangeTemplate wxMessage = new UserAccountChangeTemplate();
                    wxMessage.data = wxMessage.GenerateData(ownOpenId,
                                                            ui.Name,
                                                            amountTransType,
                                                            DateTime.Now,
                                                            ownAccount.InviteRewards,
                                                            GlobalSrv.GetRewardAmount(amountTransType)
                                                            );
                    WXApi.SendTemplateMessage <UserAccountChangeTemplate>(wxMessage);
                }
            }
            catch (Exception ex)
            {
                result.ErrorMsg = ex.Message;
            }

            return(new JsonResult(result));
        }
Пример #25
0
        public IActionResult OnPostInitPage()
        {
            ResultList <RUserSign> result = new ResultList <RUserSign>();

            try
            {
                var us = base.GetUserSession(false);
                if (us != null)
                {
                    if (us.UserRole == UserRole.Visitor)
                    {
                        result.ErrorMsg = "您还没有购买课程,请先去购买吧";
                        result.IntMsg   = -2;
                        return(new JsonResult(result));
                    }
                    result.List = _UserSrv.GetCurrentUserSign(us.OpenId, us.CurrentScheduleType);
                }
                else
                {
                    result.IntMsg   = -1;
                    result.ErrorMsg = "请重新登陆!";
                }
            }
            catch (EduException eex)
            {
                result.ErrorMsg = eex.Message;
            }
            catch (Exception ex)
            {
                result.ErrorMsg = "页面加载失败,请联系工作人员";
                NLogHelper.ErrorTxt($"签到页面[OnPostInitPage]:{ex.Message}");
            }
            return(new JsonResult(result));
        }
Пример #26
0
        public static EQRStoreAuth CreateStoreAuthUrlById(EQRStoreAuth qr)
        {
            try
            {
                string site = ConfigurationManager.AppSettings["Main_SiteUrl"];
                string url  = site + "Wap/Auth_Store?Id=" + qr.ID;

                string filePath = ConfigurationManager.AppSettings["QR_AuthStore_FP"];
                string filename = "QRAS" + System.DateTime.Now.ToString("yyyyMMddHHmmss") + (new Random()).Next(1, 100).ToString()
                                  + ".jpg";

                filePath    += filename;
                qr.FilePath  = filePath;
                qr.TargetUrl = url;

                //Create QR
                // filePath = PageController.Server.MapPath(filePath);
                filePath = System.Web.HttpContext.Current.Server.MapPath(filePath);
                QRManager.CreateQR(url, filePath, null);
            }
            catch (Exception ex)
            {
                NLogHelper.ErrorTxt(ex.Message);
                throw ex;
            }
            return(qr);
        }
Пример #27
0
 /// <summary>
 /// 记录错误日志
 /// </summary>
 private void LogWriter()
 {
     // 开启一个线程,扫描异常信息队列
     System.Threading.ThreadPool.QueueUserWorkItem(a =>
     {
         while (true)
         {
             // 检查队列中是否存在数据
             if (ErrorHandlingMiddleware.ExceptionQueue.Count > 0)
             {
                 // 将异常对象从队列中拿出来
                 Exception exception = ErrorHandlingMiddleware.ExceptionQueue.Dequeue();
                 // 若异常对象不为空则记录日志
                 if (null != exception)
                 {
                     // 记录错误到日志文件
                     NLogHelper.Write("execption", exception.ToString());
                 }
                 else
                 {
                     // 若异常对象为空则休眠三秒钟
                     System.Threading.Thread.Sleep(3000);
                 }
             }
             else
             {
                 // 若队列中没有数据则休眠三秒钟
                 System.Threading.Thread.Sleep(3000);
             }
         }
     });
 }
Пример #28
0
        private static void Init()
        {
            dynamic type             = (new Program()).GetType();
            string  currentDirectory = Path.GetDirectoryName(type.Assembly.Location);

            NLogHelper.ConsoleInfo($"RunPath:{currentDirectory}");
            _configuration = Configuration.SetBasePath(currentDirectory)
                             .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();


            var serviceCollection = new ServiceCollection()
                                    .AddDbContextPool <EduDbContext>(options =>
            {
                options.UseSqlServer(_configuration.GetConnectionString("EduCenterDB"),     //读取配置文件中的链接字符串
                                     b => b.UseRowNumberForPaging());
            })
                                    .AddTransient <EduDbContext>()
                                    .AddOptions();

            var provider = serviceCollection.BuildServiceProvider();

            _dbContext = provider.GetService <EduDbContext>();
        }
Пример #29
0
        public IActionResult OnPostSave(List <EUserChild> list)
        {
            ResultNormal result = new ResultNormal();

            try
            {
                var us = GetUserSession(false);
                if (us != null)
                {
                    foreach (var c in list)
                    {
                        c.UserOpenId = us.OpenId;
                    }
                    _UserSrv.SaveChildList(list);
                }
                else
                {
                    result.IntMsg   = -1;
                    result.ErrorMsg = "超时,请重新登陆!";
                }
            }
            catch (Exception ex)
            {
                result.ErrorMsg = "保存数据错误!请联系管理员或稍后再试";
                NLogHelper.ErrorTxt(ex.Message);
            }
            return(new JsonResult(result));
        }
Пример #30
0
 public void Start(int port = 8205)
 {
     this.Port = port;
     ThreadPool.QueueUserWorkItem(delegate
     {
         var listener = new TcpListener(IPAddress.Any, this.Port);
         listener.Start();
         while (true)
         {
             var tcpClient = listener.AcceptTcpClient();
             ThreadPool.QueueUserWorkItem(delegate
             {
                 try
                 {
                     using (var networkStream = tcpClient.GetStream())
                     {
                         ProcessRequest(networkStream);
                     }
                 }
                 catch (Exception ex)
                 {
                     NLogHelper.Error(ex);
                 }
             });
         }
     });
 }