Voila Daniel
Voila Daniel

Reputation: 55

Windows Service C# Database connection problems

I try to make a windows service in C# to send daily automatically emails, based on data read from a specified SQL server database.

I mananged to make the service run, to send email automatically but when I try to insert a sqlconnection service just doesn't work anymore. Any ideas?

It works if I remove SqlConnection and data reader.

Here is my code:

    System.Timers.Timer createOrderTimer;
    public Service1()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        createOrderTimer = new System.Timers.Timer();
        createOrderTimer.Elapsed += new System.Timers.ElapsedEventHandler(GetMail);
        createOrderTimer.Interval = 2500;
        createOrderTimer.Enabled = true;
        createOrderTimer.AutoReset = true;
        createOrderTimer.Start();
    }
    protected override void OnStop()
    {
    }
    public void GetMail(object sender, System.Timers.ElapsedEventArgs args)
    {
        SqlConnection connect = new SqlConnection("Server=10.222.160.17,5356;"  
            + "Database=tracking_tool;"
            + "Trusted_Connection=True;"
            + "user=admin;"
            + "password=root");

        string line = "";
        connect.Open();
        SqlCommand GetData = new SqlCommand("select * from validation", connect);
        SqlDataReader ReadData = null;
        ReadData = GetData.ExecuteReader();

        while (ReadData.Read())
        {

            line = ReadData["Line"].ToString();

        }
        connect.Close();

        MailMessage mailMessage = new MailMessage();
        mailMessage.To.Add("[email protected]");
        mailMessage.From = new MailAddress("[email protected]");
        mailMessage.Subject = "example";
        mailMessage.Body = "example";
        SmtpClient smtpClient = new SmtpClient("10.214.81.97");
        smtpClient.Send(mailMessage);
    }

Upvotes: 0

Views: 6818

Answers (2)

Mohammad Nikravesh
Mohammad Nikravesh

Reputation: 975

Your ConnectionString is wrong. Try this : (just replace your configs)

server={YourSqlInstanceFullName};database={YourDatabaseName};Integrated Security=false;User ID={Database Username};Password={Password}

Upvotes: 0

Rene Gijzemijter
Rene Gijzemijter

Reputation: 87

You are reading data from SQL into variable line, but afterwards you don't do anything with it. My guess is, there is actually nothing wrong. How are you determining that something is not working?

Upvotes: 1

Related Questions