ASPbee

ASPbee

  • NA
  • 40
  • 36k

Automatic Email&SMS Scheduling thru windows service

May 2 2011 10:05 PM
Hi,

  I created the below webservice to automatically schedule the email & SMS sending depending on the option selected by the user. But now when the service is started i am able to receive the emails to the email address as desired but unfortunately unable to receive SMS text. Could someone help me with this.

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Net.Mail;
using System.Net.Mime;
using System.ServiceProcess;
using System.Threading;
using System.Timers;
using System.Text;

namespace ExampleHawk
{
public enum TimerType
{
System,
SystemThreading,
None
}

public partial class MailHawk : ServiceBase
{
private bool DebugMailSending=true;
int TimerDuration; // 60000 = 1 minute
TimerType tmrType = TimerType.SystemThreading;
System.Threading.Timer tmrThrdMain;
System.Timers.Timer tmrSysMain;
string strVersion;

public MailHawk()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionOcurred);
InitializeComponent();
strVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
this.AutoLog = true;
this.CanPauseAndContinue=true;
this.CanStop=true;
}

protected override void OnStart(string[] args)
{
//DebugMailSending = Convert.ToBoolean("DebugMailSending");
StringBuilder sbStartupMessage = new StringBuilder();
sbStartupMessage.AppendFormat("{0} started version={1}", this.ServiceName, strVersion);
if (tmrType != TimerType.None) sbStartupMessage.AppendFormat("; Timer Interval={0}ms TimerType={1}", TimerDuration, tmrType.ToString());
DebugMessage(sbStartupMessage.ToString());
TimerDuration = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["PollingDuration"]);
switch (tmrType)
{
case TimerType.System:
tmrSysMain.Interval = TimerDuration;
tmrSysMain.Enabled = true;
tmrSysMain.Elapsed += new ElapsedEventHandler(tmrMain_Elapsed);
tmrSysMain.Start();
break;
case TimerType.SystemThreading:
tmrThrdMain = new System.Threading.Timer(tmrThrdMain_Elapsed, null, 0, TimerDuration);
break;
case TimerType.None:
break;
default:
break;
}
} // end OnStart

private void AlertsSend()
{
DataTable dtEmails;
string DBConnect;
try
{
DBConnect = System.Configuration.ConfigurationSettings.AppSettings["ExampleDB"];
dtEmails = DataTableMaker(DBConnect, "AlertsSendNow");
} // end try
catch (Exception exc1)
{
DebugException(exc1,"AlertSend Exception");
return;
} // end catch

int KeyTraxDeliveryDetail = 0;
// KeyTraxDeliveryDetail, KeyParticipant,TraxIterId,FollowUpCount,DateSend,Subject,Message1,Message2,AlertMethod,AlertPath,DateSent
for (int RowCounter = 0; RowCounter < dtEmails.Rows.Count; RowCounter++)
{
try
{
KeyTraxDeliveryDetail = ((int)dtEmails.Rows[RowCounter]["KeyTraxDeliveryDetail"]);
string Subject = dtEmails.Rows[RowCounter]["Subject"].ToString();
string AlertPath = dtEmails.Rows[RowCounter]["AlertPath"].ToString().ToLower();
string AlertMethod = dtEmails.Rows[RowCounter]["AlertMethod"].ToString().ToLower();
string From = dtEmails.Rows[RowCounter]["MessageFrom"].ToString();
// todo need to know which I am sending Message1 or Message2....
string Body = dtEmails.Rows[RowCounter]["Body"].ToString();

bool SMSDestination = false;
switch (AlertMethod)
{
case "phone":
SMSDestination = true;
break;
case "email":
SMSDestination = false;
break;
}
Exception excMailSent = null;
bool MailSentSuccess = MailSend(SMSDestination, From, AlertPath, Subject, Body, ref excMailSent);
if (MailSentSuccess)
DataUpdateMailStatus(DBConnect, KeyTraxDeliveryDetail, "Sent", "");
else
DataUpdateMailStatus(DBConnect, KeyTraxDeliveryDetail, "Error", excMailSent.ToString());
} // end try

catch (Exception exc1)
{
DebugException(exc1,"DataUpdateMailStatus Exception");
DataUpdateMailStatus(DBConnect, KeyTraxDeliveryDetail, "Error", exc1.Message);
} // end catch
} // end for 

} // end AlertsSend

private DataTable DataTableMaker(string strConn, string strSQL)
{
SqlConnection conn = null;
try
{
DataTable dt1 = new DataTable("temp");
conn = new SqlConnection(strConn);
SqlDataAdapter Adapter = new SqlDataAdapter(strSQL, conn);
Adapter.Fill(dt1);
return (dt1);
}
catch (Exception exc1)
{
DebugException(exc1, "DataTableMaker Exception");
return null;
}
finally
{
DisposeIfNotNull(conn);
}

} // end DataTableMaker

private void DataUpdateMailStatus(string strConn, int parmKeyTraxDeliveryDetail, string parmDeliveryStatus, string parmDeliveryDetails)
{
SqlConnection conn = null;
try
{
conn = new SqlConnection(strConn);
conn.Open();
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = conn;
sqlCmd.Parameters.AddWithValue("@KeyTraxDeliveryDetail", parmKeyTraxDeliveryDetail);
sqlCmd.Parameters.AddWithValue("@DeliveryStatus", parmDeliveryStatus);
sqlCmd.Parameters.AddWithValue("@DeliveryDetails", parmDeliveryDetails);
sqlCmd.CommandText = "AlertSentStatus";
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.ExecuteNonQuery();
}
catch (Exception exc1)
{
DebugException(exc1, "DataUpdateMailStatus Exception");
}
finally
{
DisposeIfNotNull(conn);
}

} // end DataUpdateMailStatus

private void DebugException(Exception parmExc, string parmMsg)
{
StringBuilder sbMsgForEventLog = new StringBuilder();
sbMsgForEventLog.AppendFormat("{0} version={1}", this.ServiceName, strVersion);
sbMsgForEventLog.AppendLine();
sbMsgForEventLog.Append(parmMsg);
if(parmExc!=null)
{
sbMsgForEventLog.Append(parmExc.ToString());
sbMsgForEventLog.AppendLine();
}
Debug.WriteLine(sbMsgForEventLog.ToString());
EventLog.WriteEntry("ExampleHawk",sbMsgForEventLog.ToString());
} // end DebugException

private void DebugMessage(string parmMsg)
{
Debug.WriteLine(parmMsg);
}

private void DisposeIfNotNull(IDisposable parmObject)
{
if (parmObject == null) return;
parmObject.Dispose();
}

void ExceptionOcurred(object s, UnhandledExceptionEventArgs args)
{
Exception exc1 = (Exception)args.ExceptionObject;
DebugException(exc1, "Exception Occured");
}


private bool MailSend(bool SMS,string EmailFrom, string EmailTo, string EmailSubject, string EmailBody,ref Exception parmExc)
{
MailMessage msg=null;
try
{
msg = new MailMessage(EmailFrom, EmailTo, EmailSubject, EmailBody);
if (!SMS)
{
msg.IsBodyHtml = false;
}
SmtpClient client = new SmtpClient("localhost");
client.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
client.Send(msg);
if (DebugMailSending)
{
StringBuilder sbMailSendDebug = new StringBuilder();
sbMailSendDebug.AppendFormat("EMail Sent => From={0};To={1};Subject={2};Body={3}", EmailFrom, EmailTo, EmailSubject, EmailBody);
DebugMessage(sbMailSendDebug.ToString());
}
parmExc = null;
return true;
}
catch (Exception exc1)
{
parmExc = exc1;
return false;
}
finally
{
DisposeIfNotNull(msg);
}
} // end MailSend

protected override void OnPause()
{
base.OnPause();
switch (tmrType)
{
case TimerType.System:
tmrSysMain.Enabled = false;
break;
case TimerType.SystemThreading:
tmrThrdMain.Change(Timeout.Infinite, Timeout.Infinite); // the same as pause
break;
} // end switch
} // end OnPause


protected override void OnContinue()
{
switch (tmrType)
{
case TimerType.System:
tmrSysMain.Enabled = true;
break;
case TimerType.SystemThreading:
tmrThrdMain.Change(0, TimerDuration);
break;
} // end switch
} // end OnContinue

protected override void OnStop()
{
base.OnStop();
// tmrMain.Enabled = false;
} // end OnStop

private void tmrDoWork()
{
AlertsSend();
} // end void tmrDoWork


private void tmrThrdMain_Elapsed(object state)
{
DebugMessage("tmrThrdMain System.Threads.Timer called");
tmrDoWork();
}


void tmrMain_Elapsed(object sender, ElapsedEventArgs e)
{
DebugMessage("tmrDoWork System.Timer called");
tmrDoWork();
} // end void tmrMain_Elapsed(object sender, ElapsedEventArgs e)

} // end class
} // end namespace

Answers (3)