Files
lserp_cs_6.0/其他程序/SendSms/SendSms/Form1.cs
T
cyf ab56a9bcf7 基线 SVN r240
SVN-Revision: r240
2025-02-06 06:46:06 +00:00

424 lines
15 KiB
C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lskj.Core;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Exceptions;
using System.Runtime.InteropServices;
using Lskj.Data;
using System.Data.SqlClient;
using Lskj.Util;
using System.IO;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using Lskj.Control;
using Lskj.Business.Impl;
namespace SendSms
{
public partial class Form1 : Form
{
/// <summary>
/// 阿里云账号
/// </summary>
string SMSKey = "LTAI4FoHMd53f81TcwirQFjX";
/// <summary>
/// 阿里云密码
/// </summary>
string SMSSecret = "eU13qa5jgwnY4LfVvRLe0YvCVJCLz1";
/// <summary>
/// 默认签名
/// </summary>
string SignName = "朗速科技";
/// <summary>
/// ini文件内段落名
/// </summary>
string company = "短信发送工具";
/// <summary>
/// 初始时间间隔
/// </summary>
int second = 30;
/// <summary>
/// 是否在运行
/// </summary>
bool isExecing = false;
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 初始化
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_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);
}
/// <summary>
/// 时间间隔TextBox失去焦点事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
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());
}
/// <summary>
/// 开始发送按钮事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
if (ConnectServer())
{
BaseImpl.HasExistsColumn("P_SystemTab", "SMSKey", "VARCHAR(100)");
BaseImpl.HasExistsColumn("P_SystemTab", "SMSSecret", "VARCHAR(100)");
BaseImpl.HasExistsColumn("P_SystemTab", "SignName", "VARCHAR(100)");
DataRow SystemTab = BaseImpl.GetSystemTab();
if (!string.IsNullOrWhiteSpace(SystemTab["SMSKey"] + "") && !string.IsNullOrWhiteSpace(SystemTab["SMSSecret"] + "") && !string.IsNullOrWhiteSpace(SystemTab["SignName"] + ""))
{
this.SMSKey = SystemTab["SMSKey"] + "";
this.SMSSecret = SystemTab["SMSSecret"] + "";
this.SignName = SystemTab["SignName"] + "";
}
timer1.Interval = 10;
timer1.Enabled = true;
}
}
/// <summary>
/// 发送事件
/// </summary>
public void BeginSend()
{
if (!this.isExecing)
{
try
{
this.textBox1.Invoke(new Action(() =>
{
this.textBox1.Text = "";
}));
ShowMsg("------------开始发送短信(" + DateTime.Now + ")--------------\r\n\r\n");
this.isExecing = true;
string sql = "select id,templeteId, tempContent, sendobject, tempparam1,tempparam2,tempparam3,tempparam4,tempparam5,tempparam6,tempparam7,tempparam8,tempparam9,tempparam10 from P_SystemSMSTempleteTab where issend = 0 order by sendobject";
DataTable dt = SqlHelper.ExecuteDataTable(sql);
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
string json = FinalJson(dr);
DataRow drReturn = SendSms(dr["templeteId"].ToString(), dr["sendobject"].ToString(), json);
if (drReturn["Code"].ToString() == "OK")
{
string sqlReturn = string.Format("update P_SystemSMSTempleteTab set issend = 2,finishdate = GETDATE(),SendResult = '成功' where id = {0}", dr["id"]);
SqlHelper.ExecuteNonQuery(sqlReturn);
string str = "手机号" + dr["sendobject"].ToString() + "短信发送->成功\r\n";
ShowMsg(str);
}
else
{
string sqlReturn = string.Format("update P_SystemSMSTempleteTab set SendResult = {1},issend=1 where id = {0}", dr["id"], drReturn["Code"].ToString());
SqlHelper.ExecuteNonQuery(sqlReturn);
string str = "手机号" + dr["sendobject"].ToString() + "短信发送->失败" + "(" + drReturn["Code"].ToString() + ")" + "\r\n";
ShowMsg(str);
}
}
ShowMsg("\r\n\r\n------------本次短信发送完成(" + DateTime.Now + ")--------------");
}
else
{
ShowMsg("未检测到需要发送短信的数据");
ShowMsg("\r\n\r\n------------本次短信发送完成(" + DateTime.Now + ")--------------");
}
}
catch (Exception)
{
}
finally
{
string log = textBox1.Text.ToString();
LogUtil.WriteLocalLog(log);
this.isExecing = false;
}
}
}
/// <summary>
/// 发送短信返回DataRow
/// </summary>
/// <param name="templateCode"></param>
/// <param name="phoneNumber"></param>
/// <param name="json"></param>
/// <returns></returns>
public DataRow SendSms(string templateCode, string phoneNumber, string json)
{
DataTable pDataTable = new DataTable();
DataRow drReturn = pDataTable.NewRow();
IClientProfile profile = DefaultProfile.GetProfile("cn-chengdu", SMSKey, SMSSecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
CommonRequest request = new CommonRequest();
request.Method = MethodType.POST;
request.Domain = "dysmsapi.aliyuncs.com";
request.Version = "2017-05-25";
request.Action = "SendSms";
// request.Protocol = ProtocolType.HTTP;
request.AddQueryParameters("PhoneNumbers", phoneNumber);
request.AddQueryParameters("SignName", SignName);
request.AddQueryParameters("TemplateCode", templateCode);
request.AddQueryParameters("TemplateParam", json);
try
{
CommonResponse response = client.GetCommonResponse(request);
string jsonToDr = System.Text.Encoding.Default.GetString(response.HttpResponse.Content);
jsonToDr = "[" + jsonToDr + "]";
drReturn = JsonUtil.ToDataRow(jsonToDr);
}
catch (Aliyun.Acs.Core.Exceptions.ServerException e)
{
Console.WriteLine(e);
}
catch (ClientException e)
{
Console.WriteLine(e);
}
return drReturn;
}
/// <summary>
/// 变量处理成Json
/// </summary>
/// <param name="dr"></param>
/// <returns></returns>
public string FinalJson(DataRow dr)
{
string content = dr["tempContent"].ToString();
content = content.Replace("$", "");
StringCollection resultList = new StringCollection();
try
{
Regex regex = new Regex("{([^{])+}");
MatchCollection mcs = regex.Matches(content);
foreach (Match item in mcs)
{
if (resultList.IndexOf(item.Value) == -1)
{
string field = item.Value.Replace("{", "").Replace("}", "");
resultList.Add(field);
}
}
}
catch (ArgumentException ex)
{
// Syntax error in the regular expression
}
DataTable tblDatas = new DataTable();
DataColumn dc = null;
foreach (string str in resultList)
{
dc = tblDatas.Columns.Add(str, Type.GetType("System.String"));
}
StringCollection allcontent = new StringCollection();
for (int i = 4; i < 14; i++)
{
allcontent.Add(dr[i].ToString());
}
DataRow newRow;
newRow = tblDatas.NewRow();
for (int i = 0; i < tblDatas.Columns.Count; i++)
{
newRow[i] = allcontent[i];
}
string json = JsonUtil.ToJsonObject(newRow);
json = json.Substring(1, json.Length - 2);
return json;
}
/// <summary>
/// timer事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Enabled = false;
if (timer1.Interval == 10)
{
timer1.Interval = second * 1000;
}
BeginSend();
timer1.Enabled = true;
}
/// <summary>
/// 时间间隔TextBox按键判断
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txtTimeInterval_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8)
{
e.Handled = true;
}
}
/// <summary>
/// 显示消息
/// </summary>
private void ShowMsg(string msg)
{
this.textBox1.Invoke(new Action(() =>
{
this.textBox1.AppendText(msg);
this.textBox1.ScrollToCaret();
}));
}
#region 连接服务器
/// <summary>
/// <para>说明:连接服务器</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-09 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <param name="isSave">if set to <c>true</c> [is save].</param>
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;
}
/// <summary>
/// <para>说明:创建数据库连接</para>
/// <para>创建人:龚宇超</para>
/// <para>创建日期:2017-08-07 </para>
/// <para>修改人:</para>
/// <para>修改日期:</para>
/// <para>修改备注:</para>
/// <para>版本:1.0</para>
/// </summary>
/// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
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;
}
/// <summary>
/// 获取连接服务器的字符串
/// </summary>
/// <returns></returns>
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
}
}