首页 > 系统相关 >winform开发windows服务过程简要回顾

winform开发windows服务过程简要回顾

时间:2022-08-22 16:33:56浏览次数:44  
标签:简要 log windows System new using dt winform string

总结下,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];
                // 注意:一定要读取否则。。。值得一试

标签:简要,log,windows,System,new,using,dt,winform,string
From: https://www.cnblogs.com/lrzy/p/16613267.html

相关文章

  • Windows环境下IDEA配置SSH Key访问Gitlab源代码仓库
    使用Gitlab管理项目时,project在创建的时候只能选择“Public”公开状态,Private和Internal私有模式下不能使用http方式进行连接。(ssh方式在三种模式下都可以)。使用http方式直......
  • Windows Terminal ssh登录 ubuntu
    1.ubuntu1.配好虚拟机网络模式,如果只有NAT,添加一个virtualnetworkadapter用于Host-Only模式2.打开ubuntu网络配置文件并且将Host-only   所使用的网......
  • Windows安全加固
    实验环境操作系统:WindowsServer2012系统密码:安全加固项1、用户系统1.1加固项名称:Administrator账户停用加固说明:防止Administrator账户被黑客爆破出密码,避免A......
  • windows创建SSH key
    安装Gitforwindowshttps://git-scm.com/download/win创建密钥对打开命令行,输入以下命令$ssh-keygen-trsa-C"ZhangSan<[email protected]>"-fZh......
  • Windows批量修改文件
    如图我是建立了壁纸文件夹Windows自带的排序方式如何不用自带的呢?在这个文件夹里面建一个.txt文件如下ok第二步骤将UTF-8格式改为ANSI格式点击文件-另存为AN......
  • 关于Microfoft C# Windows程序设计P494 ProgramWithIcon.cs学习体会(重点是winform标
    此程序的重点就是如何添加ico文件:一、在解决方案资源管理器的项目上右键,添加->新建项   二、下拉找到“图标文件”选项,然后将名称更改为“ProgramWithIcon.ico”......
  • [FAQ] Windows 终端 git status 不识别文件名大小写的修改
     当我们修改了文件名的大小写,gitstatus显示没有文件改动。 出现这种情况,首先看一下git的配置项是否忽略了文件问大小写:$ gitconfigcore.ignorecase 如果是......
  • windows make安装
    windowsmake安装1.1下载包网址:https://osdn.net/projects/mingw/releases/2.1安装双击后进入安装页面我更改了安装路径,默认C盘等待他自己下载安装包3.1设......
  • windows安装xgb、lgb
    Windows10操作系统+Anaconda环境,亲测有效。xgb:condainstallpy-xgboostlgb:先打开:Anacondaprompt输入:condainstall-cconda-forgelightgbm......
  • windows操作系统安装Docker
    1win10,操作系统版本号大于20042开启WSL,https://docs.microsoft.com/en-us/windows/wsl/install命令行工具,运行命令:wsl--install3确认以下功能都开启  ......