Search code examples
sqlasp.nethangfire

Null Exception when Job is handled by Hangfire


I have this job to send mail with updated info from SQL every 30 minutes.

 public void SendMail()
{
    StringBuilder sb = new StringBuilder();
    StringBuilder st = new StringBuilder();
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString))
    using (SqlCommand cmd = new SqlCommand("SELECT TITULO, DESTINATARIO FROM DIA", con))
    {
        con.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            sb.AppendLine(reader["TITULO"].ToString());
            st.AppendLine(reader["DESTINATARIO"].ToString());
        }
    }
    SmtpClient smtpClient = new SmtpClient("mysmtpclient.com", 25);
    smtpClient.Credentials = new System.Net.NetworkCredential("________", "_______");
    smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;

    MailMessage mailMessage = new MailMessage("test@test.com", st.ToString());
    mailMessage.Subject = "Documentos próximos do Vencimento";
    mailMessage.Body = "Os seguintes documentos vencem em 5 dias: \n" + sb.ToString();
}

Running directly from my application with button will work finely, when I try to Schedule it with Hangfire using this command:

BackgroundJob.Schedule(() => SendMail(), TimeSpan.FromMinutes(30));

It fails and give me a System.NullReferenceException.

It's maybe because the MailMessage and body were empty, meaning that it failed to retrieve data from the SQL Server table with Hangfire. Any Suggestions?


Solution

  • I think this one :

    BackgroundJob.Schedule(() => <YOUR CLASS>.SendMail(), TimeSpan.FromMinutes(30));
    

    But I thinl <your class> and SendMail() have to be static.