using Lskj.Control; using Lskj.Core; using Lskj.Data; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Windows.Forms; using static Lskj.SmsSending2.NewEmp; namespace Lskj.SmsSending2 { public partial class FrmMain : Form { public FrmMain() { InitializeComponent(); } /// /// ini文件内段落名 /// public string company = "短信发送工具"; /// /// 初始时间间隔 /// public int second = 30; /// /// 账号 /// public string SMSID; /// /// 密码 /// public string SMSPwd; /// /// post接口地址 /// public string postUrl = "https://sdk3.028lk.com:9988/BatchSend2.aspx"; public System.Timers.Timer timer1 = new System.Timers.Timer(); private void FrmMain_Load(object sender, EventArgs e) { txtSeverId.Text = IniUtil.IniReadValue(company, "serverName"); txtDataBase.Text = IniUtil.IniReadValue(company, "dbName"); txtName.Text = IniUtil.IniReadValue(company, "user"); txtPassword.Text = IniUtil.IniReadValue(company, "password"); txtTimeInterval.Text = IniUtil.IniReadValue(company, "interval"); if (string.IsNullOrEmpty(txtTimeInterval.Text)) txtTimeInterval.Text = "30"; txtTimeInterval.LostFocus += new EventHandler(txtTimeInterval_LostFocus); this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Tick); } /// /// 时间间隔TextBox失去焦点事件 /// /// /// private void txtTimeInterval_LostFocus(object sender, EventArgs e) { string checkStr = txtTimeInterval.Text.ToString(); if (string.IsNullOrEmpty(checkStr)) txtTimeInterval.Text = "30"; int check = Convert.ToInt32(txtTimeInterval.Text.ToString()); if (check < 30) { txtTimeInterval.Text = "30"; } second = Convert.ToInt32(txtTimeInterval.Text.ToString()); IniUtil.IniWriteValue(company, "interval", txtTimeInterval.Text.ToString()); } //点击发送 private void btnBegin_Click(object sender, EventArgs e) { try { if (ConnectServer()) { //检测并创建表 UpdateMsgTab(); SMSID = IniUtil.IniReadValue(company, "SMSID"); SMSPwd = IniUtil.IniReadValue(company, "SMSPwd"); if (string.IsNullOrEmpty(SMSID) || string.IsNullOrEmpty(SMSPwd)) { RefreshLogUIThread("短信消息发送错误:未配置账号信息\r\n"); return; } SendData(); timer1.Interval = second * 1000; timer1.Enabled = true; this.timer1.Start(); } } catch (Exception ex) { RefreshLogUIThread(DateTime.Now + string.Format("失败.原因:{0}.\r\n", ex.Message)); } } //发送数据 private void SendData() { int success = 0, failed = 0, tot = 0; try { DataTable dataTable = SqlHelper.ExecuteDataTable("select id, phonestr as Mobile, msgstr as Content from lk_apidatatab where isnull(sendFlag, '') = 0 and isnull(phonestr, '') <> ''"); tot = dataTable.Rows.Count; RefreshLogUIThread(string.Format("开始新一轮短信消息推送,本次将推送{0}条消息=========\r\n", tot)); DataTable dtcopy = dataTable.Copy(); //dtcopy.Columns["phonestr"].ColumnName = "Mobile"; //dtcopy.Columns["msgstr"].ColumnName = "Content"; //if (!dataTable.Columns.Contains("Cell")) dtcopy.Columns.Add("Cell"); //if (!dataTable.Columns.Contains("SendTime ")) dtcopy.Columns.Add("SendTime "); dtcopy.Columns.Remove("id"); for (int i = 0; i < dataTable.Rows.Count; i++) { //SMSID = "222"; //string jsonObj = JsonUtil.ToJsonObject(dtcopy.Rows[i]); //string deljson = jsonObj.Substring(1, jsonObj.Length - 2); //deljson = deljson.Insert(1, string.Format("\"CorpID\":\"{0}\",\"Pwd\":\"{1}\",", SMSID, SMSPwd)); //deljson = deljson.Insert(deljson.Length-1, ",\"Cell\"=, \"SendTime\"="); //deljson="{ \"Mobile\":\"15008278310\",\"Content\":\"测试数据\",\"Cell\":\"1\",\"SendTime \":\"\",\"CorpID\":\"CDJT001634\",\"Pwd\":\"426F7A\"}"; //ResponseMode mode = NewEmp.PostMethodToObj(postUrl, deljson); HttpTools.setting("application/x-www-form-urlencoded;charset=utf-8", null, null); Dictionary dataDic = new Dictionary(); dataDic.Add("CorpID", SMSID); dataDic.Add("Pwd", SMSPwd); dataDic.Add("Mobile", dataTable.Rows[i]["Mobile"]+""); dataDic.Add("Content", dataTable.Rows[i]["Content"]+""); dataDic.Add("Cell", ""); dataDic.Add("SendTime", ""); string mode = HttpTools.Post(postUrl, "", dataDic, HttpTools.Method.POST); //string mode = NewEmp.PostMethodToObj(postUrl, deljson); //string url = string.Format("https://sdk3.028lk.com:9988/BatchSend2.aspx?CorpID={0}&Pwd={1}&Mobile={2}&Content={3}&Cell=&SendTime=", SMSID, SMSPwd, dataTable.Rows[i]["Mobile"], dataTable.Rows[i]["Content"]); //string mode = NewEmp.GetUrl(url); if (!string.IsNullOrWhiteSpace(mode)) { if (Convert.ToInt32(mode) > 0) success++; string sql = string.Format(@"update lk_apidatatab set sendFlag=1,sendResult='{0}' where id='{1}'", mode, dataTable.Rows[i]["id"]); SqlHelper.ExecuteNonQuery(sql); } } } catch (Exception ex) { RefreshLogUIThread(DateTime.Now + string.Format("失败.原因:{0}.\r\n", ex.Message)); } finally { if (tot > 0) RefreshLogUIThread(string.Format("本轮短信消息发送{0}条消息,成功{1}条,失败{2}条=========", tot, success, tot - success)); } } /// /// timer事件 /// /// /// private void timer1_Tick(object sender, EventArgs e) { timer1.Enabled = false; //txtLog.Text = null; SendData(); timer1.Enabled = true; } //判断是否有表,没有则创建 private void UpdateMsgTab() { string sql = string.Format(@"if not exists (select 1 from dbo.sysobjects where id = object_id(N'[dbo].[{0}]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) exec('CREATE TABLE [dbo].[{0}]( [id] [int] primary key IDENTITY(1,1) NOT NULL, [phonestr] [varchar](8000) NULL, [msgstr] [varchar](8000) NULL, [createdate] [datetime] NULL default getdate(), [cltig] [int] NULL, [cldate] [datetime] NULL default 0, [sendFlag] int not null default 0, [sendResult] varchar(1000) null ) '); ", "lk_apidatatab"); SqlHelper.ExecuteNonQuery(sql); } /// /// 后台线程刷新数据 /// /// public void RefreshLogUIThread(string msg) { if (this.IsHandleCreated) { Invoke((EventHandler)delegate { txtLog.Text += msg; txtLog.Select(txtLog.TextLength, 0); txtLog.ScrollToCaret(); }); } } #region 连接服务器 /// /// 说明:连接服务器 /// 创建人:龚宇超 /// 创建日期:2017-08-09 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// if set to true [is save]. public bool ConnectServer(bool isSave = false) { string serverName = this.txtSeverId.Text.Trim(); string dbName = this.txtDataBase.Text.Trim(); string user = this.txtName.Text.Trim(); string password = this.txtPassword.Text.Trim(); if (string.IsNullOrWhiteSpace(serverName)) { MessageUtil.Show(ResourceKeys.ServerNameIsNull); return false; } if (string.IsNullOrWhiteSpace(dbName)) { MessageUtil.Show(ResourceKeys.ServerDBIsNull); return false; } if (string.IsNullOrWhiteSpace(user)) { MessageUtil.Show("请重新输入用户名"); return false; } // 测试数据库连接 try { if (CreateConnection()) { if (isSave) { } else { IniUtil.IniWriteValue(company, "serverName", serverName); IniUtil.IniWriteValue(company, "dbName", dbName); IniUtil.IniWriteValue(company, "user", user); IniUtil.IniWriteValue(company, "password", password); return true; } } else { MessageUtil.Show(ResourceKeys.ConnectFault); return false; } } catch (Exception) { MessageUtil.Show(ResourceKeys.ConnectFault); } return true; } /// /// 说明:创建数据库连接 /// 创建人:龚宇超 /// 创建日期:2017-08-07 /// 修改人: /// 修改日期: /// 修改备注: /// 版本:1.0 /// /// true if XXXX, false otherwise. public bool CreateConnection() { string connStr = GetConnection(); if (SqlHelper._connection != null) { try { SqlHelper._connection.Close(); SqlHelper._connection.Dispose(); } catch (Exception) { } SqlHelper._connection = null; } try { SqlHelper._connection = new SqlConnection(connStr); SqlHelper._connection.Open(); return true; } catch (Exception ex) { // LogHelper.Instance.WriteLog(ex.Message); } return false; } /// /// 获取连接服务器的字符串 /// /// public string GetConnection() { return string.Format("Server={0};Database={1};Persist Security Info=True;User ID={2};Password={3};Connection Timeout=5;MultipleActiveResultSets=true", txtSeverId.Text.ToString(), txtDataBase.Text.ToString(), txtName.Text.ToString(), txtPassword.Text.ToString()); } #endregion } public static class HttpTools { public static CookieContainer cookie = new CookieContainer(); // 用于记录访问网页时cookie数据 public static CookieCollection cookieCollection; private static string ContentType = string.Empty;// "application/x-www-form-urlencoded"; private static string Accept = string.Empty;//"text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; private static string UserAgent = string.Empty;//"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14"; public enum Method { POST = 0, GET = 1 } public static void setting(string contentType, string accept, string userAgent) { ContentType = contentType; Accept = accept; UserAgent = userAgent; } /// /// post数据到指定的网址,获取cookie数据,和返回页 /// public static string Post(string url, string postData, Dictionary dic, Method method) { return Post(url, postData, dic, method, out cookieCollection); } /// /// post数据到指定的网址,获取cookie数据,和返回页 /// public static string Post(string url, string postData, Dictionary dic, Method method, out CookieCollection cookieCollection) { HttpWebResponse httpWebResponse = null; try { HttpWebRequest httpWebRequest; httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(url); httpWebRequest.CookieContainer = cookie; httpWebRequest.ContentType = ContentType; httpWebRequest.Referer = url; httpWebRequest.Accept = Accept; httpWebRequest.UserAgent = UserAgent; httpWebRequest.Method = method == Method.POST ? "POST" : "GET"; byte[] byteRequest = null; if (!string.IsNullOrEmpty(postData)) { byteRequest = Encoding.Default.GetBytes(postData); httpWebRequest.ContentLength = byteRequest.Length; } else { StringBuilder builder = new StringBuilder(); int i = 0; foreach (var item in dic) { if (i > 0) builder.Append("&"); builder.AppendFormat("{0}={1}", item.Key, item.Value); i++; } byteRequest = Encoding.UTF8.GetBytes(builder.ToString()); httpWebRequest.ContentLength = byteRequest.Length; } Stream stream = httpWebRequest.GetRequestStream(); stream.Write(byteRequest, 0, byteRequest.Length); stream.Close(); httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); Stream responseStream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8); string result = streamReader.ReadToEnd(); streamReader.Close(); responseStream.Close(); cookieCollection = cookie.GetCookies(new Uri(url)); return result; } catch (Exception ex) { cookieCollection = null; return "错误,请求失败"; } } } }