Showing posts with label delegate. Show all posts
Showing posts with label delegate. Show all posts

Tuesday, December 1, 2009

Class for Sending email using Email templates (asynchronously)

using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Net.Mail;

namespace Classes.Miscellaneous
{
///
/// Created by Wilmer F. Pascual
///

public class Email
{
#region Properties
public string Subject { get; set; }
public string From { get; set; }
public string To { get; set; }
public string CC { get; set; }
public bool IsBodyHtml { get; set; }
public System.Collections.Generic.Dictionary BodyParameters { get; set; }
public string ErrorMessage { get; private set; }

const string PARAMETER_FORMAT = "<%{0}%>";
const string XML_Default_Sender_Email = "Default_Sender_Email";
const string XML_SMTP_Server = "SMTP_Server";
const string XML_SMTP_Port = "SMTP_Port";
const string XML_SMTP_User = "SMTP_User";
const string XML_SMTP_Password = "SMTP_Password";
const string ERROR_TEMPLATENOTEXIST = "Template does not exists.";
#endregion

public Email(){}

#region Methods
///
/// Adds a parameter name and value to the BodyParameters collection
///

///
///
public void AddBodyParameter(string parameterName, string parameterValue)
{
if (this.BodyParameters == null)
this.BodyParameters = new System.Collections.Generic.Dictionary();

this.BodyParameters.Add(string.Format(PARAMETER_FORMAT, parameterName), parameterValue);
}

///
/// Send email using the specified Email template
///

/// Path to the email template file
///
public bool Send(string templateFilename)
{
if (!System.IO.File.Exists(templateFilename))
{
throw new ArgumentException(ERROR_TEMPLATENOTEXIST, templateFilename);
}

MailDefinition md = new MailDefinition();
md.BodyFileName = templateFilename;
md.Subject = this.Subject;
if (string.IsNullOrEmpty(this.From))
md.From = Setting.GetSetting(XML_Default_Sender_Email).Value;
else
md.From = this.From;
md.CC = this.CC;
md.IsBodyHtml = this.IsBodyHtml;

System.Net.Mail.MailMessage mailMessage;

Control dummyControl = new Control();//the Control owner parameter is required so i just created a dummy - wfp
mailMessage = md.CreateMailMessage(this.To, this.BodyParameters, dummyControl); //pass the parameter-value collection; the CreateMailMessage will automatically replace the parameters with the value we specify - wfp

string serverSetting = Setting.GetSetting(XML_SMTP_Server).Value;
string portSetting = Setting.GetSetting(XML_SMTP_Port).Value;
string userSetting = Setting.GetSetting(XML_SMTP_User).Value;
string passwordSetting = Setting.GetSetting(XML_SMTP_Password).Value;

SmtpClient smtp = new SmtpClient(serverSetting, Convert.ToInt32(portSetting));
System.Net.NetworkCredential cred = new System.Net.NetworkCredential(userSetting, passwordSetting);
smtp.UseDefaultCredentials = false;
smtp.Credentials = cred;

try
{
//smtp.Send(mailMessage); send email synchronously -- wfp

//send email asynchronously -- wfp
SendEmailDelegate dc = new SendEmailDelegate(smtp.Send);
AsyncCallback cb = new AsyncCallback(this.SendEmailCallback);
IAsyncResult ar = dc.BeginInvoke(mailMessage, cb, null);
//

return true;
}
catch (Exception ex)
{
this.ErrorMessage = ex.Message;
return false;
}
}

#region For Asynchronous Email sending
//delegate for asynchronous sending of email -- wfp
public delegate void SendEmailDelegate(System.Net.Mail.MailMessage mailMessage);

//callback method
public void SendEmailCallback(IAsyncResult ar)
{
SendEmailDelegate del = (SendEmailDelegate)((System.Runtime.Remoting.Messaging.AsyncResult)ar).AsyncDelegate;
try
{
//bool result;
//result = del.EndInvoke(ar);
del.EndInvoke(ar);
//System.Diagnostics.Debug.WriteLine("\nSuccess on Send Email CallBack");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("\nError on Send Email CallBack: " + ex.Message);
}
}
#endregion
#endregion
}
}

Share/Save/Bookmark

Saturday, January 3, 2009

Simple Delegate and Event Implementation Sample


class definition:

public class DelegateAndEvent
{
//it is a good practice to name your delegates with "EventHandler"
public delegate void ErrorEventHandler(DelegateAndEvent sender, ErrorEventArgs args);

//declare event
public event ErrorEventHandler ErrorRaised;

//a better way of returning values is to create a class which inherits the EventArgs class and add the
//desired property(ies)
public class ErrorEventArgs : EventArgs
{
private string _errmsg;
public string ErrorMessage
{
get { return _errmsg; }
set { _errmsg = value; }
}

public ErrorEventArgs() { }
public ErrorEventArgs(string error)
{
_errmsg = error;
}
}

/// Method to allow raising of error (can either be public or private)
public void RaiseError(string error)
{
if (!string.IsNullOrEmpty(error))
{
//check is event is not null (event has a subscriber)
if (ErrorRaised != null)
{
ErrorRaised(this, new ErrorEventArgs(error));
}
}

}
}


code behind:


public partial class _Default : System.Web.UI.Page
{
DelegateAndEvent dne = new DelegateAndEvent();

protected override void OnInit(EventArgs e)
{
base.OnInit(e);
dne.ErrorRaised += new DelegateAndEvent.ErrorEventHandler(dne_ErrorRaised);
}

protected void Page_Load(object sender, EventArgs e)
{
}

protected void btnEvent_Click(object sender, EventArgs e)
{
dne.RaiseError("Error was forced to be raised!");

}

void dne_ErrorRaised(DelegateAndEvent sender, DelegateAndEvent.ErrorEventArgs args)
{
lblError.Text = args.ErrorMessage;
}
}




Share/Save/Bookmark