将数据从SQL读取到服务C#

将数据从SQL读取到服务C#,c#,service,sendmail,C#,Service,Sendmail,我想问为什么服务不能从sql获取数据,应用程序在控制台应用程序中正常工作,但当我将其粘贴到服务中时,它就不能工作了。我在网上搜索了很多东西,但是我没有找到。你能帮助我吗。在代码中,我尝试将sql查询保存在excel文件中,然后将其发送到mail 谢谢 <pre><code>using OfficeOpenXml; using System; using System.Collections.Generic; using System.ComponentModel; usi

我想问为什么服务不能从sql获取数据,应用程序在控制台应用程序中正常工作,但当我将其粘贴到服务中时,它就不能工作了。我在网上搜索了很多东西,但是我没有找到。你能帮助我吗。在代码中,我尝试将sql查询保存在excel文件中,然后将其发送到mail

谢谢

<pre><code>using OfficeOpenXml;
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.Net;
using System.Net.Mail;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace Nerma_Mail_Reporter_Service
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();

        }

        System.Timers.Timer createOrderTimer;
        private string folderPath = @"c:\CEMAL";
        static string current = DateTime.Now.ToShortTimeString();
        static DataTable dtService;
        static DataTable dtMailfrom;
        static SqlDataAdapter daService;
        static SqlDataAdapter daMailfrom;
        static DataTable dtDay;
        static SqlDataAdapter daDay;
        static int repID;

        protected override void OnStart(string[] args)
        {
            if (!System.IO.Directory.Exists(folderPath))
                System.IO.Directory.CreateDirectory(folderPath);

            EventLog.WriteEntry("start Calisti", EventLogEntryType.Information); 

            createOrderTimer = new System.Timers.Timer();

            createOrderTimer.Interval = 6000;
            createOrderTimer.Enabled = true;
            createOrderTimer.AutoReset = true;
            createOrderTimer.Start();
            createOrderTimer.Elapsed += new System.Timers.ElapsedEventHandler(Gonder_Elapsed);

        }
        protected override void OnContinue()
        {
            EventLog.WriteEntry("OnContinue Calisti", EventLogEntryType.Information); 

            createOrderTimer.Elapsed += new System.Timers.ElapsedEventHandler(Gonder_Elapsed);
        }
        protected override void OnStop()
        {
            EventLog.WriteEntry("Nerma Danismanlik Servisi Durdurulmustur...", EventLogEntryType.SuccessAudit);
        }

        private void Gonder_Elapsed(object sender, EventArgs e)
        {

            using (SqlConnection conn = new SqlConnection("Server=CEMAL;UID=sa;pwd=123 ;Database=MailReporter"))
            { EventLog.WriteEntry("Gonder Calisti", EventLogEntryType.Information); 
                conn.Open();
                daService = new SqlDataAdapter("select * from SENDSERVICE", conn);
                dtService = new DataTable();
                daService.Fill(dtService);


                foreach (DataRow dr in dtService.Rows)
                {
                    EventLog.WriteEntry("dtservice Calisti", EventLogEntryType.Information);

                    SaveToExcel(18);
                   SendMail(18);
                    EventLog.WriteEntry("Mail Gitt");
                    DateTime start = Convert.ToDateTime(dr["STARTRUNTIME"]);
                    DateTime end = Convert.ToDateTime(dr["ENDRUNTIME"]);
                    DateTime next = Convert.ToDateTime(dr["NEXTRUNTIME"]);
                    bool gittiMi = Convert.ToBoolean(dr["GITTIMI"]);
                    DateTime now = DateTime.Now;
                    // string format = "HH:mm:ss";
                    string format = "HH:mm";
                    EventLog.WriteEntry("DTService BItti", EventLogEntryType.Information); 

                    now.ToString(format);
                    int ServiceID = Convert.ToInt32(dr["ID"]);
                    int result = DateTime.Compare(next, end);
                    bool isDayly = Convert.ToBoolean(dr["isDayly"]);

                    if (result <= 0 && gittiMi == true)
                    {
                        using (SqlCommand cmd = new SqlCommand("update SENDSERVICE set GITTIMI=false)", conn))
                        {
                            cmd.ExecuteNonQuery();
                        }
                    }

                    EventLog.WriteEntry("isdayly kontrol gecti calisacak", EventLogEntryType.Information);
                    if (isDayly)
                     {   EventLog.WriteEntry("isdayly kontrol gecti Calisti", EventLogEntryType.Information);

                        //Devam Eden Islemler
                        if (result <= 0 && next.ToString(format) == now.ToString(format) && gittiMi == false)
                        {
                            EventLog.WriteEntry("isDayly Calisti", EventLogEntryType.Information);

                            int ID = 0;
                            int every = 0;

                            {
                                using (daDay = new SqlDataAdapter("select * from Dayly", conn))
                                {

                                    dtDay = new DataTable();
                                    daDay.Fill(dtDay);
                                    foreach (DataRow day in dtDay.Rows)
                                    {
                                        if (Convert.ToInt32(day["SERVICEID"]) == ServiceID)
                                        {
                                            ID = Convert.ToInt32(day["ID"]);
                                            every = Convert.ToInt32(day["EVERYisDayly"]);

                                            using (SqlCommand insert = new SqlCommand("update SENDSERVICE set LASTRUNTIME='" + DateTime.Now.ToShortDateString() + "',NEXTRUNTIME='" + DateTime.Now.AddDays(every) + "' where ID=" + ServiceID + "", conn))
                                            {

                                                insert.ExecuteNonQuery();
                                            }
                                        }

                                     }   
                                    EventLog.WriteEntry("Save to Excel Baslayacak", EventLogEntryType.Information);

                                    SaveToExcel(ServiceID);
                                    bool isSend = SendMail(ServiceID);

                                    using (SqlCommand cmd = new SqlCommand("update SENDSERVICE set GITTIMI='" + isSend + "' where ID=" + ServiceID + "", conn))
                                     {   EventLog.WriteEntry("IsSend Calisti", EventLogEntryType.Information);

                                        cmd.ExecuteNonQuery();
                                    }
                                }
                            }
                        }
                    }
                }
            }

            EventLog.WriteEntry("gonder bitti");
        }

        public  bool SendMail(int ServiceID)
        {
            try
              {              
              EventLog.WriteEntry("SENDMAil Calisti", EventLogEntryType.Information);

                using (SqlConnection conn = new SqlConnection("Server=CEMAL;UID=sa;pwd=123 ;Database=MailReporter"))
                {

                    daMailfrom = new SqlDataAdapter("select * from MAILFROM where SERVICEID=" + ServiceID + "", conn);
                    dtMailfrom = new DataTable();
                    daMailfrom.Fill(dtMailfrom);

                    daService = new SqlDataAdapter("select * from SENDSERVICE where ID=" + ServiceID + "", conn);
                    dtService = new DataTable();
                    daService.Fill(dtService);

                    foreach (DataRow mailfrom in dtMailfrom.Rows)
                    {
                        foreach (DataRow service in dtService.Rows)
                        {
                            string smtpAddress = mailfrom["SMTP"].ToString();
                            int portNumber = Convert.ToInt32(mailfrom["PORT"]);
                            bool enableSSL = Convert.ToBoolean(mailfrom["ENABLESSL"]);
                            string emailFrom = service["EMAILFROM"].ToString();
                            string password = mailfrom["PASS"].ToString();
                            string emailTo = service["EMAILTO"].ToString();
                            //string subject = service["SUBJECT"].ToString();
                            string subject = DateTime.Now.ToLongTimeString();
                            string body = service["BODY"].ToString();
                            string Attachement = service["RAPORADI"].ToString();

                            using (MailMessage mail = new MailMessage())
                            {
                                mail.From = new MailAddress(emailFrom);
                                mail.To.Add(emailTo);
                                mail.Subject = subject;
                                mail.Body = body;
                                mail.IsBodyHtml = true;
                                mail.Attachments.Add(new Attachment(@"C:\CEMAL\" + Attachement + ".xlsx"));

                                using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
                                {
                                    smtp.Credentials = new NetworkCredential(emailFrom, password);
                                    smtp.EnableSsl = enableSSL;

                                    smtp.Send(mail);
                                    return true;
                                   // EventLog.WriteEntry("Mail GOnderildi Calisti", EventLogEntryType.Information);

                                }
                            }
                        }
                    }

                }
            }
           catch(Exception){}
            return false;
        }
        public  void SaveToExcel(int ServiceID)
         {                  
            EventLog.WriteEntry("Save to Excel Calisti", EventLogEntryType.Information);


            string RaporAdi = "";

            using (SqlConnection conSave = new SqlConnection("Server=CEMAL;Database=MailReporter;user id=sa;pwd=123"))
            {
                conSave.Open();

                SqlDataAdapter daRer = new SqlDataAdapter("select * from NERRAPOR where SERVICEID=" + ServiceID + "", conSave);
                DataTable dtRep = new DataTable();
                daRer.Fill(dtRep);

                foreach (DataRow dr in dtRep.Rows)
                {
                    if (Convert.ToInt32(dr["SERVICEID"]) == ServiceID)
                    {
                        RaporAdi = dr["RAPORADI"].ToString();
                        string SqlCumle = dr["SQLCUMLE"].ToString();
                        SqlDataAdapter cumle = new SqlDataAdapter(SqlCumle, "Server=CEMAL;Database=MAS_UYG;USER ID=SA;PWD=123;");
                        DataTable dtcumle = new DataTable();
                        cumle.Fill(dtcumle);

                        using (ExcelPackage pck = new ExcelPackage(new FileInfo(@"C:\CEMAL\" + RaporAdi + ".xlsx")))
                        {
                            //if (File.Exists(@"C:\CEMAL\" + RaporAdi + ".xlsx"))
                            //{
                            //    // ws = pck.Workbook.Worksheets.Copy(DateTime.Now.ToShortDateString(), @"C:\CEMAL\" + RaporAdi + "" + DateTime.Now.ToShortTimeString() + ".xlsx");
                            //    File.Delete(@"C:\CEMAL\" + RaporAdi + ".xlsx");
                            //    // ExcelPackage pcks = new ExcelPackage(new FileInfo(@"C:\CEMAL\" + RaporAdi + ".xlsx"));
                            //}
                            ExcelWorksheet ws = pck.Workbook.Worksheets.Add(RaporAdi + " " + DateTime.Now.TimeOfDay);
                            ws.Cells["A1"].LoadFromDataTable(dtcumle, true);
                            pck.Save();
                            EventLog.WriteEntry("Save bitti Calisti", EventLogEntryType.Information);

                        }
                    }
                }
            }
        }
    }
}
<pre><code>

最肯定的是一件事。如果您在IIS中运行服务,则需要为其分配一个线程池,该线程池具有足够的权限访问SQL、“保存在excel文件SQL查询”和“然后将其发送到邮件”。

我们可以提供帮助,我们只需查看代码即可。您如何尝试通过您的服务访问数据库?到目前为止你都试了些什么?你不需要征得许可就可以提问。继续并发布相关代码,描述您认为它不起作用的指示(包括任何特定的错误消息和异常信息),等等。它在EventLog.WriteEntry(“dtservice Calisti”,EventLogEntryType.information)中循环;您得到的异常是什么?我认为eventlog viewer的错误是:特定于应用程序的权限设置没有为具有CLSID{6DF8CB71-153B-4C66-8FC4-E59301B8011B}和APPID{961AD749-64E9-4BD5-BCC8-ECE8BA0E241F}的COM服务器应用程序授予本地激活权限从应用程序容器中运行的地址LocalHost(使用LRPC)发送到用户NT SERVICE\SQL Server分布式重播客户端SID(S-1-5-80-3249811479-2167633679-2115734285-1138413726-166979568)不可用SID(不可用)。可以使用组件服务管理工具修改此安全权限。