总结下,winform开发windows服务全过程 ;windows服务的代码中,不能有MessageBox.Show()等winform的控件引用 。可以使用写文本日志的方法调试;
1、添加服务引用,输入 webservice的地址,点转到,然后给引用的服务起个“命名空间”名字,之后会在“解决方案”Connected services 下显示 ;
2、设置为需要管理员的权限 ;在app.manifest文件中,将LEVEL的值 level="requireAdministrator"
3、
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Security.Cryptography; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using System.Timers; using System.Windows; namespace LRDDIService { public partial class Service1 : ServiceBase { Timer timer; string filePath = AppDomain.CurrentDomain.BaseDirectory; public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { timer = new Timer(); timer.Interval = 60000;// 60 seconds 60秒执行一次 timer.Elapsed += new ElapsedEventHandler(this.OnTimer); //项目启动时判断,当前时间是否超过定时的时间。如定时在12:00执行,当前时间为13,则立即执行; //string lastupload = LRDDIServiceClient.CommFunc.GetXmlValue("config.xml", "//ConnString", "Lastupload"); timer.Start(); } /// <summary> /// 定时器中定时执行的任务 /// </summary> /// <param name="sender"></param> /// <param name="args"></param> public void OnTimer(object sender, ElapsedEventArgs args) { try { log(DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Hour.ToString()); //获取config.xml文件中,最近一次的上传日期 string lastUpload = LRDDIServiceClient.CommFunc.GetXmlValue(filePath + "config.xml", "//ConnString", "Lastupload"); string jobTime = LRDDIServiceClient.CommFunc.GetXmlValue(filePath + "config.xml", "//ConnString", "Jobtime"); //判断是否等于定时执行时间 if (DateTime.Now.Hour.ToString()+":"+DateTime.Now.Minute.ToString() == jobTime) { log("任务开始"); string rt = UPloadZip(); log(rt); log("任务执行结束"); } } catch (Exception ex) { log(ex.Message); } } //从数据库中取数并上传至服务器 private string UPloadZip() { try { string clientId = LRDDIServiceClient.CommFunc.GetXmlValue(filePath + "config.xml", "//ConnString", "Clientid"); log(clientId); //判断数据库类型 string databaseType = LRDDIServiceClient.CommFunc.GetXmlValue(filePath + "config.xml", "//ConnString", "DatabaseType"); //执行流向查询SQL string sql = LRDDIServiceClient.CommFunc.GetXmlValue(filePath + "sql.xml", "//Sql", "FlowSql"); log(sql + ";" + databaseType); DataTable dt = GetResult(databaseType, sql); if (dt == null) { log("查询数据库出错,DT为NULL"); return "0"; } string xmlFilename = filePath + clientId + "-flow.json"; string zipFilename = filePath + clientId + "-flow.zip"; //如果不指定dt名字,会报错:无法序列化 DataTable dt.TableName = "Flow"; #region 写入xml文件 ////写入xml文件 ///// FileStream fsWriteXml = new FileStream(xmlFilename, System.IO.FileMode.Create); //dt.WriteXml(fsWriteXml); //log(xmlFilename); //log(zipFilename); ////关闭文件 //fsWriteXml.Close(); #endregion #region 写入json文件 string jsReturn = DataTable2Json.DataTableToJsonFile(dt, xmlFilename); if (jsReturn == "0") log("写入json文件失败"); #endregion LRDDIServiceClient.ZipHelper.ZipFile(xmlFilename, zipFilename); log("完成压缩文件;"); //zip文件转换为流文件 var byteArray = FileToByteArray(zipFilename); log("zip文件转换为流文件;"); ////计算哈希值 md5 //MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); //byte[] md5Bytes = md5.ComputeHash(byteArray); //string md5String = BitConverter.ToString(md5Bytes); LrWebDDI.CommonWebServiceImplClient myWebService = null; myWebService = new LrWebDDI.CommonWebServiceImplClient("CommonWebServiceImplPort"); string rt = myWebService.upload(byteArray, clientId+"-"+DateTime.Now.ToString("yyyy'-'MM'-'dd") +"-flow.zip"); log("上传完成!"); //删除本地文件ZIP文件 if (File.Exists(zipFilename)) { //File.Delete(zipFilename); } //删除本地文件xml文件 if (File.Exists(xmlFilename)) { // File.Delete(xmlFilename); } } catch (Exception ex) { log("UPloadZip函数出错:" + ex.Message); } return "1"; } /// <summary> /// 根据SQL语句获取查询结果 /// </summary> /// <param name="databasetype">数据库类型</param> /// <param name="sql">查询SQL</param> /// <returns></returns> private DataTable GetResult(string databasetype, string sql) { DataTable dt = new DataTable(); log("进入GetResult ()函数"); try { switch (databasetype) { case "MSSQL": //dt = LRDDIServiceClient.DBHelperMS.ExecuteQuery(sql); string connstring = LRDDIServiceClient.CommFunc.GetConnString(); log("获取连接信息完成"); using (SqlConnection conn = new SqlConnection(connstring)) { conn.Open(); SqlDataAdapter sda = new SqlDataAdapter(sql, conn); sda.Fill(dt); conn.Close(); } break; case "ORACLE": dt = LRDDIServiceClient.DBHelperOracle.GetTable(sql); break; case "POSTGRESQL": dt = LRDDIServiceClient.DBHelperPg.ExecuteDataTable(sql); break; default: break; } log("SQL已执行"); } catch (Exception ex) { log("GetResult出错" + ex.Message); } return dt; } /// <summary> /// 文件 转 Byte[] /// </summary> /// <param name="fileUrl"></param> /// <returns></returns> static byte[] FileToByteArray(string fileUrl) { using (FileStream fs = new FileStream(fileUrl, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite)) { byte[] buffur = new byte[fs.Length]; // 注意:一定要读取否则。。。值得一试