Example #1
0
        private QueueItem GetMessage()
        {
            try
            {
                if (_prioritySmsQueue != null && _prioritySmsQueue.Count > 0)
                {
                    lock (((ICollection)_prioritySmsQueue).SyncRoot)
                    {
                        QueueItem smm = _prioritySmsQueue.Dequeue();
                        return(smm);
                    }
                }


                if (_normalSmsQueue != null && _normalSmsQueue.Count > 0)
                {
                    lock (((ICollection)_normalSmsQueue).SyncRoot)
                    {
                        QueueItem smm = _normalSmsQueue.Dequeue();
                        return(smm);
                    }
                }
            }
            catch (System.Exception e)
            {
                SMSLog.Error("【" + _accountInfo.eprId + "】SendService.GetMessage()=>Exception:" + e.Message);
            }
            // thisqueueState.Set();
            return(null);
        }
Example #2
0
        public override int ExecuteNonQuery(int cmdType, string cmdText, object commandParameters)
        {
            int      re  = 0;
            DateTime dt1 = DateTime.Now;

            try
            {
                //SMSGLog.Error(cmdText);
                SqlErrMsg = "";
                MySqlParameter[] cmdParameters = null;
                if (commandParameters != null)
                {
                    cmdParameters = commandParameters as MySqlParameter[];
                }
                re = MySqlHelper.ExecuteNonQuery(ConnectionstringLocalTransaction, cmdText, cmdParameters);
                if ((DateTime.Now - dt1).TotalMilliseconds > 3000)
                {
                    SMSLog.Debug("SqlDBExec =>ExecuteNonQuery 耗时:" + (DateTime.Now - dt1).TotalMilliseconds + "毫秒,result=" + re + ",sql=" + cmdText);
                }
                return(re);
            }
            catch (MySqlException ex)
            {
                SqlErrMsg = ex.Message;
                SMSLog.Error("SqlDBExec =>ExecuteNonQuery Exception:" + cmdText);
                SMSLog.Error("SqlDBExec =>ExecuteNonQuery Exception: ", ex.Message);
            }
            return(0);
        }
Example #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Consume(ConsumeContext <ISendSMS> context)
        {
            Log.Logger = new LoggerConfiguration()
                         .MinimumLevel.Debug()
                         .WriteTo.Console(theme: ConsoleTheme.None)
                         .CreateLogger();
            var start = Stopwatch.GetTimestamp();

            Log.Information("Received command {CommandName}-{MessageId}: {@Messages}", GetType().Name, context.MessageId, context.Message);

            var data   = context.Message;
            var smsLog = new SMSLog();

            switch (data.TypeNotification)
            {
            case TypeNotification.VerifyAccount:
                smsLog = await _smsSender.SendSMSVerifyAccountAsync(data.Data.Phone, data.Data.Message.ToString(), data.ObjectId, data.Culture);

                break;
            }
            if (smsLog != null)
            {
                await _context.SMSLog.InsertOneAsync(smsLog);
            }

            Log.Information("Completed command {CommandName}-{MessageId} {ExecuteTime}ms", GetType().Name, context.MessageId, (Stopwatch.GetTimestamp() - start) * 1000 / (double)Stopwatch.Frequency);
        }
Example #4
0
 // 新增短信发送日志
 private static void SaveLog(string userId, string content, string mobileNo, string result, string sendTime)
 {
     try
     {
         using (EntityContext db = new EntityContext())
         {
             SMSLog SMSloginfo = new SMSLog();
             SMSloginfo.ID          = CommonUtil.GetNewID();
             SMSloginfo.UserId      = userId;
             SMSloginfo.Message     = content;
             SMSloginfo.SMSTYPE     = 1;
             SMSloginfo.MobilePhone = mobileNo;
             SMSloginfo.ReturnStr   = result;
             if (!string.IsNullOrEmpty(sendTime))
             {
                 SMSloginfo.SendTime = DateTime.Parse(sendTime.ToString());
             }
             else
             {
                 SMSloginfo.SendTime = DateTime.Now;
             }
             db.SMSLogs.Add(SMSloginfo);
             db.SaveChanges();
         }
     }
     catch (Exception ex)
     {
         Tools.MessBox(ex.ToString());
     }
 }
Example #5
0
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            try
            {
                string    str         = "";
                string    strDateInfo = "应用程序的主入口点。未处理的异常:" + DateTime.Now.ToString() + "\r\n";
                Exception error       = e.Exception as Exception;
                if (error != null)
                {
                    str = string.Format(strDateInfo + "异常类型:{0}\r\n异常消息:{1}\r\n异常信息:{2}\r\n",
                                        error.GetType().Name, error.Message, error.StackTrace);
                }
                else
                {
                    str = string.Format("应用程序线程错误:{0}", e);
                }

                MyTools.SendSMS("网关【" + GlobalModel.Lparams.GatewayName + "】ThreadException,请查看状态!");
                SMSLog.Error(str);
                MessageBox.Show("F**K!F**K!F**K!", "Application_ThreadException", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception)
            {
            }
        }
Example #6
0
 /// <summary>
 /// 异步连接回调,登录
 /// </summary>
 /// <param name="ir"></param>
 private void ConnectCallBack(IAsyncResult ir)
 {
     try
     {
         if (ir.IsCompleted)
         {
             Socket sok = ir.AsyncState as Socket;
             if (sok != null && sok.Connected)
             {
                 sok.EndConnect(ir);
                 _isConnectionSuccessful = true;
                 CmppConnectModel cc = new CmppConnectModel();
                 cc.Source_Addr = _account;
                 cc.Password    = _password;
                 cc.Version     = 0x20;
                 cc.Timestamp   = Convert.ToUInt32(DateTime.Now.ToString("MMddHHmmss"));
                 Cmpp_Login login = new Cmpp_Login(cc);
                 SendAsync(login.Encode());
                 Receive(sok);
             }
             else
             {
                 SMSLog.Error("【" + _account + "】====>ConnectCallBack(),连接失败");
             }
         }
     }
     catch (Exception ex)
     {
         _isConnectionSuccessful = false;
         SMSLog.Error("【" + _account + "】====>ConnectCallBack()Exception:" + ex.ToString());
     }
 }
        public bool getCode()
        {
            var    smsHelper = new SMSHelper();
            string mobile, code = "";

            try
            {
                UserBll uBll = new UserBll();
                mobile = Request.Params["mobile"].ToString();
                if (uBll.CheckCanSendSms(mobile))
                {
                    code = DateTime.Now.ToString("ssff");
                    //code = "1234";
                    Session["generate_code"] = code;
                    smsHelper.SendSms(mobile, code);
                    SMSLog smsLog = new SMSLog()
                    {
                        telephone = mobile, content = code, Browser = Request.Browser.Browser, ip = Request.UserHostAddress, kdate = DateTime.Now
                    };
                    uBll.AddUserSMSLog(smsLog);
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Example #8
0
        private void CHTQueryWriteSMSLog(string serno, string content)
        {
            content = GetCHTRtnMessage(content);
            string[] MessageSet = content.Split('|');

            if (MessageSet.Length == 4)
            {
                SMSLog entitySL = new SMSLog(_conn);

                if (MessageSet[2] != "null")
                {
                    StringBuilder dt = new StringBuilder();
                    dt.Append(MessageSet[2].Substring(0, 4));
                    dt.Append("/");
                    dt.Append(MessageSet[2].Substring(4, 2));
                    dt.Append("/");
                    dt.Append(MessageSet[2].Substring(6, 2));
                    dt.Append(" ");
                    dt.Append(MessageSet[2].Substring(8, 2));
                    dt.Append(":");
                    dt.Append(MessageSet[2].Substring(10, 2));
                    dt.Append(":");
                    dt.Append(MessageSet[2].Substring(12, 2));
                    entitySL.SLG_DTTM = Convert.ToDateTime(dt.ToString());
                }

                entitySL.SLG_STATUS  = MessageSet[1];
                entitySL.SLG_MESSAGE = MessageSet[3];
                entitySL.update(entitySL.SLG_SERNO.cds_Equal(serno));
            }
        }
Example #9
0
        private void ErrorWriteSMSLog(string serno, string content, string status)
        {
            _conn.startTransaction();
            try
            {
                SMS entityS = new SMS(_conn);
                entityS.SMS_STATUS = status;
                entityS.SMS_DTTM   = DateTime.Now;
                entityS.update(entityS.SMS_SERNO.cds_Equal(serno));

                SMSLog entitySL = new SMSLog(_conn);
                entitySL.SMS_SERNO   = serno;
                entitySL.SLG_SERNO   = EASONTECH.Framework2.Common.Utility.generateSerialNum();
                entitySL.SLG_CONTENT = content;
                entitySL.SLG_DTTM    = DateTime.Now;
                entitySL.SLG_STATUS  = "SysError";
                entitySL.SLG_MESSAGE = content;
                entitySL.insert();

                _conn.commitTransaction();
            }
            catch
            {
                _conn.rollbackTransaction();
            }
        }
Example #10
0
 public void StopMe()
 {
     try
     {
         if (!_isStop)
         {
             if (this.TcpIsCanUse())//发送一条对服务器的通告
             {
                 uint           seq = Tools.GetSequence_Id();
                 CMPP_Terminate t   = new CMPP_Terminate();
                 this.Send(t.Encode());
                 this.HeartStop();
                 SMSLog.Log("=SocketClient==》StopMe()==HeartStop==");
             }
             MyTools.WaitTime(10);  //等待1000ms,告知服务器
             _isStop = true;
             if (_socket != null)
             {
                 _socket.Shutdown(SocketShutdown.Both);
                 _socket.Close();
                 _socket = null;
             }
             SMSLog.Log("=SocketClient==》StopMe()==_socket==");
         }
     }
     catch (Exception ex)
     {
         SMSLog.Log("=SocketClient==》StopMe()异常:" + ex.Message);
     }
 }
Example #11
0
        public void Close()
        {
            try
            {
                if (_socket != null)
                {
                    try
                    {
                        uint           seq = Tools.GetSequence_Id();
                        CMPP_Terminate t   = new CMPP_Terminate();
                        this.Send(t.Encode());
                        SMSLog.Debug("===Close==发送退出命令======");
                        // MyTools.WaitTime(100);
                        Thread.Sleep(100);
                    }
                    catch (Exception ex)
                    {
                        SMSLog.Error("Close Error", ex.Message);
                    }


                    _socket.Shutdown(SocketShutdown.Both);
                    _socket.Close();
                }
            }
            catch
            {
            }
        }
Example #12
0
        public async Task <Response> AddMeal(Guid id, MealDto dto)
        {
            var st = await GetStudentFullDetails(id);

            if (st != null)
            {
                if (st.Parents.Count > 0)
                {
                    var p = st.Parents.First();
                    st.AddMeal(dto.MealType, dto.POSId);
                    _context.Students.Update(st);
                    //SMS
                    var s = SMSLog.Create(p.Phone, $"Dear {p.Name.First} student has ordered a meal on {DateTime.UtcNow} ...");
                    _context.SMSLogs.Add(s);
                    await _context.SaveChangesAsync();

                    //Email
                    _emailService.SendMail(p.Email, "Meal Notice", $"Dear {p.Name.First} student has ordered a meal on {DateTime.UtcNow} ...");
                    return(new Response());
                }
                return(new Response(new List <string> {
                    "Parent not found"
                }));
            }
            return(new Response(new List <string> {
                "Student not found"
            }));
        }
        public async Task SendMessageAsync(string to, string body)
        {
            string sender = _configuration["Twilio:Sender"];

            SMSLog log = new SMSLog
            {
                Sender    = sender,
                Recipient = to,
                Text      = body,
                CreatedAt = DateTime.UtcNow
            };

            try
            {
                var message = await MessageResource.CreateAsync(
                    to : new PhoneNumber(to),
                    from : sender,
                    body : body);

                log.Status = SendingStatus.Success;
            }
            catch (ApiException e)
            {
                log.Status = SendingStatus.Failed;

                _logger.LogError($"Twilio Error {e.Code}({e.Message}) - {e.MoreInfo}");
                throw new SystemException(e.Message);
            }
            finally
            {
                _unitOfWork.Repository <SMSLog>().Insert(log);
                _unitOfWork.SaveChanges();
            }
        }
Example #14
0
 /// <summary>
 /// 异步连接
 /// </summary>
 /// <returns></returns>
 public bool ConnAsync()
 {
     try
     {
         _isConnectionSuccessful = false;
         TimeoutObject.Reset();
         _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         IPEndPoint ipe = new IPEndPoint(IPAddress.Parse(_ip), _port);
         _socket.BeginConnect(ipe, new AsyncCallback(ConnectCallBack), _socket);
         if (TimeoutObject.WaitOne(timeoutMSec, false))
         {
             if (_isConnectionSuccessful && _isLoginSuccessful)
             {
                 _isLogining = false;
                 return(true);
             }
             else
             {
                 SMSLog.Error("【" + _account + "】ConnAsync=====>连接超时");
             }
         }
     }
     catch (Exception ex)
     {
         _bNre = true;
         SMSLog.Error("【" + _account + "】conn=====>" + ex.ToString());
     }
     return(false);
 }
 public bool Stop()
 {
     SMSLog.Debug("SmsService==>Stop=>开始停止");
     GlobalModel.IsStopCollect = true;
     if (_cstDic != null)
     {
         foreach (int key in _cstDic.Keys)
         {
             _cstDic[key].Exit();
         }
     }
     if (ReportQueue != null && ReportQueue.Length > 0)
     {
         foreach (SMDQueue smsq in ReportQueue)
         {
             smsq.Stop();
         }
     }
     if (ReportSeqQueue != null && ReportSeqQueue.Length > 0)
     {
         foreach (SMDQueue smsq in ReportSeqQueue)
         {
             smsq.Stop();
         }
     }
     SMSLog.Debug("SmsService==>Stop=>已结束...");
     return(false);
 }
Example #16
0
 /// <summary>
 /// 同步连接
 /// </summary>
 /// <returns></returns>
 private Socket Conn()
 {
     try
     {
         // System.Threading.Interlocked.Increment(ref i);
         this.Close();
         SMSLog.Debug("---------Conn---连接-------------");
         Socket       sock    = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
         IPEndPoint   ipe     = new IPEndPoint(IPAddress.Parse(_ip), _port);
         IAsyncResult result  = sock.BeginConnect(ipe, null, null); //连接
         bool         success = result.AsyncWaitHandle.WaitOne(1000, false);
         if (!success)
         {
             SMSLog.Debug("---------Conn---连接--超时-----------");
             try { sock.Close(); }
             catch { }
             throw new SocketException();
         }
         sock.EndConnect(result);
         _isConnectionSuccessful = true;
         SMSLog.Debug("---------Conn---连接--成功-----------");
         return(sock);
     }
     catch (SocketException se)
     {
         _isConnectionSuccessful = false;
         _bNre = true;
         SMSLog.Error("--------Conn-----连接失败-------Exception:" + se.Message);
     }
     return(null);
 }
Example #17
0
        public void Query()
        {
            try
            {
                SMSLog        entityS   = new SMSLog(_conn);
                StringBuilder Cndstring = new StringBuilder();

                Cndstring.Append(entityS.SLG_MESSAGE.cds_NotEqual("Successful"));
                Cndstring.Append(" and ");
                Cndstring.Append(entityS.SLG_DTTM.cds_BetweenDate(DateTime.Now.Date, DateTime.Now.Date));

                entityS.query(null, Cndstring.ToString(), "");

                while (entityS.read())
                {
                    switch (MoblieType)
                    {
                    case "SMSTaiwanMoblie":
                        //QueryTaiwanMoblie();
                        break;

                    case "SMSCHTMoblie":
                        QueryCHTMoblie(entityS.SLG_SERNO.ToString(), entityS.SLG_CONTENT.ToString());
                        break;

                    default:
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                string ErrMessage = ex.Message;
            }
        }
        private void SendSMS(string SendText, string Mobile, SysSet SS)
        {
            SMSLog SMSLog = new SMSLog();

            SMSLog.SendText = SendText;
            SMSLog.Mobile   = Mobile;
            SMSLog.SendSMS(SS, Entity);
        }
Example #19
0
        public bool CheckCanSendSms(string mobile)
        {
            SMSLog smsLog = new SMSLog()
            {
                telephone = mobile
            };

            return(userDao.SelectUserSmsLogByData(smsLog));
        }
        /// <summary>
        /// 根据批次号修改手机号码表状态
        /// </summary>
        /// <param name="state">状态:0未提交,-1失败,1成功</param>
        /// <param name="batchnum">批次号</param>
        /// <param name="errorCode">错误码</param>
        /// <param name="errMsg">错误说明</param>
        /// <returns></returns>
        private void UpdateMobileByBatchNum(int state, string batchnum, string errorCode, string errMsg)
        {
            string sql    = string.Format("update t_smsmobile_t set SubmitStatus={0},ErrorCode='{1}',Remark='{2}' where BatchNum='{3}'", state, errorCode, errMsg, batchnum);
            int    result = MySqlDBExec.ExecuteNonQuery(sql, null);

            if (result == 0)
            {
                SMSLog.Debug("SmsService==>UpdateSMSContentSubmitStatu[FailSql]:" + sql);
            }
        }
        /// <summary>
        /// 修改ct提交状态,待下次读取
        /// </summary>
        /// <param name="id">内容表id</param>
        /// <param name="cTSubmitStatus">状态0 可读取,1已发完</param>
        /// <returns></returns>
        private void UpdateSMSContentSubmitStatu(string id, int cTSubmitStatus)
        {
            string sql    = string.Format("update  t_sendsms set CTSubmitStatus={0} where Id={1} ", cTSubmitStatus, id);
            int    result = MySqlDBExec.ExecuteNonQuery(sql, null);

            if (result == 0)
            {
                SMSLog.Debug("SmsService==>UpdateSMSContentSubmitStatu[FailSql]:" + sql);
            }
        }
        /// <summary>
        /// 删除内容
        /// </summary>
        /// <param name="id">内容表id</param>
        /// <returns></returns>
        private void DeleteContent(string id)
        {
            string delsql = string.Format("delete from t_sendsms where id={0} and CMSubmitStatus='1' and CUSubmitStatus='1' and CTSubmitStatus='1' ", id);
            int    result = MySqlDBExec.ExecuteNonQuery(delsql, null);

            if (result == 0)
            {
                SMSLog.Debug("SmsService==>DeleteContent[FailSql]:" + delsql);
            }
        }
        private void SendSMS(string SendText, string Mobile, SysSet SS)
        {
            SMSLog SMSLog = new SMSLog();

            SMSLog.SendText = SendText;
            SMSLog.Mobile   = Mobile;
            SysAgent SA = BasicAgent.GetTopAgent(Entity);

            SMSLog.SendSMS(SS, SA, Entity);
        }
 private void AddCache(string msgid, SmsModel msg)
 {
     try
     {
         cache.Add(msgid, msg);
     }
     catch (Exception ex)
     {
         SMSLog.Error("SMDDatabase::[" + msgid + "],Id=" + msg.id + " AddCache:Exception:", ex.Message);
     }
 }
Example #25
0
        private void WriteSMSLog(string serno, string content)
        {
            SMSLog entity = new SMSLog(_conn);

            entity.SMS_SERNO   = serno;
            entity.SLG_SERNO   = EASONTECH.Framework2.Common.Utility.generateSerialNum();
            entity.SLG_CONTENT = content;
            entity.SLG_DTTM    = DateTime.Now;

            entity.insert();
        }
Example #26
0
 //多线程
 private void Send(object obj)
 {
     try
     {
         Submit();
     }
     catch (Exception ex)
     {
         SMSLog.Error("CmppSendThread==>Submit Exception:" + ex.Message);
     }
 }
Example #27
0
    protected void btnHasten_Click(object sender, EventArgs e)
    {
        SMSLog sMSData = this.GetSMSData();
        int    num     = PublicInterface.SendSmsMsg(sMSData);

        if (num > 0)
        {
            this.Page.RegisterStartupScript("", "<script>alert('档案借阅催还信息发送成功!');</script>");
            return;
        }
        this.Page.RegisterStartupScript("", "<script>alert('档案借阅催还信息发送失败!');</script>");
    }
Example #28
0
 public static int SendSmsMsg(SMSLog model)
 {
     if (IsDays(DateTime.Now, model.SendTime))
     {
         string receiverMobileNo = GetReceiverMobileNo(model.ReceiveUser);
         if (receiverMobileNo != "0")
         {
             SMSLogTodayAdd(model, receiverMobileNo);
         }
     }
     return(SMSLogAdd(model));
 }
Example #29
0
        /// <summary>
        /// 获取手机验证码
        /// </summary>
        public void GetSMSCode()
        {
            using (ProxyBE p = new ProxyBE())
            {
                try
                {
                    string phone = Request["phone"];
                    if (string.IsNullOrEmpty(phone))
                    {
                        throw new Exception("手机号不能为空");
                    }
                    Partner partnerModel = p.Client.GetPartnerByMobile(SenderUser, phone);
                    if (partnerModel != null)
                    {
                        throw new Exception("该手机号码已经被注册");
                    }

                    string smsCode    = SMSHelper.GetRandom(6);
                    bool   isComplete = false;
                    //短信验证码限制:小于等于 1天/5次 5条/小时 累计10条/天
                    string message = SMSHelper.SendMessage(phone, smsCode, out isComplete);
                    if (isComplete)
                    {
                        // 将手机验证码存入session
                        SetCacheSMSCode(smsCode);

                        //记录手机注册短信到数据库表
                        SMSLog smsLog = new SMSLog()
                        {
                            ID      = Guid.NewGuid(),
                            Phone   = phone,
                            Message = smsCode,
                            Created = DateTime.Now,
                            Status  = true
                        };
                        SaveSMSLogArgs args = new SaveSMSLogArgs();
                        args.SMSLog = smsLog;
                        p.Client.SaveSMSLog(SenderUser, args);

                        //短信日志
                        WriteSuccess();
                    }
                    else
                    {
                        throw new Exception("发送失败," + message);
                    }
                }
                catch (Exception ex)
                {
                    WriteError(ex.Message, ex);
                }
            }
        }
 private SmsModel GetFormCache(string msgid)
 {
     try
     {
         SmsModel obj = cache.Get(msgid) as SmsModel;
         return(obj);
     }
     catch (Exception ex)
     {
         SMSLog.Error("SMDDatabase:: GetFormCache:Exception:", ex.Message);
     }
     return(null);
 }