1.服务初始化
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using log4net;
namespace EohiQuartzService
{
//窗体控制->委托
public delegate void ServiceHeplerHandler(string[] args); //开始
public delegate void ServiceHeplerStopHandler(); //停止
public delegate void ServiceHeplerShowTaskHandler(); //显示远程控制页面
public partial class Service1 : ServiceBase
{
//日志
private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public bool ServiceRunIsTrue { get; set; } //服务运行状态
public ServiceHeplerHandler ServiceStratHandler;
public ServiceHeplerStopHandler ServiceStopHandler;
public ServiceHeplerShowTaskHandler ServiceShowTaskHandler;
public Service1()
{
QuarztHelper.Start();
ServiceRunIsTrue = QuarztHelper.ServiceRunIsTrue;
ServiceStratHandler += OnStart;
ServiceStopHandler += OnStop;
ServiceShowTaskHandler += ShowTaskManagers;
InitializeComponent();
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "服务初始化;");
log.Info(start);
}
protected override void OnStart(string[] args)
{
QuarztHelper.Start();
ServiceRunIsTrue = QuarztHelper.ServiceRunIsTrue;
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "服务启动,ONSTART");
log.Info(start);
}
protected override void OnStop()
{
QuarztHelper.Stop();
ServiceRunIsTrue = QuarztHelper.ServiceRunIsTrue;
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "服务停止,ONSTOP");
log.Info(start);
}
protected void ShowTaskManagers()
{
System.Diagnostics.Process.Start("http://localhost:39897/CrystalQuartzPanel.axd?menucode=008");
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "跳转远程管理页面,CrystalQuartzPanel.acd");
log.Info(start);
}
}
}
2.Quartz初始化
using EohiQuartzService.Quarzt;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using Quartz;
using log4net;
namespace EohiQuartzService
{
public class QuarztHelper
{
private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static Quartz.IScheduler scheduler = null;
public static bool ServiceRunIsTrue { get; set; }
public static void Stop()
{
try
{
if (scheduler != null)
{
//if (scheduler.IsStarted)
//{
scheduler.Shutdown();
bool b = scheduler.IsStarted;
ServiceRunIsTrue = false;
//}
}
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "停止Quartz服务成功!;");
log.Info(start);
}
catch (Exception exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "停止Quartz服务失败!;"+exp.Message);
log.Info(start);
Console.WriteLine(exp.Message);
//throw;
}
}
public static void Start()
{
try
{
if (scheduler != null)
{
if (!scheduler.IsStarted)
{
scheduler.Start();
ServiceRunIsTrue = true;
}
}
else
{
#region 测试.
var properties = new NameValueCollection();
//properties["quartz.scheduler.instanceName"] = "RemoteServerSchedulerClient";
设置线程池
//properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
//properties["quartz.threadPool.threadCount"] = "5";
//properties["quartz.threadPool.threadPriority"] = "Normal";
// 远程输出配置
properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
properties["quartz.scheduler.exporter.port"] = "555";
properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
properties["quartz.scheduler.exporter.channelType"] = "tcp";
var schedulerFactory = new Quartz.Impl.StdSchedulerFactory(properties);
scheduler = schedulerFactory.GetScheduler();
scheduler.Start();
string startm = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "初始化Quartz服务开始运行!;" );
log.Info(startm);
}
#endregion
#region 原
//var properties = new NameValueCollection();
properties["quartz.scheduler.instanceName"] = "RemoteServerSchedulerClient";
properties["quartz.scheduler.instanceName"] = "RemoteServerSchedulerClient";
// 设置线程池
properties["quartz.threadPool.type"] = "Quartz.Simpl.SimpleThreadPool, Quartz";
properties["quartz.threadPool.threadCount"] = "5";
properties["quartz.threadPool.threadPriority"] = "Normal";
远程输出配置
//properties["quartz.scheduler.exporter.type"] = "Quartz.Simpl.RemotingSchedulerExporter, Quartz";
//properties["quartz.scheduler.exporter.port"] = "555";
//properties["quartz.scheduler.exporter.bindName"] = "QuartzScheduler";
//properties["quartz.scheduler.exporter.channelType"] = "tcp";
scheduler = StdSchedulerFactory.GetDefaultScheduler(properties);
//var schedulerFactory = new StdSchedulerFactory(properties);
//scheduler = schedulerFactory.GetScheduler();
//scheduler.Start();
#endregion
//
List<Model_QuartzNetItem> itemList = QuartzNetService.GetList();
{
foreach (Model_QuartzNetItem itm in itemList)
{
if (itm.Quartzstatus != "启动")
continue;
if (itm.Jobtype.ToLower() == "http")
{
HttpJob_Create(itm);
}
}
}
ServiceRunIsTrue = true;
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "启动Quartz服务成功总有"+itemList.Count+"条任务");
log.Info(start);
}
catch (Exception exp)
{
//初始化log4net
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "启动Quartz服务失败:" + exp.Message);
log.Info(start);
ServiceRunIsTrue = false;
Console.WriteLine(exp.Message);
//throw;
}
}
private static void HttpJob_Create(Model_QuartzNetItem itm)
{
try
{
Quartz.IJobDetail job = Quartz.JobBuilder.Create<HttpRequestJob>()
.WithIdentity("job-" + itm.Id.ToString() )
.WithDescription(itm.Quartzname+"|"+itm.Quartznote)
.UsingJobData("httpurl", itm.Jobpars)
.Build();
//ITrigger trigger = TriggerBuilder.Create()
// .WithIdentity("trigger" + itm.Id.ToString(), "triggergroup" + itm.Id.ToString())
// .WithSimpleSchedule(t =>
// t.WithIntervalInSeconds(5)
// .RepeatForever())
// .Build();
Quartz.ITrigger trigger = Quartz.TriggerBuilder.Create()
.WithIdentity("trigger-" + itm.Id.ToString())
.StartNow()
.WithCronSchedule(itm.Crontrigger) //时间表达式,5秒一次
.Build();
//
scheduler.ScheduleJob(job, trigger);
}
catch (Exception exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "HttpJob_Create方法 Quartz请求任务失败:" + exp.Message);
log.Info(start);
//throw;
}
}
private static void HttpJob_Remove(Model_QuartzNetItem itm)
{
try
{
string jobid = "job-" + itm.Id.ToString();
string triggerid = "trigger-" + itm.Id.ToString();
JobKey jobKey = new JobKey(jobid);
TriggerKey triggerKey = new TriggerKey(triggerid);
scheduler.PauseJob(jobKey);// 停止触发器
scheduler.UnscheduleJob(triggerKey);// 移除触发器
scheduler.DeleteJob(jobKey);// 删除任务
}
catch (Exception exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "HttpJob_Remove方法 删除Quartz请求任务失败:" + exp.Message);
log.Info(start);
//throw;
}
}
public static void JoinJob(int jobid)
{
try
{
Model_QuartzNetItem itm = QuartzNetService.GetById(jobid);
if (itm == null)
return;
if (itm.Jobtype.ToLower() == "http")
{
if (itm.Quartzstatus == "停止")
{
//移除
HttpJob_Remove(itm);
}
else
{
HttpJob_Create(itm);
}
}
}
catch (Exception exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "JoinJob方法 JoinJobQuartz请求任务失败:" + exp.Message);
log.Info(start);
//throw;
}
}
}
}
2.1 [DisallowConcurrentExecution] //禁止并发,一般当任务的执行时间大于定时时间时防止并发,
using Quartz;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace EohiQuartzService
{
[DisallowConcurrentExecution] //禁止并发
public class HttpRequestJob : IJob
{
private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//public string httpurl = "http://www.baidu.com";
public void Execute(IJobExecutionContext context)
{
/*
var reportDirectory = string.Format("~/reports/{0}/", DateTime.Now.ToString("yyyy-MM"));
reportDirectory = System.Web.Hosting.HostingEnvironment.MapPath(reportDirectory);
if (!Directory.Exists(reportDirectory))
{
Directory.CreateDirectory(reportDirectory);
}
var dailyReportFullPath = string.Format("{0}report_{1}.log", reportDirectory, DateTime.Now.Day);
var logContent = string.Format("{0}==>>{1}{2}", DateTime.Now, "create new log.", Environment.NewLine);
File.AppendAllText(dailyReportFullPath, logContent);
*/
try
{
JobDataMap dataMap = context.JobDetail.JobDataMap;
string httpurl = dataMap.GetString("httpurl");
System.Net.HttpWebRequest myHttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(httpurl);
System.Net.HttpWebResponse myHttpWebResponse = (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse();
//System.IO.Stream receiveStream = myHttpWebResponse.GetResponseStream();//得到回写的字节流
}
catch (Exception exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), " HttpRequestJob+ Execute:" + exp.Message);
log.Info(start);
//throw;
}
}
}
}
3.
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace EohiQuartzService.Quarzt
{
// 数据库接口类
public class DBHelper
{
private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//构造函数
public DBHelper()
{
}
public static string ReReadConnectionString()
{
return Common.DBHelper.SqlConn.GetConnectionString();
}
/// <summary>
/// 返回查询语句行数字,必须包含 rows 字段
/// </summary>
/// <param name="sqlString">被执行的SQL语句</param>
/// <returns>返回值</returns>
public static int DBSelectRows(string sqlString)
{
int rows = -1;
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
SqlCommand cmd = new SqlCommand(sqlString, myConn);
try
{
myConn.Open();
SqlDataReader datareader = null;
datareader = cmd.ExecuteReader();
while (datareader.Read())
{
rows = Convert.ToInt32(datareader["rows"].ToString());
}
datareader.Close();
}
catch (SqlException ex)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "DBSelectRows"+ex.Message);
log.Info(start);
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return -1;
}
finally
{
cmd.Dispose();
myConn.Close();
myConn.Dispose();
}
return rows;
}
#region ExecuteScalar 执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行
public static object ExecuteScalar(string sqlString, SqlParameter[] pars)
{
return ExecuteScalar(ReReadConnectionString(), sqlString, pars);
}
/// <summary>
/// 执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行
/// 如果为NULL 则返回 -1
/// </summary>
/// <param name="sqlString">被执行的SQL语句</param>
/// <returns>返回值</returns>
public static object ExecuteScalar(string connString, string sqlString, SqlParameter[] pars)
{
SqlConnection myConn = new SqlConnection(connString);
SqlCommand cmd = new SqlCommand(sqlString, myConn);
try
{
myConn.Open();
cmd.Parameters.AddRange(pars);
object obj = cmd.ExecuteScalar();
return obj;
}
catch (SqlException exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "ExecuteScalar" + exp.Message);
log.Info(start);
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return -1;
throw exp;
}
finally
{
cmd.Dispose();
myConn.Close();
myConn.Dispose();
}
}
#endregion
#region ExecuteNonQuery 执行SQL语句,返回执行语句所影响的行数
/// <summary>
/// 执行SQL语句,返回执行语句所影响的行数
/// </summary>
/// <param name="StrSql">被执行的SQL语句</param>
/// <param name="pars">参数</param>
/// <returns>返回首影响的行数</returns>
public static int ExecuteNonQuery(string StrSql, SqlParameter[] pars)
{
return ExecuteNonQuery(ReReadConnectionString(), StrSql, pars);
}
/// <summary>
/// 执行SQL语句,返回执行语句所影响的行数
/// </summary>
/// <param name="StrSql">被执行的SQL语句</param>
/// <param name="pars">参数</param>
/// <returns>返回首影响的行数</returns>
public static int ExecuteNonQuery(string connString, string StrSql, SqlParameter[] pars)
{
int rows = -1;
SqlConnection myConn = new SqlConnection(connString);
try
{
myConn.Open();
SqlCommand com = new SqlCommand(StrSql, myConn);
com.Parameters.AddRange(pars);
rows = com.ExecuteNonQuery();
}
catch (SqlException exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "ExecuteNonQuery" + exp.Message);
log.Info(start);
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return -1;
throw exp;
}
finally
{
myConn.Close();
myConn.Dispose();
}
return rows;
}
#endregion
#region SqlDataAdapter 返回执行SQL查询语句返回的数据表
public static DataTable getDataTable(string sqlString, SqlParameter[] pars)
{
return getDataTable(ReReadConnectionString(), sqlString, pars);
}
public static DataTable getDataTable(string connString, string sqlString, SqlParameter[] pars)
{
DataTable tb = new DataTable();
SqlConnection myConn = new SqlConnection(connString);
SqlCommand MyCmd = new SqlCommand(sqlString, myConn);
try
{
MyCmd.Parameters.AddRange(pars);
SqlDataAdapter dataAdapter = new SqlDataAdapter(MyCmd);
dataAdapter.Fill(tb);
}
catch (SqlException exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "getDataTable" + exp.Message);
log.Info(start);
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return tb;
throw exp;
}
finally
{
myConn.Close();
myConn.Dispose();
}
return tb;
}
#endregion
#region ExecuteScalar 执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行
/// <summary>
/// 执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行
/// 如果为NULL 则返回 -1
/// </summary>
/// <param name="sqlString">被执行的SQL语句</param>
/// <returns>返回值</returns>
public static int DBExecuteScalar(string sqlString)
{
//
int rows = -1;
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
SqlCommand cmd = new SqlCommand(sqlString, myConn);
try
{
myConn.Open();
object obj = cmd.ExecuteScalar();
if (obj == System.DBNull.Value)
rows = -1;
else
rows = Convert.ToInt32(obj);
}
catch (SqlException exp)
{
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return -1;
throw exp;
}
finally
{
cmd.Dispose();
myConn.Close();
myConn.Dispose();
}
return rows;
}
/// <summary>
/// 执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行
/// 如果结果为空 则返回 string.Empty
/// </summary>
/// <param name="sqlString"></param>
/// <returns></returns>
public static String DBExecuteString(string sqlString)
{
//
string result = string.Empty;
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
SqlCommand cmd = new SqlCommand(sqlString, myConn);
try
{
myConn.Open();
object obj = cmd.ExecuteScalar();
if (obj == System.DBNull.Value)
result = string.Empty;
else
result = obj.ToString();
}
catch (SqlException exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "DBExecuteString" + exp.Message);
log.Info(start);
throw exp;
}
finally
{
cmd.Dispose();
myConn.Close();
myConn.Dispose();
}
return result;
}
/// <summary>
/// 执行查询,并返回查询所返回的结果集中第一行的第一列。忽略其他列或行
/// 如果为NULL 则返回 -1
/// </summary>
/// <param name="sqlString">被执行的SQL语句</param>
/// <returns>返回值</returns>
public static object DBExecuteScalar(string sqlString, SqlParameter[] pars)
{
//
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
SqlCommand cmd = new SqlCommand(sqlString, myConn);
try
{
myConn.Open();
cmd.Parameters.AddRange(pars);
object obj = cmd.ExecuteScalar();
return obj;
}
catch (SqlException exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "DBExecuteScalar" + exp.Message);
log.Info(start);
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return -1;
throw exp;
}
finally
{
cmd.Dispose();
myConn.Close();
myConn.Dispose();
}
}
#endregion
#region ExecuteNonQuery 执行SQL语句,返回执行语句所影响的行数
/// <summary>
/// 执行SQL语句,返回执行语句所影响的行数
/// </summary>
/// <param name="sqlString">被执行的SQL语句</param>
/// <returns>返回值</returns>
public static int DBExecuteNonQuery(string sqlString)
{
int rows = -1;
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
try
{
myConn.Open();
SqlCommand myCommand = new SqlCommand(sqlString, myConn);
myCommand.CommandType = CommandType.Text;
rows = myCommand.ExecuteNonQuery();
}
catch (SqlException exp)
{
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return -1;
throw exp;
}
finally
{
myConn.Close();
myConn.Dispose();
}
return rows;
}
/// <summary>
/// 执行SQL语句,返回执行语句所影响的行数
/// </summary>
/// <param name="sqlString">被执行的SQL语句</param>
/// <returns>返回值</returns>
public int DBExecuteNonQuerym(string sqlString)
{
int rows = -1;
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
try
{
myConn.Open();
SqlCommand myCommand = new SqlCommand(sqlString, myConn);
myCommand.CommandType = CommandType.Text;
rows = myCommand.ExecuteNonQuery();
}
catch (SqlException exp)
{
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return -1;
throw exp;
}
finally
{
myConn.Close();
myConn.Dispose();
}
return rows;
}
/// <summary>
/// 执行SQL语句,返回执行语句所影响的行数
/// </summary>
/// <param name="StrSql">被执行的SQL语句</param>
/// <param name="pars">参数</param>
/// <returns>返回首影响的行数</returns>
public static int DBExecuteNonQuery(string StrSql, SqlParameter[] pars)
{
int rows = -1;
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
try
{
myConn.Open();
SqlCommand com = new SqlCommand(StrSql, myConn);
com.Parameters.AddRange(pars);
rows = com.ExecuteNonQuery();
}
catch (SqlException exp)
{
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return -1;
throw exp;
}
finally
{
myConn.Close();
myConn.Dispose();
}
return rows;
}
/// <summary>
/// 执行SQL语句,返回执行语句所影响的行数
/// </summary>
/// <param name="StrSql">被执行的SQL语句</param>
/// <param name="pars">参数</param>
/// <returns>返回首影响的行数</returns>
public int DBExecuteNonQuerym(string StrSql, SqlParameter[] pars)
{
int rows = -1;
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
try
{
myConn.Open();
SqlCommand com = new SqlCommand(StrSql, myConn);
com.Parameters.AddRange(pars);
rows = com.ExecuteNonQuery();
}
catch (SqlException exp)
{
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return -1;
throw exp;
}
finally
{
myConn.Close();
myConn.Dispose();
}
return rows;
}
public static int DBExecuteNonQuery(string sqlString, SqlParameter[] pars, ref SqlParameter[] refpars)
{
int rows = -1;
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
try
{
myConn.Open();
SqlCommand com = new SqlCommand(sqlString, myConn);
com.Parameters.AddRange(pars);
rows = com.ExecuteNonQuery();
//取回参数
refpars = pars;
com.Dispose();
}
catch (SqlException exp)
{
throw exp;
}
finally
{
myConn.Close();
myConn.Dispose();
}
return rows;
}
#endregion
#region SqlDataAdapter 返回执行SQL查询语句返回的数据表
/// <summary>
/// 执行SQL查询语句返回的数据表
/// </summary>
/// <param name="sqlString">查询语句</param>
/// <returns></returns>
public static DataTable DataTableDBExecuteSqlCommand(string sqlString)
{
DataTable tb = new DataTable();
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
try
{
SqlDataAdapter dataAdapter = new SqlDataAdapter(sqlString, myConn);
dataAdapter.Fill(tb);
}
catch (SqlException exp)
{
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return tb;
throw exp;
}
finally
{
myConn.Close();
myConn.Dispose();
}
return tb;
}
public static DataTable DataTableDBExecuteSqlCommand(string sqlString, SqlParameter[] pars)
{
DataTable tb = new DataTable();
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
SqlCommand MyCmd = new SqlCommand(sqlString, myConn);
try
{
MyCmd.Parameters.AddRange(pars);
SqlDataAdapter dataAdapter = new SqlDataAdapter(MyCmd);
dataAdapter.Fill(tb);
}
catch (SqlException exp)
{
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return tb;
throw exp;
}
finally
{
myConn.Close();
myConn.Dispose();
}
return tb;
}
/// <summary>
/// 执行SQL查询语句返回的数据集
/// </summary>
/// <param name="sqlString">查询语句</param>
/// <returns></returns>
public static DataSet DataSetDBExecuteSqlCommand(string sqlString)
{
DataSet dt = new DataSet();
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
try
{
myConn.Open();
SqlCommand myCommand = new SqlCommand(sqlString, myConn);
myCommand.CommandType = CommandType.Text;
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = myCommand;
dataAdapter.Fill(dt);
}
catch (SqlException exp)
{
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return dt;
throw exp;
}
finally
{
myConn.Close();
myConn.Dispose();
}
return dt;
}
public static DataSet DataSetDBExecuteSqlCommand(string sqlString, SqlParameter[] pars)
{
DataSet dt = new DataSet();
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
try
{
myConn.Open();
SqlCommand myCommand = new SqlCommand(sqlString, myConn);
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.AddRange(pars);
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = myCommand;
dataAdapter.Fill(dt);
}
catch (SqlException exp)
{
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return dt;
throw exp;
}
finally
{
myConn.Close();
myConn.Dispose();
}
return dt;
}
#endregion
#region ExecuteNonQuery 执行SQL语句,返回执行语句的状态
/// <summary>
/// 执行SQL语句,返回执行状态
/// </summary>
/// <param name="sqlString">被执行的SQL语句</param>
/// <returns>返回值</returns>
public static bool BoolDBExecuteNonQuery(string sqlString)
{
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
try
{
myConn.Open();
SqlCommand myCommand = new SqlCommand(sqlString, myConn);
myCommand.CommandType = CommandType.Text;
myCommand.ExecuteNonQuery();
}
catch (SqlException exp)
{
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return false;
throw exp;
}
finally
{
myConn.Close();
myConn.Dispose();
}
return true;
}
/// <summary>
/// 执行SQL语句,返回执行状态
/// </summary>
/// <param name="sqlString">被执行的SQL语句</param>
/// <param name="pars">参数</param>
/// <returns>返回值</returns>
public static bool BoolDBExecuteNonQuery(string sqlString, SqlParameter[] pars)
{
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
try
{
myConn.Open();
SqlCommand myCommand = new SqlCommand(sqlString, myConn);
myCommand.CommandType = CommandType.Text;
myCommand.Parameters.AddRange(pars);
myCommand.ExecuteNonQuery();
}
catch (SqlException exp)
{
//MessageBox.Show("数据操作失败!\r\n\r\n描述:" + exp.Message.ToString()
// , "数据库执行提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return false;
throw exp;
}
finally
{
myConn.Close();
myConn.Dispose();
}
return true;
}
#endregion
#region 执行存储过程
/// <summary>
/// 执行存储过程。不带返回信息
/// </summary>
/// <param name="StoredProcedure_name">被执行的存储过程名称</param>
/// <param name="commandParamters">存储过程参数集</param>
/// <returns>执行成功返回一个DataSet,否则返回null</returns>
public static DataSet DataSetDBStoredProcedure(string StoredProcedure_name, params SqlParameter[] pars)
{
DataSet dt = new DataSet();
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
SqlCommand MyCmd = new SqlCommand(StoredProcedure_name, myConn);
MyCmd.CommandType = CommandType.StoredProcedure;
try
{
myConn.Open();
if (pars != null)
{
foreach (SqlParameter parm in pars)
{
MyCmd.Parameters.Add(parm);
}
}
//填充数据源
SqlDataAdapter dataAdapter = new SqlDataAdapter();
dataAdapter.SelectCommand = MyCmd;
dataAdapter.Fill(dt);
}
catch (Exception exp)
{
//MessageBox.Show(exp.Message);
//return null;
throw exp;
}
finally
{
MyCmd.Dispose();
myConn.Close();
myConn.Dispose();
}
return dt;
}
/// <summary>
/// 执行存储过程
/// </summary>
/// <param name="StoredProcedure_name">被执行的存储过程名称</param>
/// <param name="pars">存储过程参数集</param>
/// <returns>执行成功返回true 否则 false</returns>
public static bool BoolDBStoredProcedure(string StoredProcedure_name, SqlParameter[] pars)
{
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
SqlCommand MyCmd = new SqlCommand(StoredProcedure_name, myConn);
MyCmd.CommandType = CommandType.StoredProcedure;
//
try
{
myConn.Open();
MyCmd.Parameters.AddRange(pars);
MyCmd.ExecuteNonQuery();
}
catch (SqlException exp)
{
//MessageBox.Show(exp.Message.ToString(), "数据库操作失败:存储过程错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return false;
throw exp;
}
finally
{
MyCmd.Dispose();
myConn.Close();
myConn.Dispose();
}
return true;
}
public static SqlParameter[] SqlParametersDBStoredProcedure(string StoredProcedure_name, params SqlParameter[] pars)
{
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
SqlCommand MyCmd = new SqlCommand(StoredProcedure_name, myConn);
MyCmd.CommandType = CommandType.StoredProcedure;
//
try
{
myConn.Open();
MyCmd.Parameters.AddRange(pars);
MyCmd.ExecuteNonQuery();
}
catch (SqlException exp)
{
//MessageBox.Show(exp.Message.ToString(), "数据库操作失败:存储过程错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
//return pars;
throw exp;
}
finally
{
MyCmd.Dispose();
myConn.Close();
myConn.Dispose();
}
return pars;
}
#endregion
#region 执行事务
/// <summary>
/// 多SQL语句操作--事务处理
/// </summary>
/// <param name="sqlComm">SQL语句数组</param>
/// <returns>事务,返回String事务结果</returns>
public static bool DoTran(string[] sqlComm)
{
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
SqlTransaction myTran;
myTran = myConn.BeginTransaction();
SqlCommand command = new SqlCommand("", myConn, myTran);
try
{
foreach (string comm in sqlComm)
{
command.CommandText = comm;
command.ExecuteNonQuery();
}
myTran.Commit();
}
catch (Exception exp)
{
//MessageBox.Show(exp.Message.ToString(), "事务处理失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw new ApplicationException("系统信息:" + e.Message);
//return false;
throw exp;
}
finally
{
command.Dispose();
myTran.Dispose();
myConn.Close();
}
return true;
}
public static bool DoTran(List<string> sqlComm)
{
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
try
{
myConn.Open();
SqlTransaction myTran;
myTran = myConn.BeginTransaction();
SqlCommand command = new SqlCommand("", myConn, myTran);
foreach (string comm in sqlComm)
{
command.CommandText = comm;
command.ExecuteNonQuery();
}
myTran.Commit();
command.Dispose();
myTran.Dispose();
}
catch (Exception exp)
{
//MessageBox.Show(exp.Message.ToString(), "事务处理失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw new ApplicationException("系统信息:" + e.Message);
//return false;
throw exp;
}
finally
{
myConn.Close();
}
return true;
}
public static bool DoTran(List<string> sqlComm, List<SqlParameter[]> sqlParsList)
{
string strSql = string.Empty;
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
try
{
myConn.Open();
SqlTransaction myTran = myConn.BeginTransaction();
SqlCommand command = new SqlCommand("", myConn, myTran);
for (int i = 0; i < sqlComm.Count; i++)
{
command.Parameters.Clear();
command.CommandText = sqlComm[i];
strSql = sqlComm[i];
command.Parameters.AddRange(sqlParsList[i]);
command.ExecuteNonQuery();
}
myTran.Commit();
command.Dispose();
myTran.Dispose();
}
catch (Exception exp)
{
//MessageBox.Show(exp.Message.ToString() + "\r\n" + strSql, "事务处理失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw new ApplicationException("系统信息:" + e.Message);
//return false;
throw exp;
}
finally
{
myConn.Close();
}
return true;
}
public static bool DoTran(List<string> sqlComm, List<SqlParameter[]> sqlParsList, out string msg)
{
string strSql = string.Empty;
SqlConnection myConn = new SqlConnection(ReReadConnectionString());
try
{
myConn.Open();
SqlTransaction myTran = myConn.BeginTransaction();
SqlCommand command = new SqlCommand("", myConn, myTran);
for (int i = 0; i < sqlComm.Count; i++)
{
command.Parameters.Clear();
command.CommandText = sqlComm[i];
strSql = sqlComm[i];
command.Parameters.AddRange(sqlParsList[i]);
command.ExecuteNonQuery();
}
myTran.Commit();
command.Dispose();
myTran.Dispose();
}
catch (Exception exp)
{
//MessageBox.Show(exp.Message.ToString() + "\r\n" + strSql, "事务处理失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
//DBHelperErrorLogs.ErrorDeal(exp);
//throw new ApplicationException("系统信息:" + e.Message);
msg = exp.Message;
return false;
}
finally
{
myConn.Close();
}
msg = "";
return true;
}
#endregion
}
}
4
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
namespace EohiQuartzService.Quarzt
{
public class QuartzNetService
{
private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public QuartzNetService()
{
}
/// <summary>
///
/// </summary>
/// <param name="accountname"></param>
/// <returns></returns>
public static List<Model_QuartzNetItem> GetList()
{
try
{
string strSql = @"select * from api_quartz order by quartzname asc ";
//
SqlParameter[] parames = new SqlParameter[]
{
};
DataTable dt = DBHelper.getDataTable(strSql, parames);
if (dt != null)
{
List<Model_QuartzNetItem> list = DataTableEntityConverter.ConvertToEntityList<Model_QuartzNetItem>(dt);
return list;
}
else
return null;
}
catch (Exception exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), " QuartzNetService+ GetList:" + exp.Message);
log.Info(start);
throw exp;
}
}
/// <summary>
///
/// </summary>
/// <param name="accountname"></param>
/// <returns></returns>
public static Model_QuartzNetItem GetById(int id)
{
try
{
string strSql = @"select * from api_quartz where id=@id";
//构建一个哈希表,把参数依次压入
SqlParameter[] parames = new SqlParameter[]
{
new SqlParameter("@id", id)
};
DataTable dt = DBHelper.getDataTable(strSql, parames);
if (dt != null && dt.Rows.Count > 0)
{
Model_QuartzNetItem list = DataTableEntityConverter.ConvertToEntity<Model_QuartzNetItem>(dt.Rows[0]);
return list;
}
else
return null;
}
catch (Exception exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), " QuartzNetService+ GetById:" + exp.Message);
log.Info(start);
throw exp;
}
}
public static void Add(Model_QuartzNetItem item)
{
try
{
string strSql = @"insert into api_quartz (quartzname,quartznote,quartzstatus,crontrigger,jobtype,jobpars,mod_man,mod_date)
values (@quartzname,@quartznote,@quartzstatus,@crontrigger,@jobtype,@jobpars,'',getdate())";
SqlParameter[] pars = new SqlParameter[] {
new SqlParameter("@quartzname", item.Quartzname==null? "":item.Quartzname),
new SqlParameter("@quartznote", item.Quartznote==null? "":item.Quartznote),
new SqlParameter("@quartzstatus", item.Quartzstatus==null? "":item.Quartzstatus),
new SqlParameter("@crontrigger", item.Crontrigger==null? "":item.Crontrigger),
new SqlParameter("@jobtype", item.Jobtype==null? "":item.Jobtype),
new SqlParameter("@jobpars", item.Jobpars==null? "":item.Jobpars)
};
DBHelper.ExecuteNonQuery(strSql, pars);
}
catch (Exception exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), " QuartzNetService+ Add:" + exp.Message);
log.Info(start);
throw exp;
}
}
public static void Update(Model_QuartzNetItem item)
{
try
{
string strSql = @"update api_quartz set
quartzname=@quartzname,
quartznote=@quartznote,
quartzstatus=@quartzstatus,
crontrigger=@crontrigger,
jobtype=@jobtype,
jobpars=@jobpars,
mod_date=getdate(),
mod_man=''
where id=@id";
SqlParameter[] pars = new SqlParameter[]
{
new SqlParameter("@id", item.Id),
new SqlParameter("@quartzname", item.Quartzname==null? "":item.Quartzname),
new SqlParameter("@quartznote", item.Quartznote==null? "":item.Quartznote),
new SqlParameter("@quartzstatus", item.Quartzstatus==null? "":item.Quartzstatus),
new SqlParameter("@crontrigger", item.Crontrigger==null? "":item.Crontrigger),
new SqlParameter("@jobtype", item.Jobtype==null? "":item.Jobtype),
new SqlParameter("@jobpars", item.Jobpars==null? "":item.Jobpars)
};
DBHelper.ExecuteNonQuery(strSql, pars);
}
catch (Exception exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), " QuartzNetService+ Update:" + exp.Message);
log.Info(start);
throw exp;
}
}
public static void UpdateStatus(Model_QuartzNetItem item)
{
try
{
string strSql = @"update api_quartz set quartzstatus=@quartzstatus where id=@id";
SqlParameter[] pars = new SqlParameter[]
{
new SqlParameter("@id", item.Id),
new SqlParameter("@quartzstatus", item.Quartzstatus==null? "":item.Quartzstatus)
};
DBHelper.ExecuteNonQuery(strSql, pars);
}
catch (Exception exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), " QuartzNetService+ UpdateStatus:" + exp.Message);
log.Info(start);
throw exp;
}
}
public static void Delete(Model_QuartzNetItem apiItem)
{
try
{
string strSql = @"delete from api_quartz where id=@id";
SqlParameter[] parames = new SqlParameter[]
{
new SqlParameter("@id",apiItem.Id),
};
DBHelper.ExecuteNonQuery(strSql, parames);
}
catch (Exception exp)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), " QuartzNetService+ Delete:" + exp.Message);
log.Info(start);
throw exp;
}
}
}
}
5
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
namespace EohiQuartzService.Quarzt
{
public static class DataTableEntityConverter
{
private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static T ConvertToEntity<T>(DataRow tableRow) where T : new()
{
// Create a new type of the entity I want
Type t = typeof(T);
T returnObject = new T();
foreach (DataColumn col in tableRow.Table.Columns)
{
string colName = col.ColumnName;
// Look for the object's property with the columns name, ignore case
PropertyInfo pInfo = t.GetProperty(colName.ToLower(),
BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
// did we find the property ?
if (pInfo != null)
{
object val = tableRow[colName];
// is this a Nullable<> type
bool IsNullable = (Nullable.GetUnderlyingType(pInfo.PropertyType) != null);
if (IsNullable)
{
if (val is System.DBNull)
{
val = null;
}
else
{
// Convert the db type into the T we have in our Nullable<T> type
val = Convert.ChangeType(val, Nullable.GetUnderlyingType(pInfo.PropertyType));
}
}
else
{
try
{
// Convert the db type into the type of the property in our entity
val = Convert.ChangeType(val, pInfo.PropertyType);
}
catch (Exception ex)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "DataTableEntityConverter" + ex.Message);
log.Info(start);
}
}
try
{
// Set the value of the property with the value from the db
pInfo.SetValue(returnObject, val, null);
}
catch (Exception ex)
{
string start = string.Format("{0}-{1}", DateTime.Now.ToString("yyyyMMddHHmmss"), "DataTableEntityConverter+ pInfo" + ex.Message);
log.Info(start);
}
}
}
// return the entity object with values
return returnObject;
}
public static List<T> ConvertToEntityList<T>(DataTable table) where T : new()
{
// Create a new type of the entity I want
List<T> result = new List<T>();
foreach (DataRow tableRow in table.Rows)
{
Type t = typeof(T);
T returnObject = new T();
foreach (DataColumn col in table.Columns)
{
string colName = col.ColumnName;
// Look for the object's property with the columns name, ignore case
PropertyInfo pInfo = t.GetProperty(colName.ToLower(),
BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
// did we find the property ?
if (pInfo != null)
{
object val = tableRow[colName];
// is this a Nullable<> type
bool IsNullable = (Nullable.GetUnderlyingType(pInfo.PropertyType) != null);
if (IsNullable)
{
if (val is System.DBNull)
{
val = null;
}
else
{
// Convert the db type into the T we have in our Nullable<T> type
val = Convert.ChangeType
(val, Nullable.GetUnderlyingType(pInfo.PropertyType));
}
}
else
{
// Convert the db type into the type of the property in our entity
val = Convert.ChangeType(val, pInfo.PropertyType);
}
// Set the value of the property with the value from the db
pInfo.SetValue(returnObject, val, null);
}
}
result.Add(returnObject);
}
// return the entity object with values
return result;
}
public static DataTable GetDataTableSchema<T>()
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
Type pt = prop.PropertyType;
if (pt.IsGenericType && pt.GetGenericTypeDefinition() == typeof(Nullable<>))
pt = Nullable.GetUnderlyingType(pt);
table.Columns.Add(prop.Name, pt);
}
return table;
}
public static DataTable ConvertToDataTable<T>(List<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = GetDataTableSchema<T>();
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
table.AcceptChanges();
return table;
}
}
}
6
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EohiQuartzService.Quarzt
{
public class Model_QuartzNetItem
{
int id = 0;
string quartzname = "";
string quartznote = "";
string quartzstatus = "";
string crontrigger = "";//触发规则
public string Crontrigger
{
get { return crontrigger; }
set { crontrigger = value; }
}
string jobpars = "";
string jobtype = "";
string mod_man = "";
DateTime mod_date;
public int Id
{
get { return id; }
set { id = value; }
}
public string Quartzname
{
get { return quartzname; }
set { quartzname = value; }
}
public string Quartznote
{
get { return quartznote; }
set { quartznote = value; }
}
public string Quartzstatus
{
get { return quartzstatus; }
set { quartzstatus = value; }
}
public string Mod_man
{
get { return mod_man; }
set { mod_man = value; }
}
public DateTime Mod_date
{
get { return mod_date; }
set { mod_date = value; }
}
public string Jobtype
{
get { return jobtype; }
set { jobtype = value; }
}
public string Jobpars
{
get { return jobpars; }
set { jobpars = value; }
}
}
}