views:

233

answers:

3

I have created the following C# windows service to send email to all the subscribed users of my asp.net 3.5(C#) website, daily and/or weekly depending upon their subscription type.

using System;
using System.Security;
using System.Web;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Net.Mail;
using System.Data.SqlClient;
using System.Configuration;
using System.Threading;
using System.Timers;
using System.Runtime.Remoting.Messaging;

namespace AutoEmailService
{
    public partial class AutoEmailService : ServiceBase
    {
        private System.ComponentModel.IContainer components = null;
        private System.Timers.Timer Timer;
        public AutoEmailService()
        {
            InitializeComponent();   <-- this one
        }

        // The main entry point for the process
        static void Main()
        {
            System.ServiceProcess.ServiceBase[] ServicesToRun;
            ServicesToRun = new System.ServiceProcess.ServiceBase[] 
            {
                new AutoEmailService()
            };
            ServiceBase.Run(ServicesToRun);
        }

        private void InitializeComponent()
        {
            this.Timer = new System.Timers.Timer();
            ((System.ComponentModel.ISupportInitialize)(this.Timer)).BeginInit();
            this.Timer.Interval = 60000;
            this.Timer.Elapsed += new System.Timers.ElapsedEventHandler(this.Timer_Elapsed);
            this.ServiceName = "AutomaticEmailService";
            ((System.ComponentModel.ISupportInitialize)(this.Timer)).EndInit();
        }
        /// <summary>
        /// Clean up any resources being used. 
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose(); <-- this
                }
            }
            base.Dispose(disposing);
        }

        protected override void OnStart(string[] args)
        {
            this.Timer.Enabled = true;
            LogMessage.LogMessages("Service Started"); <-- this
        }

        protected override void OnStop()
        {
            Timer.Enabled = false;
            LogMessage.LogMessages("Service Stopped"); <-- this
        }

        // Respond to the Elapsed event of the timer control 
        private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //add a log entry to windows log to check windows service current position/activity
            LogMessage.LogMessages("Service Running"); <-- this
            if (DateTime.Now.ToString("hh tt") == "05 PM")
            {
                List DailySubscription = new List();
                DataSet dataset = new DataSet();
                DataSet ArticlesDataSet = new DataSet();
                int subscriptionType = 0;
                string strArticleHeading = null;
                DateTime currentDate = DateTime.Now.Date;

                //Get all the subscribed users
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("SELECT SubType, Email FROM ArticleSubscription WHERE SubType > 0", Conn);
                sqlDataAdapter.Fill(dataset);

                //Seprate users on the bases of their subscription type 
                foreach (DataRow dr in dataset.Tables[0].Rows)
                {
                    subscriptionType = Convert.ToInt32(dr["SubType"].ToString());
                    if (subscriptionType == 1 || subscriptionType == 3)
                    {
                        DailySubscription.Add(dr["Email"].ToString());
                    }
                }

                // get all today's articles 
                SqlDataAdapter sqlArticlesDataAdapter = new SqlDataAdapter();
                SqlCommand Command = new SqlCommand("SELECT articleheading FROM Articles WHERE postedDate %LIKE% @currentDate", Conn);
                Command.Parameters.Add("@currentDate", SqlDbType.NVarChar);
                Command.Parameters["@currentDate"].Value = DateTime.Now.Date;
                sqlArticlesDataAdapter.SelectCommand = Command;
                sqlArticlesDataAdapter.Fill(dealsDataSet);

                //copy all the articles to a string 
                foreach (DataRow dr in dealsDataSet.Tables[0].Rows)
                {
                    strArticleHeading = strArticleHeading + dr["articleheading"].ToString();
                }

                //send emails to all subscribers 
                foreach (string email in DailySubscription)
                {
                    MailMessage mail = new MailMessage(); mail.From = new MailAddress("[email protected]", "My Web Site");
                    mail.To.Add(new MailAddress(email.ToString()));
                    mail.Subject = "Today's Articles";
                    mail.IsBodyHtml = true;
                    mail.Body = strArticleHeading;
                    System.Net.Mail.SmtpClient SmtpMail = "IP Address";
                    SmtpMail.Send(mail); <-- this
                }
            }

            if (DateTime.Now.ToString("hh tt") == "07 PM" && DateTime.Now.DayOfWeek.ToString("dddd") == "Friday")
            {
                List WeeklySubscription = new List();
                DataSet dataset = new DataSet();
                int subscriptionType = 0;
                DataSet articlesDataSet = new DataSet();
                string strArticleHeading = null;

                //Get all the subscribed users
                SqlDataAdapter sqlDataAdapter = new SqlDataAdapter("SELECT SubType, Email FROM ArticleSubscription WHERE SubType > 0", Conn);
                sqlDataAdapter.Fill(dataset);

                //Seprate users on the bases of their subscription type 
                foreach (DataRow dr in dataset.Tables[0].Rows)
                {
                    subscriptionType = Convert.ToInt32(dr["SubType"].ToString());
                    if (subscriptionType == 2 || subscriptionType == 3)
                    {
                        WeeklySubscription.Add(dr["Email"].ToString());
                    }
                }

                // get all articles of this week 
                SqlDataAdapter sqlArticlesDataAdapter = new SqlDataAdapter();
                SqlCommand Command = new SqlCommand("SELECT articleheading FROM Articles WHERE postedDate >= @currentDate", Conn);
                Command.Parameters.Add("@currentDate", SqlDbType.NVarChar);
                Command.Parameters["@currentDate"].Value = DateTime.Now.Date.AddDays(-7);
                sqlArticlesDataAdapter.SelectCommand = Command;
                sqlArticlesDataAdapter.Fill(articlesDataSet);

                //copy all the articles to a string 
                foreach (DataRow dr in dealsDataSet.Tables[0].Rows)
                {
                    strArticleHeading = strArticleHeading + dr["articleheading"].ToString();
                }

                //send emails to all subscribers 
                foreach (string email in WeeklySubscription)
                {
                    MailMessage mail = new MailMessage();
                    mail.From = new MailAddress("[email protected]", "My Web Site");
                    mail.To.Add(new MailAddress(email.ToString()));
                    mail.Subject = "This week's Articles";
                    mail.IsBodyHtml = true;
                    mail.Body = strArticleHeading;
                    System.Net.Mail.SmtpClient SmtpMail = "IP Address";
                    SmtpMail.Send(mail); <-- this
                }
            }
        }
    }
}

I have marked the lines with <-- this where errors occured and those errors description is as follows

  1. The call is ambiguous between the following methods or properties AutoEmailService.AutoEmailService.InitializeComponent() and AutoEmailService.AutoEmailService.InitializeComponent()

  2. The name LogMessage does not exist in the current context.

  3. components this member is defined more than once. Error: Ambiguity between AutoEmailService.AutoEmailService.components and AutoEmailService.AutoEmailService.components

  4. SmtpMail does not exist in this context. These are the errors and their description that this window service have. If anybody knows their correction please let me know about that.

Also let me know that what will be the smtp settings for this windows service as it is going to run on a dedicated server. Furthermore If anyone figures out any other logical as well as programmatic bug/error in this windows service, please also let me know about that. Actually this is the first windows service I have ever made so I want you people to manually debug it with me.

+1  A: 

Try formatting your code. Other than that:

System.Net.Mail.SmtpClient SmtpMail = "IP Address";

You are trying to assign a string to a variable of type SmtpClient.

Darin Dimitrov
+3  A: 

Here's your answers.

  1. Since you've declared a partial class, my guess is that the Visual Studio editor has declared a .Designer.cs file for you, with both components, Dispose, and InitializeComponents. You need to figure out why you added them yourself, and decide whether to keep the ones you added, or use the ones the designer added for you. This will take care of the ambiguous code.
  2. The SmtpMail class is located in the System.Web.Mail namespace, since you don't have that in your using-directives at the top of your code, the compiler can't find it. Add the correct using statement.
  3. LogMessage I have no idea what is, my guess it is a class you have in your project, see if you need to add a using-directive for that as well.
  4. Settings for the smtp sending for a dedicated server, the only person who can tell you that is the person that configured the server. Perhaps there is an SMTP service running locally, in which case you probably want to set your ip address as localhost, but you might need to authenticate with it.

Also, here's a general hint when you ask questions (on Stack Overflow and other places). Try to be as specific as possible. Dumping a whole file of code, listing 4+ problems, and then closing your question with "Furthermore If anyone figures out any other logical as well as programmatic bug/error in this windows service" will almost guarantee you that few people will look at it. Also, learn how to format code and lists properly, the less time you spend ensuring the quality of your question is good, the less time people will invest in helping you with it.

Lasse V. Karlsen
Reflection regarding 2: I always thought `System.Net.Mail` replaced the `System.Web.Mail` namespace. Can't remember where I read it though, I guess both work.. On msdn, `System.Net.Mail` seems newer (and has that new namespace smell about it). :-)
Patrick
Yeah, could be, I don't use either, I just wasn't really motivated to go hunting for the correct way to send email through C#.
Lasse V. Karlsen
A: 

This ERROR CODE:

//send emails to all subscribers 
            foreach (string email in DailySubscription)
            {
                MailMessage mail = new MailMessage(); mail.From = new MailAddress("[email protected]", "My Web Site");
                mail.To.Add(new MailAddress(email.ToString()));
                mail.Subject = "Today's Articles";
                mail.IsBodyHtml = true;
                mail.Body = strArticleHeading;
                System.Net.Mail.SmtpClient SmtpMail = "IP Address";
                SmtpMail.Send(mail); <-- this
            }

Here I would recommend to use the SendAsync method since you are using the same thread and the operation will wait until the email is delivered, if you loop and the email has not been delivered yet you will get and error.-

Check that and let me know, I had the same issue.

Hope this helps!

MRFerocius
I have used this SendAsync method and install this windows service on my local machine , but it isn't sending any email/s.
nzahra