2012-10-09 73 views
0

這裏我目前在我的SQL Server 2008數據庫中有一些日期值。我想在該日期值等於當前日期時將電子郵件警報發送到特定的郵件地址。想象一下自動化的b'day許願軟件。如何使用Windows服務跟蹤數據庫活動

這裏是我使用電子郵件functionality.It的代碼工作沒有任何問題。

private void sendMailMessage() 
     { 
      try 
      { 

       MailMessage myMessage = new MailMessage(); 
       myMessage.From = new MailAddress("[email protected]", "Online Alert System"); 
       myMessage.To.Add(new MailAddress("[email protected]")); 
       myMessage.Subject = "Test Mail"; 
       myMessage.Body = "This is test mail from OAS."; 
       myMessage.IsBodyHtml = true; 


       SmtpClient mySmtpClient = new SmtpClient(); 
       mySmtpClient.Host="smtp.gmail.com"; 
       mySmtpClient.Port= 587; 
       mySmtpClient.Credentials = new NetworkCredential("[email protected]", "password"); 
       mySmtpClient.EnableSsl = true; 
       mySmtpClient.Send(myMessage); 
      } 

      catch (Exception ex) 
      { 
       throw new Exception(ex.Message); 
      } 

     } 

但我想使用widows服務來做到這一點。請解釋我如何做到這一點。在這種情況下,我只對Windows服務知之甚少。

在此先感謝..!

+0

從數據庫中選擇的所有電子郵件地址,其中'則DateValue = CurrentDate'並通過每一個電子郵件地址,你的服務環和發送電子郵件。 –

回答

0
// try the following code 
//in app.config add the following key 
// <add key="starttime" value="00.00"/> 
    public static System.Timers.Timer Timer; 
    Double _timeinterval; 
    public static bool IstimerEnabled = false; 
     protected override void OnStart(string[] args) 
    { 
     try 
     { 
      Timer = new System.Timers.Timer(); 
      string starttime = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["starttime"]); 
      double mins = Convert.ToDouble(starttime); 
      DateTime t = DateTime.Now.Date.AddHours(mins); 
      TimeSpan ts = new TimeSpan(); 
      ts = t.AddDays(1) - System.DateTime.Now; 
      log.WriteEntry("BBPush Service timespan ts--" + ts.ToString()); 
      if (ts.TotalMilliseconds < 0) 
      { 
       ts = t.AddDays(1) - System.DateTime.Now; 
      } 
      _timeinterval = ts.TotalMilliseconds; 
      Timer.Elapsed += new ElapsedEventHandler(OnTimedEvent); 
      Timer.Interval = _timeinterval; 
      Timer.Enabled = true; 

     } 
     catch (Exception ex) 
     { 
      log.WriteEntry("exception :" + ex.ToString()); 

     } 
     finally 
     { 
      IstimerEnabled = false; 
      Timer.Start(); 
     } 
    } 
    protected override void OnStop() 
    { 
     Timer.Stop(); 
     Timer.Dispose(); 

    } 
    private void OnTimedEvent(object source, ElapsedEventArgs e) 
    { 

     // write your code here or call the method that checks the current date with dob in your table ,fetch the matching emailid and call the mail sending method. 
     //after this method timer is set for 24 hrs. 
     Timer.Interval = 86400000; 
    } 
+0

添加一個窗口服務,在視圖代碼有一些事件的OnStart,調用OnStop,OnTimeEvent 我也寫了你。 試試這個代碼,這個服務將在12點執行。我正在使用此代碼在上午12點執行服務,並且它工作正常。如果它有幫助,請標記它。 – Swati