public ActionResult CheckMsg() { //1:APP消息,2:平台短信 int type = 2; //发送方式(0按小朋友,1按老师,2按年级,3按班级,4按部门,5按职位) SmsInfo sms = new SmsInfo(); sms.content = Request["content"] ?? ""; sms.senderuserId = UserID; sms.reccid = ""; sms.recteaids = Request["teachers"] ?? ""; sms.recuserId = Request["students"] ?? ""; sms.sendtype = Convert.ToInt32(string.IsNullOrWhiteSpace(Request["students"]) ? 1 : 0); sms.kid = Convert.ToInt32(Request["kid"] ?? "0"); sms.smstype = Convert.ToInt32(Request["smstype"] ?? "1"); sms.smstitle = Request["title"] ?? "幼儿园通知"; sms.istime = Convert.ToInt32(Request["istime"] ?? "0"); sms.sendtime = Convert.ToDateTime(string.IsNullOrWhiteSpace(Request["sendtime"]) ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : Request["sendtime"]); sms.auditSms = Convert.ToInt32(Request["needAudit"] ?? "1"); sms.issms = 1; //1:APP短信,2:平台短信 SmsReturn smsret = SmsDataProxy.CheckSmsValid(sms); //1成功,2短信不足,3待审核 return(this.Json(smsret, JsonRequestBehavior.AllowGet)); }
public static bool WriteRecord(string json) { try { if (!json.StartsWith("[") || !json.EndsWith("]")) { json = "[" + json + "]"; } JArray array = JArray.Parse(json); foreach (var item in array.Children()) { JObject jrow = JObject.Parse(item.ToString()); SmsInfo smsRow = new SmsInfo(); smsRow.phone = (string)jrow["phone_number"]; smsRow.content = (string)jrow["content"]; smsRow.time = (string)jrow["send_time"]; Console.WriteLine(smsRow.ToString()); //csv.WriteRecord(smsRow); //csv.NextRecord(); csvWriter.WriteLine(smsRow.ToString()); } } catch (Exception e) { Console.Write("ERR: " + e.Message); return(false); } return(true); }
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "application/json"; try { string strJson = new StreamReader(context.Request.InputStream).ReadToEnd(); //deserialize the object SmsInfo objUsr = Deserialize <SmsInfo>(strJson); var task1 = SmsService.SendSms(objUsr.message, objUsr.phoneto); task1.Start(); task1.Wait(); if (task1.Result) { context.Response.Write("{ 'result':'success'}"); } else { context.Response.Write("{ 'result':'failed'}"); } } catch (Exception ex) { context.Response.Write("{ 'result':'{" + ex.Message + "}"); } }
internal static void EnqueuSMS(SmsInfo smsInfo, SiteSettings settings) { if (smsInfo != null && !string.IsNullOrEmpty(smsInfo.Mobile)) { new SMSQueueDao().QueueSMS(smsInfo); } }
public override bool Init(string content) { var result = base.Init(content); if (Success) { if (!content.Contains("CMGR:")) { return(false); } var a = new SmsInfo(); int pos = content.IndexOf("CMGR:"); pos = content.IndexOf("\r\n", pos) + 2; int pos2 = content.IndexOf("\r\n", pos); if (pos2 == -1) { pos2 = content.Length; } string smsContent = content.Substring(pos, pos2 - pos); SmsInfo ra = a.DecodingSMS(smsContent); Content = ra.UD.Replace("\\0", ""); SendMobile = ra.OAAddr; SCAAddr = ra.SCAAddr; ReceiveTime = DateTime.Parse(ra.SCTS); } return(result); }
public void TestServiceSms() { bool res = true; try { Client client = new Client(publickey, privatekey, mode); PlaceOrderInfo order = new PlaceOrderInfo( "12", "M4 C# SDK", 180, "Eduardo Aguilar", "*****@*****.**" ); NewOrderInfo neworder = client.api.placeOrder(order); SmsInfo response = client.api.sendSmsInstructions(phone_number, neworder.getId()); res = !response.getType().Equals(""); } catch (Exception e) { res = false; } Assert.IsTrue(res); }
/// <summary> /// 获取剩余短信数量 /// </summary> /// <param name="smsInfo">sms短信平台信息</param> /// <returns>剩余短信数量</returns> public static SendResult GetSMSNum(SmsInfo smsInfo, out int smsNum, bool isMD5 = true) { ///获取短信数量接口地址(UTF8): ///http://sms.webchinese.cn/web_api/SMS/?Action=SMS_Num&Uid=本站用户名&Key=接口安全秘钥 string requestUriString; //请求地址 smsNum = 0; //最终剩余短信数量 if (isMD5) { //密钥加密 requestUriString = String.Format("http://sms.webchinese.cn/web_api/SMS/?Action=SMS_Num&Uid={0}&KeyMD5={1}", smsInfo.Uid, EncryptHelper.HashMD532(smsInfo.Key)); } else { requestUriString = String.Format("http://sms.webchinese.cn/web_api/SMS/?Action=SMS_Num&Uid={0}&Key={1}", smsInfo.Uid, smsInfo.Key); } //创建请求并获取响应 string result = GetResponseByUri(requestUriString); //读取响应结果 int intResult = 0; //响应结果尝试转成整型 int.TryParse(result, out intResult); if (intResult >= 0) { //获取短信数量成功 smsNum = intResult; return((SendResult)Enum.ToObject(typeof(SendResult), 1)); } return((SendResult)intResult); }
public static SmsInfo LoadPhoneSmsRuleById(int id) { string text = new AssetLoader().LoadTextSync(AssetLoader.GetPhoneDataPath(id.ToString())); SmsInfo info = JsonConvert.DeserializeObject <SmsInfo>(text); return(info); }
public bool QueueSMS(SmsInfo message) { if (message != null) { StringBuilder sql = new StringBuilder(); sql.Append("INSERT INTO Ecshop_SMSQueue(SmsId, Mobile, Subject, Body, Priority, NextTryTime, NumberOfTries,Type) VALUES(@SmsId, @Mobile, @Subject, @Body, @Priority, @NextTryTime, @NumberOfTries,@Type);"); if (!string.IsNullOrWhiteSpace(message.ClaimCode)) { // 更改为已提醒 sql.Append(" update Ecshop_CouponItems set WarnStatus = 1 where ClaimCode = @claimcode "); } DbCommand sqlStringCommand = this.database.GetSqlStringCommand(sql.ToString()); this.database.AddInParameter(sqlStringCommand, "SmsId", DbType.Guid, Guid.NewGuid()); this.database.AddInParameter(sqlStringCommand, "Mobile", DbType.String, message.Mobile); this.database.AddInParameter(sqlStringCommand, "Subject", DbType.String, message.Subject); this.database.AddInParameter(sqlStringCommand, "Body", DbType.String, message.Body); this.database.AddInParameter(sqlStringCommand, "Priority", DbType.Int32, (int)message.Priority); this.database.AddInParameter(sqlStringCommand, "NextTryTime", DbType.DateTime, DateTime.Parse("1900-1-1 12:00:00")); this.database.AddInParameter(sqlStringCommand, "NumberOfTries", DbType.Int32, 0); this.database.AddInParameter(sqlStringCommand, "Type", DbType.Int32, message.type); this.database.AddInParameter(sqlStringCommand, "claimcode", DbType.String, message.ClaimCode); return(this.database.ExecuteNonQuery(sqlStringCommand) > 0); } return(false); }
/// <summary> /// 发送短信 /// </summary> /// <param name="mobile">接收消息的手机号</param> /// <param name="content">短信内容</param> /// <param name="resultNum">输出参数,成功发送的短信数量</param> /// <param name="isMD5">可选,是否对密钥进行MD5加密,默认加密</param> /// <returns>短信发送结果枚举</returns> public static SendResult SendMessage(string mobile, string content, out int resultNum, bool isMD5 = true) { SmsInfo smsInfo = new SmsInfo(ToolOptions.SMSUId, ToolOptions.SMSPassword, mobile, content); SendResult sendResult = SendMessage(smsInfo, out resultNum); return(sendResult); }
public bool Send(string phone, string sms, SmsFormat format) { lock (lockItem) { MakeSureConnection(); sms = sms.Replace("\r\n", ""); string[] contentSet = CutMessageFromContent(sms); if (ChinaMobile && contentSet.Length > 1) { return(SendMobile(phone, sms, format)); } for (int i = 0; i < contentSet.Length; i++) { string content = contentSet[i]; var messageFromat = new SetSmsFromatCommand(format); AbstractCommand resultCommand = Send(messageFromat); if (!resultCommand.Success) { return(false); } var cmgsCommand = new CmgsCommand(); if (format == SmsFormat.Pdu) { var info = new SmsInfo(ServiceCenterNumber, phone, content); int smsLen = 0; content = info.EncodingSMS(out smsLen); cmgsCommand.Argument = string.Format(smsLen.ToString("D2")); } else { cmgsCommand.Argument = phone; } resultCommand = Send(cmgsCommand); if (!resultCommand.Success) { return(false); } var directCommand = new SendContent { Content = content }; resultCommand = Send(directCommand); if (!resultCommand.Success) { return(false); } Thread.Sleep(1000); } Thread.Sleep(1000); } return(true); }
/// <remarks/> public void sendAsync(SmsInfo sms, object userState) { if ((this.sendOperationCompleted == null)) { this.sendOperationCompleted = new System.Threading.SendOrPostCallback(this.OnsendOperationCompleted); } this.InvokeAsync("send", new object[] { sms }, this.sendOperationCompleted, userState); }
private SmsInfo GetGuvenSmsInfo() { var info = new SmsInfo(); info.Ordinator = _guvenSmsConfig.Value.Orjinator; var t = GetGuvenSmsInfoRequest(); int.TryParse(t, out var i); info.SmsCount = i; return(info); }
public static bool QueueSMS(string mobile, string body, int priority, int type) { SmsInfo message = new SmsInfo(); message.SmsId = Guid.NewGuid(); message.Mobile = mobile; message.Subject = ""; message.Body = body; message.Priority = priority; message.type = type; return(QueueSMS(message)); }
private static Dictionary <int, Dictionary <string, bool> > FindPhoneAudio() { DirectoryInfo dir = new DirectoryInfo(PhoneJsonPath); FileInfo[] files = dir.GetFiles("*.json"); Dictionary <int, Dictionary <string, bool> > fileDict = new Dictionary <int, Dictionary <string, bool> >(); foreach (var file in files) { string num = file.Name.Replace(".json", ""); int result; if (int.TryParse(num, out result) == false || result >= 20000) { continue; } string text = FileUtil.ReadFileText(file.FullName); SmsInfo info = JsonConvert.DeserializeObject <SmsInfo>(text); int npcId = -1; foreach (var talkInfo in info.smsTalkInfos) { if (talkInfo.NpcId != 0) { npcId = talkInfo.NpcId; } string mId = talkInfo.MusicID; if (string.IsNullOrEmpty(mId) || mId == "0") { continue; } if (fileDict.ContainsKey(npcId) == false) { fileDict[npcId] = new Dictionary <string, bool>(); } if (fileDict[npcId].ContainsKey(mId) == false) { fileDict[npcId].Add(mId, true); } } } string str = JsonConvert.SerializeObject(fileDict, Formatting.Indented); FileUtil.SaveFileText(GetPackageDir(), "PhoneAudio.json", str); return(fileDict); }
public SmsInfo PopulateSMSFromIDataReader(IDataReader reader) { SmsInfo result; if (null == reader) { result = null; } else { try { SmsInfo mailMessage = new SmsInfo(); if (reader["SmsId"] != DBNull.Value) { mailMessage.SmsId = (Guid)reader["SmsId"]; } if (reader["Priority"] != DBNull.Value) { mailMessage.Priority = (int)reader["Priority"]; } if (reader["Subject"] != DBNull.Value) { mailMessage.Subject = (string)reader["Subject"]; } if (reader["Mobile"] != DBNull.Value) { mailMessage.Mobile = (string)reader["Mobile"]; } if (reader["Body"] != DBNull.Value) { mailMessage.Body = (string)reader["Body"]; } if (reader["Type"] != DBNull.Value) { mailMessage.type = (int)reader["Type"]; } result = mailMessage; } catch { result = null; } } return(result); }
public static async Task <bool> SendSms(string phoneto, string message) { if (client == null) { client = new HttpClient(); } var obj = new SmsInfo() { message = message, phoneto = phoneto }; var json = JsonConvert.SerializeObject(obj); var res = await client.PostAsync(DataConfig.UrlSms, new StringContent(json, Encoding.UTF8, "application/json")); return(res.IsSuccessStatusCode); }
private SmsInfo GetMesajPanaliSmsInfo() { var info = new SmsInfo(); info.Ordinator = _smsVitriniConfig.Value.Baslik; smsData MesajPaneli = new smsData(); MesajPaneli.user = new UserInfo(_smsVitriniConfig.Value.Name, _smsVitriniConfig.Value.Pass); ReturnValue ReturnData = MesajPaneli.DoPost("http://api.mesajpaneli.com/json_api/login/", true, true); info.SmsCount = ReturnData.userData.orjinli; return(info); }
public static SmsInfo smsInfo(string source) { var serializer = new JavaScriptSerializer(); SmsInfo obj = null; if (verifierVersion(source, serializer)) { obj = serializer.Deserialize <SmsInfo11>(source); } else { obj = serializer.Deserialize <SmsInfo10>(source); } return(obj); }
/// <summary> /// api获取手机验证码 /// </summary> /// <param name="mobile"></param> /// <param name="sign"></param> /// <param name="apiKey"></param> /// <param name="accountId"></param> /// <returns></returns> public ResponsResult ApiGetVerifyCode(string mobile, string sign, string apiKey, string accountId = "") { ResponsResult result = new ResponsResult(); if (string.IsNullOrEmpty(mobile)) { return(result.SetStatus(ErrorCode.CannotEmpty, "请输入手机号!")); } if (!mobile.IsMobile()) { return(result.SetStatus(ErrorCode.InvalidMobile, "手机号格式不正确!")); } if (string.IsNullOrEmpty(apiKey)) { return(result.SetStatus(ErrorCode.CannotEmpty, "输入不正确!")); } if (!Security.ValidSign(sign, apiKey, mobile)) { return(result.SetStatus(ErrorCode.InvalidSign)); } var message = CheckRequest(ServiceCollectionExtension.ClientIP, mobile); if (!string.IsNullOrEmpty(message)) { return(result.SetStatus(ErrorCode.BadRequest, message)); } var codeList = Enumerable.Range(0, 9).OrderBy(t => Guid.NewGuid()).Skip(3).Take(6); var code = string.Join("", codeList); result.Message = $"验证码已发送到你的手机,有效时长{TbConstant.CodeValidMinutes}分钟"; /**/ SmsInfo sms = new SmsInfo { Code = code, Contents = "获取验证码", Ip = ServiceCollectionExtension.ClientIP, Mobile = mobile, CreateTime = DateTime.Now, AccountId = accountId }; base.Add(sms, true); return(result); }
public ResponsResult GetValidCode(string mobile) { ResponsResult result = new ResponsResult(); if (string.IsNullOrEmpty(mobile)) { return(result.SetStatus(ErrorCode.CannotEmpty, "请输入手机号!")); } if (!mobile.IsMobile()) { return(result.SetStatus(ErrorCode.InvalidMobile, "手机号格式不正确!")); } if (this.Exists <Account>(t => t.RealName == mobile)) { return(result.SetStatus(ErrorCode.Existed, "该手机号已注册! 如果该手机号为你所有,请登录!")); } var message = CheckRequest(ServiceCollectionExtension.ClientIP, mobile); if (!string.IsNullOrEmpty(message)) { return(result.SetStatus(ErrorCode.BadRequest, message)); } var codeList = Enumerable.Range(0, 9).OrderBy(t => Guid.NewGuid()).Skip(3).Take(6); var code = string.Join("", codeList); result.Message = $"验证码已发送到你的手机,有效时长{TbConstant.CodeValidMinutes}分钟"; //MobileRequest request = new MobileRequest(mobile, $"{{code:'{code}',product:'{Constant.CompanyName}'}}"); //var response = request.Excute(); //if (!response.Success || response.ErrCode != 0) //{ // return result.SetError(response.Msg); //} SmsInfo sms = new SmsInfo { Code = code, Contents = "获取验证码", Ip = ServiceCollectionExtension.ClientIP, Mobile = mobile, CreateTime = DateTime.Now, }; base.Add(sms, true); return(result); }
//GAL start private void InitializeDashboard() { receiverUI1 = new ReceiverUI(); receiverUI2 = new ReceiverUI(); receiverUI3 = new ReceiverUI(); receiverUI4 = new ReceiverUI(); ARFCN1 = new UnitView(); ARFCN2 = new UnitView(); ARFCN3 = new UnitView(); ARFCN4 = new UnitView(); SetReceiverUI(receiverUI1, 1); SetReceiverUI(receiverUI2, 2); SetReceiverUI(receiverUI3, 3); SetReceiverUI(receiverUI4, 4); BrushConverter conv = new BrushConverter(); dashboardButtonFiles = new DashboardButton(); FilesInfo filesButton = new FilesInfo(); SetDashboardButton("#ffea6c41", filesButton.ItemName, filesButton.Count, PackIconMaterialKind.File, dashboardButtonFiles); dashboardButtonRecordFiles = new DashboardButton(); RecordsInfo recordsButton = new RecordsInfo(); SetDashboardButton("#ffe69a2a", recordsButton.ItemName, recordsButton.Count, PackIconMaterialKind.RecordRec, dashboardButtonRecordFiles); dashboardButtonPhoneCalls = new DashboardButton(); CallsInfo callButton = new CallsInfo(); SetDashboardButton("#FF469408", callButton.ItemName, callButton.Count, PackIconMaterialKind.PhoneLog, dashboardButtonPhoneCalls); dashboardButtonSmsMessages = new DashboardButton(); SmsInfo smsButton = new SmsInfo(); SetDashboardButton("#FF177EC1", smsButton.ItemName, smsButton.Count, PackIconMaterialKind.EmailOpen, dashboardButtonSmsMessages); Units = TransferDB.Units; computers = TransferDB.Computers; }
public ActionResult SendSMS() { //1:APP消息,2:平台短信 int type = 2; //发送方式(0按小朋友,1按老师,2按年级,3按班级,4按部门,5按职位) SmsInfo sms = new SmsInfo(); sms.content = Request["content"] ?? ""; sms.senderuserId = UserID; //sms.reccid = ""; sms.recteaids = Request["teachers"] ?? ""; sms.recuserId = Request["students"] ?? ""; sms.sendtype = Convert.ToInt32(string.IsNullOrWhiteSpace(Request["students"]) ? 1 : 0); sms.kid = Convert.ToInt32(Request["kid"] ?? "0"); sms.smstype = Convert.ToInt32(Request["smstype"] ?? "1"); sms.smstitle = Request["title"] ?? "幼儿园通知"; sms.istime = Convert.ToInt32(Request["istime"] ?? "0"); sms.sendtime = Convert.ToDateTime(string.IsNullOrWhiteSpace(Request["sendtime"]) ? DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") : Request["sendtime"]); sms.issms = 1; //sms.img_url = ""; SmsReturn smsret = new SmsReturn(); //smsret.result = 1; //1:APP短信,2:平台短信 if (Request["needAudit"] == "1" && Request["role"] != "0")//园长、管理员不需要审核 { //审核后再发送 smsret = SmsDataProxy.audit_SendSMS(sms); if (smsret.result > 2) { smsret.result = 3; } } else { if (type == 2) { smsret = SmsDataProxy.class_sms_ADD_V3_mobile(sms); } } //1成功,2短信不足,3待审核 return(this.Json(smsret, JsonRequestBehavior.AllowGet)); }
/// <summary> /// 发送短信 /// </summary> /// <param name="smsInfo">sms短信平台信息</param> /// <param name="resultNum">输出参数,成功发送的短信数量</param> /// <param name="isMD5">可选,是否对密钥进行MD5加密,默认加密</param> /// <returns>短信发送结果枚举</returns> public static SendResult SendMessage(SmsInfo smsInfo, out int resultNum, bool isMD5 = true) { ///UTF-8编码发送接口地址: ///http://utf8.sms.webchinese.cn/?Uid=本站用户名&Key=接口安全秘钥&smsMob=手机号码&smsText=验证码:8888 resultNum = 0; //字符串拼接出请求地址 StringBuilder requestUri = new StringBuilder(); requestUri.Append(url); requestUri.Append(strUid); requestUri.Append(smsInfo.Uid); if (isMD5) { //密钥加密 requestUri.Append(strKeyMD5); requestUri.Append(EncryptHelper.HashMD532(smsInfo.Key)); } else { requestUri.Append(strKey); requestUri.Append(smsInfo.Key); } requestUri.Append(strMob); requestUri.Append(smsInfo.SmsMob); requestUri.Append(strContent); requestUri.Append(smsInfo.SmsText); string requestUriString = requestUri.ToString(); //创建请求并获取响应 string result = GetResponseByUri(requestUriString); //读取响应结果 int intResult = 0; //响应结果尝试转成整型 int.TryParse(result, out intResult); if (intResult > 0) { //发送短信成功 resultNum = intResult; return((SendResult)Enum.ToObject(typeof(SendResult), 1)); } return((SendResult)intResult); }
public Dictionary <Guid, SmsInfo> DequeueSMS() { DbCommand sqlStringCommand = this.database.GetSqlStringCommand("SELECT * FROM Ecshop_SMSQueue WHERE NextTryTime < GETDATE() ORDER BY Priority DESC"); Dictionary <Guid, SmsInfo> dictionary = new Dictionary <Guid, SmsInfo>(); using (IDataReader dataReader = this.database.ExecuteReader(sqlStringCommand)) { while (dataReader.Read()) { SmsInfo mailMessage = this.PopulateSMSFromIDataReader(dataReader); if (mailMessage != null) { dictionary.Add((Guid)dataReader["SmsId"], mailMessage); } else { this.DeleteQueuedSMS((Guid)dataReader["SmsId"]); } } dataReader.Close(); } return(dictionary); }
public string Send_HW(SmsInfo model) { return(this.GetMessage("华为", model)); }
public BaseResult SendSms(SmsInfo sms) { var rs = new BaseResult { State = false, Value = -1, Desc = "数据操作层初始化" }; if (sms.UserID <= 0) { rs.Failed(-101, "userId无效"); return rs; } if (sms == null) { rs.Failed(-102, "sms无效"); return rs; } _desc = "发送短信"; _procName = "UP_SMS_AddSms"; _methodName = MethodBase.GetCurrentMethod().Name; _log = new LogBuilder { Method = string.Format("类[{0}]方法[{1}]", ClassName, _methodName), Desc = _desc, Database = _databaseName, StroreProcedure = _procName }; _log.Append("userId", sms.UserID); try { StringBuilder smsDetailXML = new StringBuilder(); smsDetailXML.Append("<SmsList>"); sms.SmsDetailList.ForEach((item) => { smsDetailXML.Append("<Sms>"); smsDetailXML.AppendFormat("<Mobile>{0}</Mobile>", item.Mobile); smsDetailXML.AppendFormat("<Name>{0}</Name>", item.Name); smsDetailXML.Append("</Sms>"); }); smsDetailXML.Append("</SmsList>"); var parameters = new[] { _smsDatabase.MakeInParam("@UserId", SqlDbType.Int, 4, sms.UserID), _smsDatabase.MakeInParam("@TaskName", SqlDbType.VarChar, sms.TaskName), _smsDatabase.MakeInParam("@Sender", SqlDbType.VarChar, sms.Sender), _smsDatabase.MakeInParam("@Priority", SqlDbType.Int,(int) sms.Priority), _smsDatabase.MakeInParam("@InputType", SqlDbType.Int,(int) sms.InputType), _smsDatabase.MakeInParam("@SendWay", SqlDbType.Int, (int)sms.SendWay), _smsDatabase.MakeInParam("@SendTime", SqlDbType.DateTime, sms.SendTime), _smsDatabase.MakeInParam("@SubmitTime", SqlDbType.DateTime, sms.SubmitTime), _smsDatabase.MakeInParam("@Message", SqlDbType.VarChar, sms.Message), _smsDatabase.MakeInParam("@SmsType", SqlDbType.VarChar, (int)sms.SmsType), _smsDatabase.MakeInParam("@SmsDetailXML",SqlDbType.Xml,smsDetailXML.ToString()), _smsDatabase.MakeOutParam("@MsgID", SqlDbType.VarChar,16) }; _smsDatabase.ExecuteProc(_procName, parameters, out _result); if (_result != 1) { rs.Failed(-2, "todo"); return rs; } } catch (Exception ex) { rs.Failed(-1, "todo"); _log.Exception = string.Format("{0},发生异常:{1}", _desc, ex.Message); _log.Error(); return rs; } finally { _smsDatabase.Close();//仅显式关闭链接,不做其它操作 } rs.Success(); return rs; }
public static void SendQueuedSMS(int failureInterval, int maxNumberOfTries, SiteSettings settings) { ErrorLog.Write("开始发送短信,进入队列..."); if (settings != null) { HiConfiguration config = HiConfiguration.GetConfig(); Dictionary <System.Guid, SmsInfo> dictionary = new SMSQueueDao().DequeueSMS(); IList <System.Guid> list = new List <System.Guid>(); ErrorLog.Write("开始发送短信,创建发送对象..."); SMSSender sender = Messenger.CreateSMSSender(settings); if (sender != null) { int num = 0; int smsSendBatchSize = 500; foreach (System.Guid current in dictionary.Keys) { SmsInfo currentSms = dictionary[current]; string msg = ""; SendStatus sendStatus = SendStatus.Fail; try { ErrorLog.Write(string.Format("发送短信,手机号码:{0},短信内容:{1}", currentSms.Mobile, currentSms.Body)); if (currentSms.type == 2) { sendStatus = Messenger.SendSMS(currentSms.Mobile, currentSms.Body, settings, currentSms.type, out msg); } else { sendStatus = Messenger.SendSMS(currentSms.Mobile, currentSms.Body, settings, out msg); } } catch (Exception ex) { ErrorLog.Write(string.Format("发送短信异常,手机号码:{0},短信内容:{1},原因:{2}", currentSms.Mobile, currentSms.Body, ex.Message)); } if (sendStatus == SendStatus.Success) { ErrorLog.Write(string.Format("发送短信成功,开始删除队列,手机号码:{0},短信内容:{1}", currentSms.Mobile, currentSms.Body)); new SMSQueueDao().DeleteQueuedSMS(current); if (smsSendBatchSize != -1 && ++num >= smsSendBatchSize) { System.Threading.Thread.Sleep(new System.TimeSpan(0, 0, 0, 15, 0)); num = 0; } } else { ErrorLog.Write(string.Format("发送短信失败,手机号码:{0},短信内容:{1},加入失败队列", currentSms.Mobile, currentSms.Body)); list.Add(current); } } if (list.Count > 0) { ErrorLog.Write("发送短信包含失败号码,重置发送队列"); new SMSQueueDao().QueueSendingFailure(list, failureInterval, maxNumberOfTries); } } else { ErrorLog.Write("开始发送短信,发送对象创建不成功,请检查配置..."); } } }
/// <summary> /// 获取短信主记录列表 /// </summary> /// <param name="userId"></param> /// <param name="taskName"></param> /// <param name="startTime"></param> /// <param name="endTime"></param> /// <param name="pageSize"></param> /// <param name="pageIndex"></param> /// <returns></returns> public ResultSmsList GetSmsList(int userId,string taskName,DateTime startTime,DateTime endTime, int pageSize, int pageIndex) { var rs = new ResultSmsList { State = false, Value = -1, Desc = "数据操作层初始化" }; if (userId <= 0) { rs.Failed(-101, "userId无效"); return rs; } _desc = "获取短信主记录列表"; _procName = "UP_SMS_GetSmsList"; _methodName = MethodBase.GetCurrentMethod().Name; _log = new LogBuilder { Method = string.Format("类[{0}]方法[{1}]", ClassName, _methodName), Desc = _desc, Database = _databaseName, StroreProcedure = _procName }; _log.Append("userId", userId); try { var parameters = new[] { _smsDatabase.MakeInParam("@userId", SqlDbType.Int, 4, userId), _smsDatabase.MakeInParam("@TaskName", SqlDbType.VarChar, taskName), _smsDatabase.MakeInParam("@StartTime", SqlDbType.DateTime, startTime), _smsDatabase.MakeInParam("@EndTime", SqlDbType.DateTime, endTime), _smsDatabase.MakeInParam("@PageIndex", SqlDbType.Int, 4, pageIndex), _smsDatabase.MakeInParam("@PageSize", SqlDbType.Int, 4, pageSize), _smsDatabase.MakeOutParam("@Total", SqlDbType.Int) }; _smsDatabase.ExecuteProc(_procName, parameters, out _dr); if (_dr == null) { rs.Failed(-2, "todo"); return rs; } while (_dr.Read()) { if (rs.SmsList == null) { rs.SmsList = new List<SmsInfo>(); } var obj = new SmsInfo(); obj.UserID = userId; obj.TaskName = SqlComponents.ReaderGetString(_dr["TaskName"]); obj.MsgID = SqlComponents.ReaderGetString(_dr["MsgID"]); obj.Sender = SqlComponents.ReaderGetString(_dr["Sender"]); obj.Message= SqlComponents.ReaderGetString(_dr["Message"]); obj.InputType = (InputType)SqlComponents.ReaderGetInt32(_dr["InputType"]); obj.SendWay = (SendWay)SqlComponents.ReaderGetInt32(_dr["SendWay"]); obj.Priority= (SmsPriority)SqlComponents.ReaderGetByte(_dr["Priority"]); obj.Status = (BatchState)SqlComponents.ReaderGetByte(_dr["Status"]); obj.SmsType=(SmsType)SqlComponents.ReaderGetByte(_dr["SmsType"]); obj.SubmitTime = SqlComponents.ReaderGetDateTime(_dr["SubmitTime"]); obj.ApprovalTime = SqlComponents.ReaderGetDateTime(_dr["ApprovalTime"]); obj.CompletedTime = SqlComponents.ReaderGetDateTime(_dr["CompletedTime"]); obj.SuccessCount = SqlComponents.ReaderGetInt32(_dr["SuccessCount"]); obj.FailCount = SqlComponents.ReaderGetInt32(_dr["FailCount"]); obj.Amount = SqlComponents.ReaderGetLong(_dr["Amount"]); obj.SendCount = SqlComponents.ReaderGetInt32(_dr["SendCount"]); rs.SmsList.Add(obj); } _dr.Close(); rs.Total = SqlComponents.ReaderGetInt32(parameters[6].Value); } catch (Exception ex) { rs.Failed(-1, "todo"); _log.Exception = string.Format("{0},发生异常:{1}", _desc, ex.Message); _log.Error(); return rs; } finally { _smsDatabase.Close();//仅显式关闭链接,不做其它操作 } rs.Success(); return rs; }
public ResultSmsInfo GetSmsInfo(string MsgId,int UserID) { var rs = new ResultSmsInfo { State = false, Value = -1, Desc = "数据操作层初始化" }; if (string.IsNullOrEmpty(MsgId)) { rs.Failed(-101, "MsgIdi不能为空"); return rs; } _desc = "获取短信主记录列表"; _procName = "UP_SMS_GetSmsInfo"; _methodName = MethodBase.GetCurrentMethod().Name; _log = new LogBuilder { Method = string.Format("类[{0}]方法[{1}]", ClassName, _methodName), Desc = _desc, Database = _databaseName, StroreProcedure = _procName }; _log.Append("msgId", MsgId); try { var parameters = new[] { _smsDatabase.MakeInParam("@MsgID", SqlDbType.VarChar,MsgId), _smsDatabase.MakeInParam("@UserID", SqlDbType.Int, 4, UserID) }; _smsDatabase.ExecuteProc(_procName, parameters, out _dr); if (_dr == null) { rs.Failed(-2, "todo"); return rs; } if (_dr.Read()) { var obj = new SmsInfo(); obj.TaskName = SqlComponents.ReaderGetString(_dr["TaskName"]); obj.MsgID = SqlComponents.ReaderGetString(_dr["MsgID"]); obj.Sender = SqlComponents.ReaderGetString(_dr["Sender"]); obj.Message = SqlComponents.ReaderGetString(_dr["Message"]); obj.InputType = (InputType)SqlComponents.ReaderGetInt32(_dr["InputType"]); obj.SendWay = (SendWay)SqlComponents.ReaderGetInt32(_dr["SendWay"]); obj.Priority = (SmsPriority)SqlComponents.ReaderGetByte(_dr["Priority"]); obj.Status = (BatchState)SqlComponents.ReaderGetByte(_dr["Status"]); obj.SmsType = (SmsType)SqlComponents.ReaderGetByte(_dr["SmsType"]); obj.SubmitTime = SqlComponents.ReaderGetDateTime(_dr["SubmitTime"]); obj.ApprovalTime = SqlComponents.ReaderGetDateTime(_dr["ApprovalTime"]); obj.CompletedTime = SqlComponents.ReaderGetDateTime(_dr["CompletedTime"]); obj.SuccessCount = SqlComponents.ReaderGetInt32(_dr["SuccessCount"]); obj.FailCount = SqlComponents.ReaderGetInt32(_dr["FailCount"]); obj.Amount = SqlComponents.ReaderGetLong(_dr["Amount"]); rs.SmsInfo = obj; } _dr.Close(); } catch (Exception ex) { rs.Failed(-1, "todo"); _log.Exception = string.Format("{0},发生异常:{1}", _desc, ex.Message); _log.Error(); return rs; } finally { _smsDatabase.Close();//仅显式关闭链接,不做其它操作 } rs.Success(); return rs; }
public string Send_MI(SmsInfo model) { return(this.GetMessage("小米", model)); }
public string Send_LX(SmsInfo model) { return(this.GetMessage("联想", model)); }
private string GetMessage(string name, SmsInfo model) { return($"[{IPUtils.GetLocalIp()}]" + $"通过【{name}】短信接口向【{model.PhoneNum}】发送短信【{model.Msg}】"); }