C#Windows服务未按预期工作

时间:2019-02-01 18:58:40

标签: c# windows-services

我写了一个Windows服务,该服务应该检查一个表,如果该表有行,那么它将创建一个报告并将其放在文件夹中。它写入用于停止和启动的时间戳记,但是OnElapsedTime不起作用。第一个代码块是服务,第二个代码块是我编写的用于发送报告的方法(我知道,在我将其作为服务之前,我对其进行了测试)。不确定为什么不会生成报告。

partial class Service2 : ServiceBase
{
    Timer timer = new Timer(); // name space(using System.Timers;) 
    public Service2()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        WriteToFile("Service is started at " + DateTime.Now);
        timer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
        timer.Interval = 600000; //number in milisecinds  
        timer.Enabled = true;
        timer.AutoReset = true;
        timer.Start();
    }

    protected override void OnStop()
    {
        WriteToFile("Service is stopped at " + DateTime.Now);
    }
    private void OnElapsedTime(object source, ElapsedEventArgs e)
    {
        CheckForReports();
        WriteToFile("Service is recall at " + DateTime.Now);
    }
    public void WriteToFile(string Message)
    {
        string path = AppDomain.CurrentDomain.BaseDirectory + "\\Logs";
        if (!Directory.Exists(path))
        {
            Directory.CreateDirectory(path);
        }
        string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\Logs\\ServiceLog_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
        if (!File.Exists(filepath))
        {
            // Create a file to write to.   
            using (StreamWriter sw = File.CreateText(filepath))
            {
                sw.WriteLine(Message);
            }
        }
        else
        {
            using (StreamWriter sw = File.AppendText(filepath))
            {
                sw.WriteLine(Message);
            }
        }
    }
    public void CheckForReports()
    {
        {
            SqlConnection sqlConnection;

            sqlConnection = new SqlConnection("Server=****;Database=ChrisCMS; Trusted_Connection=True;");
            sqlConnection.Open();

            using (sqlConnection)
            {
                SqlCommand command = new SqlCommand(
                    "Select * from SentReports;");

                SqlDataReader reader = command.ExecuteReader();

                if (reader.HasRows)
                {
                    DataClasses1DataContext classes1DataContext = new DataClasses1DataContext();
                    foreach (SentReport entity in classes1DataContext.SentReports)
                    {
                        new ReportSender.MyReportRenderer().RenderTest(entity.QueueReports);
                        classes1DataContext.SentReports.DeleteOnSubmit(entity);

                    }
                    classes1DataContext.ExecuteCommand("TRUNCATE TABLE SentReports");
                    classes1DataContext.SubmitChanges();
                }
                reader.Close();

            }


        }
    }
}


public class MyReportRenderer
{
    private rs2005.ReportingService2010 rs;
    private rs2005Execution.ReportExecutionService rsExec;



    public void RenderTest(String matchedCaseNumber)
    {
        string HistoryID = (string)null;

        string DeviceInfo = (string)null;
        string MimeType = string.Empty;
        string Encoding = string.Empty;
        string Extension = string.Empty;
        ReportSender.rs2005Execution.Warning[] Warnings = (ReportSender.rs2005Execution.Warning[])null;
        string[] StreamIds = (string[])null;
        this.rs = new ReportingService2010();
        this.rsExec = new ReportExecutionService();
        this.rs.Credentials = CredentialCache.DefaultCredentials;
        this.rsExec.Credentials = CredentialCache.DefaultCredentials;
        this.rs.Url = "http://***/ReportServer/ReportService2010.asmx";
        this.rsExec.Url = "http://***/ReportServer/ReportExecution2005.asmx";


        try
        {
            // Load the selected report.
            this.rsExec.LoadReport("/ChrisPhiladelphiaReports/AFSReport", HistoryID);
            //string devInfo = @"<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>";
            // Set the parameters for the report needed.

            rs2005Execution.ParameterValue[] parameters = new rs2005Execution.ParameterValue[1];
            parameters[0] = new rs2005Execution.ParameterValue();
            parameters[0].Name = "paramCaseNum";
            parameters[0].Value = matchedCaseNumber;

            rsExec.SetExecutionParameters(parameters, "en-us");

            // get pdf of report 
            byte[] buffer = this.rsExec.Render("PDF", DeviceInfo, out Extension, out MimeType, out Encoding, out Warnings, out StreamIds);
            DataClasses1DataContext classes1DataContext = new DataClasses1DataContext();
            Queryable.SingleOrDefault<string>(Queryable.Select<CaseInfo, string>(Queryable.Where<CaseInfo>((IQueryable<CaseInfo>)classes1DataContext.GetTable<CaseInfo>(), (Expression<Func<CaseInfo, bool>>)(c => c.CaseNumberKey == matchedCaseNumber)), (Expression<Func<CaseInfo, string>>)(c => c.ParcelNumber)));
            //string str1 = Queryable.SingleOrDefault<string>(Queryable.Select<CaseInfo, string>(Queryable.Where<CaseInfo>((IQueryable<CaseInfo>)classes1DataContext.GetTable<CaseInfo>(), (Expression<Func<CaseInfo, bool>>)(c => c.CaseNumberKey == matchedCaseNumber)), (Expression<Func<CaseInfo, string>>)(c => c.Summary)));
            // string str2 = Queryable.SingleOrDefault<string>(Queryable.Select<CaseInfo, string>(Queryable.Where<CaseInfo>((IQueryable<CaseInfo>)classes1DataContext.GetTable<CaseInfo>(), (Expression<Func<CaseInfo, bool>>)(c => c.CaseNumberKey == matchedCaseNumber)), (Expression<Func<CaseInfo, string>>)(c => string.Format("{0:C}", (object)c.Total))));
            string str3 = Queryable.SingleOrDefault<string>(Queryable.Select<CaseInfo, string>(Queryable.Where<CaseInfo>((IQueryable<CaseInfo>)classes1DataContext.GetTable<CaseInfo>(), (Expression<Func<CaseInfo, bool>>)(c => c.CaseNumberKey == matchedCaseNumber)), (Expression<Func<CaseInfo, string>>)(c => c.Premises)));
            //MailMessage message = new MailMessage("Reports@aalacquest.com", "gcg@aalacquest.com", "Report for Property " + Queryable.SingleOrDefault<string>(Queryable.Select<CaseInfo, string>(Queryable.Where<CaseInfo>((IQueryable<CaseInfo>)classes1DataContext.GetTable<CaseInfo>(), (Expression<Func<CaseInfo, bool>>)(c => c.CaseNumberKey == matchedCaseNumber)), (Expression<Func<CaseInfo, string>>)(c => c.Premises))), "MuniReport.");
            //MailAddress mailAddress = new MailAddress("george.greiner@aalacquest.com");
            //((Collection<MailAddress>)message.CC).Add(mailAddress);
            //SmtpClient smtpClient = new SmtpClient("localhost");
            //message.Attachments.Add(new Attachment((Stream)new MemoryStream(buffer), string.Format("{0}" + str3 + ".pdf", (object)"BRT")));
            //smtpClient.Send(message);
            FileStream stream = File.OpenWrite("D:\\ClientWebFiles\\Reports\\" + str3 + ".pdf");
            stream.Write(buffer, 0, buffer.Length);
            stream.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我发现了我的错误。这也是愚蠢的。方法实际上从未检查的报告我错过这是粗体下面的行:

public void CheckForReports()
{
    {
        SqlConnection sqlConnection;

        sqlConnection = new SqlConnection("Server=****;Database=ChrisCMS; Trusted_Connection=True;");
        sqlConnection.Open();

        using (sqlConnection)
        {
            SqlCommand command = new SqlCommand(
                "Select * from SentReports;");
            ***command.Connection = sqlConnection;***
            SqlDataReader reader = command.ExecuteReader();

            if (reader.HasRows)
            {
                DataClasses1DataContext classes1DataContext = new DataClasses1DataContext();
                foreach (SentReport entity in classes1DataContext.SentReports)
                {
                    new ReportSender.MyReportRenderer().RenderTest(entity.QueueReports);
                    classes1DataContext.SentReports.DeleteOnSubmit(entity);

                }
                classes1DataContext.ExecuteCommand("TRUNCATE TABLE SentReports");
                classes1DataContext.SubmitChanges();
            }
            reader.Close();

        }


    }
}