将控制台应用转换为 Windows 服务

本文关键字:Windows 服务 转换 控制台 应用 | 更新日期: 2023-09-27 18:36:36

>我试图将生成pdf报告的控制台应用程序转换为Windows服务。我的代码如下。我的方向是否正确?我安装了此服务并且启动/停止工作正常,但没有生成报告!控制台应用本身可以正常工作,以生成输出.pdf。我的目标是在服务启动时生成输出。

class Program : ServiceBase
{
    public Program()
    {
        this.ServiceName = "My PdfGeneration";
    }
    static void Main(string[] args)
    {
        ServiceBase.Run(new Program());
    }
    protected override void OnStart(string[] args)
    {
        EventLog.WriteEntry("My PdfGeneration Started");
        //base.OnStart(args);
        //Customise parameters for render method
        Warning[] warnings;
        string[] streamIds;
        string mimeType = string.Empty;   //"application/pdf";
        string encoding = string.Empty;
        string filenameExtension = string.Empty;
        string deviceInfo = "<DeviceInfo>" + "<OutputFormat>PDF</OutputFormat>" + "<PageWidth>15in</PageWidth>" + "<PageHeight>11in</PageHeight>" + "<MarginTop>0.5in</MarginTop>" + "<MarginLeft>0.5in</MarginLeft>" + "<MarginRight>0.5in</MarginRight>" + "<MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>";
        //Create a SqlConnection to the AdventureWorks2008R2 database. 
        SqlConnection connection = new SqlConnection("data source=localhost;initial catalog=pod;integrated security=True");
        //Create a SqlDataAdapter for the Sales.Customer table.
        SqlDataAdapter adapter = new SqlDataAdapter();
        // A table mapping names the DataTable.
        adapter.TableMappings.Add("View", "Route_Manifest");
        // Open the connection.
        connection.Open();
        Console.WriteLine("'nThe SqlConnection is open.");
        // Create a SqlCommand to retrieve Suppliers data.
        SqlCommand command = new SqlCommand("SELECT TOP 10 [RouteID],[FullTruckID],[DriverID],[DriverName],[StopID],[CustomerID],[CustomerName],[InvoiceID],[last_modified],[Amount] FROM [pod].[dbo].[Route_Manifest]", connection);
        command.CommandType = CommandType.Text;
        // Set the SqlDataAdapter's SelectCommand.
        adapter.SelectCommand = command;
        command.ExecuteNonQuery();
        // Fill the DataSet.
        DataSet dataset = new DataSet("Route_Manifest");
        adapter.Fill(dataset);
        //Set up reportviewver and specify path
        ReportViewer viewer = new ReportViewer();
        viewer.ProcessingMode = ProcessingMode.Local;
        viewer.LocalReport.ReportPath = @"C:'Documents and Settings'xxxxx'My Documents'Visual Studio 2008'Projects'PdfReportGeneration'PdfReportGeneration'Report.rdlc";
        //specify the dataset syntax = (datasetofreport.rdlc,querydataset); 
        viewer.LocalReport.DataSources.Add(new ReportDataSource("podDataSet_Route_Manifest", dataset.Tables[0]));

        //Now render it to pdf
        try
        {
            byte[] bytes = viewer.LocalReport.Render("PDF", deviceInfo, out mimeType, out encoding, out filenameExtension, out streamIds, out warnings);
            //output to bin directory 
            using (System.IO.FileStream fs = new System.IO.FileStream("output.pdf", System.IO.FileMode.Create))
            {
                //file saved to bin directory
                fs.Write(bytes, 0, bytes.Length);
            }
            Console.WriteLine("'n YEP!! The report has been generated:-)");
            /*           //Save report to D:' -- later
                         FileStream fsi = new FileStream(@"D:'output.pdf", System.IO.FileMode.Create);
            */
        }
        catch (Exception e)
        {
            Console.WriteLine("'n CHEY!!!this Exception encountered:", e);
        }

        // Close the connection.
        connection.Close();
        Console.WriteLine("'nThe SqlConnection is closed.");
        Console.ReadLine();
    }
    protected override void OnStop()
    {
        EventLog.WriteEntry("My PdfGeneration Stopped");
            base.OnStop();
    }
}

将控制台应用转换为 Windows 服务

我建议您将 OnStart 事件中的代码移动到单独的线程,因为您的服务需要及时启动,否则可能会超时启动时。

例如

using System.ServiceProcess;
using System.Threading;
namespace myService
{
    class Service : ServiceBase
    {
        static void Main()
        {
            ServiceBase.Run(new Service());
        }
        public Service()
        {
            Thread thread = new Thread(Actions);
            thread.Start();
        }
        public void Actions()
        {
            // Do Work
        }
    }
}

您可能还想检查执行用户(运行服务的用户上下文)有权访问您要写入的文件夹等。

您还需要将错误写入事件日志,而不是将它们写入控制台窗口,如您的代码片段所示(您的代码目前正在吞噬异常这就是为什么你不能指出出了什么问题)

在这里阅读更多内容:C# 基础知识:创建 Windows 服务

是和不是,你应该做的是通过定义一个接口来定义你正在公开的操作合约。

例如,在第 9 频道上看到这个:
http://channel9.msdn.com/Shows/Endpoint/Endpoint-Screencasts-Creating-Your-First-WCF-Service

应将此服务定义为单独的库程序集(因为明天您将希望在其他位置托管此服务,并且很可能在控制台应用程序中进行开发时)。

使用服务时,您需要考虑它是否应该来自 asp.net 网页、Windows 窗体程序或控制台实用工具,实际上取决于您的使用者方案,您希望将实际的 PDF 功能外部化到一个单独的类(在同一库程序集中),以便有一天您希望能够在其他程序中执行此操作, 它不必与网络上某处的 WCF 服务进行通信,尽管这样的事情本身就很漂亮,它会在有限的程度上影响跨进程集成的性能。