Click here to Skip to main content
15,896,063 members
Articles / Database Development / SQL Server

Ready-to-use Mass Emailing Functionality with C#, .NET 2.0, and Microsoft® SQL Server 2005 Service Broker

Rate me:
Please Sign up or sign in to vote.
4.84/5 (40 votes)
7 Sep 200613 min read 298.9K   4.6K   210  
This paper demonstrates an extensible mass emailing framework (Smart Mass Email SME). The demo implementation uses cutting edge .NET technologies available today such as C#, .NET 2.0, Microsoft® SQL Server 2005 Service Broker, MS Provider Pattern, Enterprise Library January 2006 etc.
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Globalization;
using System.Configuration;
using System.IO;
using System.Configuration.Install;
using SmartMassEmail;
using SmartMassEmail.Providers;
using SmartMassEmail.Entities;
namespace SmartMassEmail.Sql2005.Service
{
	public class Sql2005Service : System.ServiceProcess.ServiceBase
	{
		/// <summary> 
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public Sql2005Service()
		{
			// This call is required by the Windows.Forms Component Designer.
			InitializeComponent();

			// TODO: Add any initialization after the InitComponent call
		}


		/// <summary>
		/// Runs the service.
		/// </summary>
		private static void Run()
		{
			// instantiate and run service
			ServiceBase.Run(
				new ServiceBase[] { new Sql2005Service() });
		}

		// The main entry point for the process
		static void Main(string[] args)
		{
			string opt = null;
			// check for arguments
			if (args.Length > 0)
			{ 
				opt = args[0];
				if(opt!=null && opt.ToLower()=="/install")
				{
					TransactedInstaller ti= new TransactedInstaller();
					ProjectInstaller pi = new ProjectInstaller();
					ti.Installers.Add(pi);
					String path=String.Format("/assemblypath={0}",
						System.Reflection.Assembly.GetExecutingAssembly().Location);
					String[] cmdline={path};
					InstallContext ctx = new InstallContext("",cmdline);			 
					ti.Context =ctx;				 		
					ti.Install(new Hashtable());
				}
				else if (opt !=null && opt.ToLower()=="/uninstall")
				{
					TransactedInstaller ti=new TransactedInstaller();
					ProjectInstaller mi=new ProjectInstaller();
					ti.Installers.Add(mi);
					String path = String.Format("/assemblypath={0}",
						System.Reflection.Assembly.GetExecutingAssembly().Location);
					String[] cmdline={path};
					InstallContext ctx = new InstallContext("",cmdline);
					ti.Context=ctx;
					ti.Uninstall(null);
			 
				}				
				if(opt==null)  // e.g. ,nothing on the command line
				{
					System.ServiceProcess.ServiceBase[] ServicesToRun;
					ServicesToRun = new System.ServiceProcess.ServiceBase[] { new Sql2005Service() };
					System.ServiceProcess.ServiceBase.Run(ServicesToRun);
				}
			}
			else // no arguments, just run
				Run();
		}


		#region Component Designer generated code
		/// <summary> 
		/// Required method for Designer support - do not modify 
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			// 
			// Sql2005Service
			// 
			//this.ServiceName = "SmartMassEmailSql2005Service";
			components = new System.ComponentModel.Container();
			this.ServiceName = "SmartMassEmailSql2005Service";

		}
		#endregion

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing ) 
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}
		
		JobRunning jRun = JobRunning.Instance();


		/// <summary>
		/// Set things in motion so your service can do its work.
		/// </summary>
		protected override void OnStart(string[] args)
		{
			// TODO: Add code here to start your service.
			jRun = JobRunning.Instance();
			InitializeConfigs();
			InitializeTimer();
			timer.Enabled = true;

		}
 
		/// <summary>
		/// Stop this service.
		/// </summary>
		protected override void OnStop()
		{
			// TODO: Add code here to perform any tear-down necessary to stop your service.
			timer.Enabled = false;
			jRun.IsRunning = false;

			
		}

		

		


		#region Custom Methods
		protected System.Timers.Timer timer;
		protected void InitializeConfigs()
		{
			try
			{
			}
			catch (Exception x)
			{
			}

			
		}
		
		
		protected void InitializeTimer()
		{
			//if (timer == null)
					
			timer = new System.Timers.Timer();
			timer.AutoReset = true;
			timer.Interval = ReadAppSettingInterval();
			timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
		}

		protected double ReadAppSettingInterval()
		{
			double interval = 60000, tempInterval; //initialize to 1 minutes.
			if (ConfigurationSettings.AppSettings != null && 
				ConfigurationSettings.AppSettings["IntervalMinutes"] != null)
			{
				string intervalMin;
				intervalMin =ConfigurationSettings.AppSettings["IntervalMinutes"];
				if (Double.TryParse(intervalMin, NumberStyles.Any,
					NumberFormatInfo.InvariantInfo, out tempInterval))
					interval = tempInterval * 60000;
			}
			return interval;			
		}

		

		
		private void timer_Elapsed(object source,System.Timers.ElapsedEventArgs e)
		{
			if (!jRun.IsRunning)
			{
				try
				{
					jRun.IsRunning = true;
                    DequeueEmail();
				}
				finally
				{
					jRun.IsRunning = false;
				}
			}
			else
			{
				//jRun.No = jRun.No + 1;
			}

			

		}
        private void DequeueEmail( )
        {
            TList<EmailMessage> list = EmailDeQueue.Recieve();
            EmailDispatch.Dispatch(list);
        }   
		#endregion

	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Australia Australia
I have been awarded MVP (Visual C#) for year 2007, 2008, 2009. I am a Microsoft Certified Application Developer (C# .Net). I currently live in Melbourne, Australia. I am a co-founder and core developer of Pageflakes www.pageflakes.com and Founder of Simplexhub, a highly experienced software development company based in Melbourne Australia and Dhaka, Bangladesh. Simplexhub.
My BLOG http://www.geekswithblogs.net/shahed
http://msmvps.com/blogs/shahed/Default.aspx.

Comments and Discussions