Updating Mail sub functions to 2.0
Horribly under-tested ; however fixes the warnings for System.Web.Mail....
Code is for Stock GCN / CSK 1.x (No other Mods - so if you have any of the MODs I have written in the past you may need to slightly tweak)....
please post any corrections to this thread...
NotifyUtility.cs
namespace Cavalia {
using System;
using System.Data;
using System.Data.SqlClient;
//Was System.Web.Mail;
using System.Net.Mail;
using Cavalia;
//*********************************************************************
//
// NotifyUtility Class
//
// Contains static methods for working with notification
// emails.
//
//*********************************************************************
public class NotifyUtility {
//*********************************************************************
//
// GetNotificationStatus Method
//
// Returns true if the user is receiving notifications for
// this section or content page.
//
//*********************************************************************
public static bool GetNotificationStatus(int contentPageID, int sectionID, string username) {
SqlConnection conPortal = new SqlConnection(CommunityGlobals.ConnectionString);
SqlCommand cmd = new SqlCommand("Community_NotifyGet", conPortal);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@communityID", CommunityGlobals.CommunityID);
cmd.Parameters.AddWithValue("@sectionID", sectionID);
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@contentPageID", contentPageID);
cmd.Parameters.Add("@status", SqlDbType.Bit).Direction = ParameterDirection.Output;
conPortal.Open();
cmd.ExecuteNonQuery();
bool result = (bool)cmd.Parameters["@status"].Value;
conPortal.Close();
return result;
}
//*********************************************************************
//
// UpdateNotificationStatus Method
//
// Updates user notification status in the database.
//
//*********************************************************************
public static void UpdateNotificationStatus(int contentPageID, int sectionID, string username, bool status) {
SqlConnection conPortal = new SqlConnection(CommunityGlobals.ConnectionString);
SqlCommand cmd = new SqlCommand("Community_NotifyUpdate", conPortal);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@communityID", CommunityGlobals.CommunityID);
cmd.Parameters.AddWithValue("@sectionID", sectionID);
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@contentPageID", contentPageID);
cmd.Parameters.AddWithValue("@status", status);
conPortal.Open();
cmd.ExecuteNonQuery();
conPortal.Close();
}
//*********************************************************************
//
// SendNotifications Method
//
// Sends notification emails to interested users.
//
//*********************************************************************
public static void SendNotifications(int sectionID, int contentPageID, string contentTitle, string username) {
NotifyFormatInfo formatInfo = new NotifyFormatInfo();
string mailSubject;
string mailBody;
//Removed - no longer required
//MailMessage mailMessage = null;
// Get the notification message
MessageInfo notifyEmail = MessageUtility.GetMessage("Email Notification");
// Get the Smtp server
string smtpServer = CommunityGlobals.SmtpServer;
// Get base url
string baseUrl = CommunityGlobals.ResolveAbsoluteUrl(CommunityGlobals.AppPath);
// Set common format info properties
formatInfo.EditProfileLink = baseUrl + "/Users_EditProfile.aspx";
formatInfo.SectionName = SectionUtility.GetSectionNameFromID(sectionID);
formatInfo.ContentLink = CommunityGlobals.ResolveAbsoluteUrl(ContentPageUtility.CalculateContentPath(sectionID, contentPageID));
formatInfo.ContentTitle = contentTitle;
// Get the notifications
SqlConnection conPortal = new SqlConnection(CommunityGlobals.ConnectionString);
SqlCommand cmdGet = new SqlCommand("Community_NotifySendNotifications", conPortal);
cmdGet.CommandType = CommandType.StoredProcedure;
cmdGet.Parameters.AddWithValue("@communityID", CommunityGlobals.CommunityID);
cmdGet.Parameters.AddWithValue("@sectionID", sectionID);
cmdGet.Parameters.AddWithValue("@contentPageID", contentPageID);
conPortal.Open();
SqlDataReader dr = cmdGet.ExecuteReader();
while (dr.Read()) {
mailSubject = notifyEmail.Title;
mailBody = notifyEmail.Body;
formatInfo.Username = (string)dr["user_username"];
//Mail routine Replacement
using (MailMessage message = new MailMessage("notify@" + CommunityGlobals.PrimaryDomain, (string)dr["User_Email"], FormatEmail(formatInfo, mailSubject), FormatEmail(formatInfo, mailBody)))
{
//This can be expanded to use the users's profile settings
message.IsBodyHtml = true;
SmtpClient mailClient = new SmtpClient();
mailClient.Host = smtpServer;
mailClient.UseDefaultCredentials = true;
mailClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
//Send delivers the message to the mail server
mailClient.Send(message);
}
/*
//Replaced with code above
mailMessage = new MailMessage();
mailMessage.From = "notify@" + CommunityGlobals.PrimaryDomain;
mailMessage.To = (string)dr["User_Email"];
mailMessage.Subject = FormatEmail(formatInfo, mailSubject);
mailMessage.Body = FormatEmail(formatInfo, mailBody);
SmtpMail.SmtpServer = smtpServer;
SmtpMail.Send(mailMessage); */
}
conPortal.Close();
}
//*********************************************************************
//
// FormatEmail Method
//
// Formats notification email.
//
//*********************************************************************
public static string FormatEmail(NotifyFormatInfo formatInfo, string text) {
// Perform replacements
text = text.Replace("<Username>", formatInfo.Username);
text = text.Replace("<EditProfileLink>", formatInfo.EditProfileLink);
text = text.Replace("<SectionName>", formatInfo.SectionName);
text = text.Replace("<ContentLink>", formatInfo.ContentLink);
text = text.Replace("<ContentTitle>", formatInfo.ContentTitle);
return text;
}
//*********************************************************************
//
// NotifyUtility Constructor
//
// Private constructor in the case of a class with static methods.
//
//*********************************************************************
private NotifyUtility() {}
}
}
-------------------------
EmailUtility.cs
namespace Cavalia {
using System;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using System.Data.SqlClient;
using System.Web;
//Was System.Web.Mail;
using System.Net.Mail;
//*********************************************************************
//
// EmailUtility Class
//
// Contains static utility methods for sending emails.
//
//*********************************************************************
public class EmailUtility {
//*********************************************************************
//
// GetNewsletterStatus Method
//
// Returns the number of newsletters sent and the number of
// newsletters that still need to be sent.
//
//*********************************************************************
public static SqlDataReader GetNewsletterStatus(int newsletterID) {
SqlConnection conPortal = new SqlConnection( CommunityGlobals.ConnectionString );
SqlCommand cmdGet = new SqlCommand( "Community_AdminGetNewsletterStatus", conPortal );
cmdGet.CommandType = CommandType.StoredProcedure;
cmdGet.Parameters.AddWithValue("@communityID", CommunityGlobals.CommunityID);
cmdGet.Parameters.AddWithValue("@newsletterID", newsletterID);
conPortal.Open();
SqlDataReader dr = cmdGet.ExecuteReader();
return dr;
}
//*********************************************************************
//
// SendNewsletter Method
//
// Sends newsletter to all users who requested a newsletter.
//
//*********************************************************************
public static void SendNewsletter
(
int newsletterID,
string subject,
string body,
IsBodyHtml bodyFormat
) {
int status;
string subjectForUser;
string bodyForUser;
// Get the Smtp Server
string smtpServer = CommunityGlobals.SmtpServer;
// Format Subject and Body Text
subject = FormatContentText(subject, bodyFormat);
body = FormatContentText(body, bodyFormat);
// Create connection for updating email status
SqlConnection conStatus = new SqlConnection( CommunityGlobals.ConnectionString );
conStatus.Open();
// Get the users to send email
SqlConnection conNews = new SqlConnection( CommunityGlobals.ConnectionString );
SqlCommand cmdGet = new SqlCommand( "Community_AdminSendNewsletter", conNews );
cmdGet.CommandType = CommandType.StoredProcedure;
cmdGet.Parameters.AddWithValue("@communityID", CommunityGlobals.CommunityID);
cmdGet.Parameters.AddWithValue("@newsletterID", newsletterID);
// Loop through the emails
conNews.Open();
SqlDataReader dr = cmdGet.ExecuteReader();
while (dr.Read()) {
// Update status
status = UpdateNewsletterStatus(conStatus, newsletterID, (int)dr["user_id"]);
if (status == 1)
throw new Exception( "newsletter already sent!");
// Copy the newsletter template
subjectForUser = subject;
bodyForUser = body;
// Format Subject for individual user
subjectForUser = FormatUserText
(
subject,
bodyFormat,
(string)dr["user_username"],
(string)dr["user_password"],
(string)dr["user_firstname"],
(string)dr["user_lastname"]
);
// Format Body for individual user
bodyForUser = FormatUserText
(
body,
bodyFormat,
(string)dr["user_username"],
(string)dr["user_password"],
(string)dr["user_firstname"],
(string)dr["user_lastname"]
);
// Send the newsletter
try {
SendEmail
(
String.Format("news@{0}", CommunityGlobals.PrimaryDomain),
(string)dr["user_email"],
subjectForUser,
bodyForUser,
bodyFormat,
smtpServer
);
} catch (Exception ex) {
ActivityUtility.RecordError("Error sending newsletter", ex);
}
// clear the user copies
subjectForUser = String.Empty;
bodyForUser = String.Empty;
}
conNews.Close();
// Close the update status connection
conStatus.Close();
}
//*********************************************************************
//
// UpdateNewsletterStatus Method
//
// Records the fact that a newsletter has been sent to a user
// so that the newsletter is not emailed twice.
//
//*********************************************************************
private static int UpdateNewsletterStatus
(
SqlConnection connection,
int newsletterID,
int userID
) {
SqlCommand cmdUpdateStatus = new SqlCommand( "Community_AdminUpdateNewsletterStatus", connection );
cmdUpdateStatus.CommandType = CommandType.StoredProcedure;
cmdUpdateStatus.Parameters.AddWithValue("@RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmdUpdateStatus.Parameters.AddWithValue("@communityID", CommunityGlobals.CommunityID);
cmdUpdateStatus.Parameters.AddWithValue("@newsletterID", newsletterID);
cmdUpdateStatus.Parameters.AddWithValue("@userID", userID);
cmdUpdateStatus.ExecuteNonQuery();
return (int)cmdUpdateStatus.Parameters["@RETURN_VALUE"].Value;
}
//*********************************************************************
//
// AddEmail Method
//
// Adds a new email to the Emails table so it can be sent by the timer.
//
//*********************************************************************
// public static void AddEmail
// (
// string from,
// string to,
// string subject,
// string body,
// IsBodyHtml bodyFormat,
// string smtpServer
// ) {
//
// SqlCommand cmdAdd = new SqlCommand( "Community_EmailsAddEmail", connection );
// cmdUpdateStatus.CommandType = CommandType.StoredProcedure;
// cmdUpdateStatus.Parameters.AddWithValue("@RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
// cmdUpdateStatus.Parameters.AddWithValue("@communityID", CommunityGlobals.CommunityID);
//
//
// MailMessage message = new MailMessage();
// message.From = from;
// message.To = to;
// message.Subject = subject;
// message.Body = body;
// message.BodyFormat = bodyFormat;
//
//
// SmtpMail.SmtpServer = smtpServer;
// SmtpMail.Send(message);
//
// }
//
//*********************************************************************
//
// SendEmail Method
//
// Sends a single email.
//
//*********************************************************************
public static void SendEmail
(
string from,
string to,
string subject,
string body,
IsBodyHtml bodyFormat,
string smtpServer
)
//this code replaces previous
{
using (MailMessage message = new MailMessage(from, to, subject, body))
{
message.IsBodyHtml = true;
SmtpClient mailClient = new SmtpClient();
mailClient.Host = smtpServer;
mailClient.UseDefaultCredentials = true;
mailClient.DeliveryMethod = SmtpDeliveryMethod.PickupDirectoryFromIis;
//Send delivers the message to the mail server
mailClient.Send(message);
}
}
//*********************************************************************
//
// SendFormattedEmail Method
//
// Sends a single email with formatting applied to it. For
// example, <Username> is replaced with a username.
//
//*********************************************************************
public static void SendFormattedEmail
(
string from,
MessageInfo messageInfo,
ProfileInfo profileInfo,
string smtpServer
) {
// format the text
messageInfo.Title = FormatUserText
(
messageInfo.Title,
IsBodyHtml.Text,
profileInfo.Username,
profileInfo.Password,
profileInfo.FirstName,
profileInfo.LastName
);
messageInfo.Body = FormatUserText
(
messageInfo.Body,
IsBodyHtml.Text,
profileInfo.Username,
profileInfo.Password,
profileInfo.FirstName,
profileInfo.LastName
);
messageInfo.Body = FormatContentText(messageInfo.Body, IsBodyHtml.Text);
// Send the email
SendEmail
(
from,
profileInfo.Email,
messageInfo.Title,
messageInfo.Body,
IsBodyHtml.Text,
smtpServer
);
}
//*********************************************************************
//
// FormatEmailText Method
//
// Formats email text without sending the email.
//
//*********************************************************************
public static string FormatEmailText
(
string text,
IsBodyHtml bodyFormat,
ProfileInfo profileInfo
) {
// Format Content Text
text = FormatContentText(text, bodyFormat);
// Get and apply user specific formatting
text = FormatUserText
(
text,
bodyFormat,
profileInfo.Username,
profileInfo.Password,
profileInfo.FirstName,
profileInfo.LastName
);
return text;
}
//*********************************************************************
//
// FormatUserText Method
//
// Formats text with user specific information.
//
//*********************************************************************
public static string FormatUserText
(
string text,
IsBodyHtml bodyFormat,
string username,
string password,
string firstName,
string lastName
) {
string matchString;
// Get base url
string baseUrl = CommunityGlobals.ResolveAbsoluteUrl(CommunityGlobals.AppPath);
// Replace username
matchString = Regex.Escape("<Username>");
text = Regex.Replace(text, matchString, username);
// Replace password
matchString = Regex.Escape("<Password>");
text = Regex.Replace(text, matchString, password);
// Replace first name
matchString = Regex.Escape("<FirstName>");
text = Regex.Replace(text, matchString, firstName);
// Replace last name
matchString = Regex.Escape("<LastName>");
text = Regex.Replace(text, matchString, lastName);
// Replace full name
matchString = Regex.Escape("<FullName>");
text = Regex.Replace(text, matchString, firstName + " " + lastName);
// Replace Edit Profile Link
matchString = Regex.Escape("<EditProfileLink>");
if (bodyFormat == IsBodyHtml.Html)
text = Regex.Replace(text, matchString, String.Format("<a href=\"{0}\">{0}</a>", baseUrl + "/Users_EditProfile.aspx"));
else
text = Regex.Replace(text, matchString, baseUrl + "/Users_EditProfile.aspx");
// Replace Home Link
matchString = Regex.Escape("<HomeLink>");
if (bodyFormat == IsBodyHtml.Html)
text = Regex.Replace(text, matchString, String.Format("<a href=\"{0}\">{0}</a>", baseUrl + "/Default.aspx"));
else
text = Regex.Replace(text, matchString, baseUrl + "/Default.aspx");
return text;
}
//*********************************************************************
//
// FormatContentText Method
//
// Formats email text with content specific information.
//
//*********************************************************************
public static string FormatContentText(string text, IsBodyHtml bodyFormat) {
string matchText;
// Replace new articles
matchText = Regex.Escape("<NewArticles>");
if (Regex.IsMatch(text, matchText))
text = Regex.Replace(text, matchText, FormatContentCollection(ContentPageUtility.GetNewContent("Article"), bodyFormat));
// Replace new events
matchText = Regex.Escape("<NewEvents>");
if (Regex.IsMatch(text, matchText))
text = Regex.Replace(text, matchText, FormatContentCollection(ContentPageUtility.GetNewContent("Event"), bodyFormat));
// Replace new books
matchText = Regex.Escape("<NewBooks>");
if (Regex.IsMatch(text, matchText))
text = Regex.Replace(text, matchText, FormatContentCollection(ContentPageUtility.GetNewContent("Book"), bodyFormat));
// Replace new links
matchText = Regex.Escape("<NewLinks>");
if (Regex.IsMatch(text, matchText))
text = Regex.Replace(text, matchText, FormatContentCollection(ContentPageUtility.GetNewContent("Link"), bodyFormat));
// Replace new downloads
matchText = Regex.Escape("<NewDownloads>");
if (Regex.IsMatch(text, matchText))
text = Regex.Replace(text, matchText, FormatContentCollection(ContentPageUtility.GetNewContent("Download"), bodyFormat));
// Replace new photos
matchText = Regex.Escape("<NewPhotos>");
if (Regex.IsMatch(text, matchText))
text = Regex.Replace(text, matchText, FormatContentCollection(ContentPageUtility.GetNewContent("Photo"), bodyFormat));
// Replace new discuss
matchText = Regex.Escape("<NewDiscuss>");
if (Regex.IsMatch(text, matchText))
text = Regex.Replace(text, matchText, FormatContentCollection(ContentPageUtility.GetNewContent("Post"), bodyFormat));
return text;
}
//*********************************************************************
//
// FormatContentCollection Method
//
// Formats a collection of content items (events, articles, etc)
// and returns the formatted string.
//
//*********************************************************************
public static string FormatContentCollection(ArrayList colContent, IsBodyHtml bodyFormat) {
string contentLink;
StringBuilder builder = new StringBuilder();
foreach (ContentInfo _contentInfo in colContent) {
contentLink = ContentPageUtility.CalculateFullContentPath(_contentInfo.SectionID, _contentInfo.ContentPageID);
if (bodyFormat == IsBodyHtml.Html) {
builder.Append("<li>");
builder.AppendFormat("<a href=\"{0}\">{1}</a>", contentLink, _contentInfo.Title);
builder.Append("<br>");
builder.Append(CommunityGlobals.FormatPlainText(_contentInfo.BriefDescription));
builder.Append("<p>");
} else {
builder.AppendFormat("\n{0}", _contentInfo.Title);
builder.AppendFormat("\n {0}", _contentInfo.BriefDescription);
builder.AppendFormat("\n\n {0}", contentLink);
builder.Append("\n ");
}
}
return builder.ToString();
}
//*********************************************************************
//
// EmailUtility Constructor
//
// Use a private constructor for a class with static methods.
//
//*********************************************************************
private EmailUtility() {}
}
}
------------------
Additionally, you need to declare an enum for IsBodyHtml. I created a new class in my conversion and placed all of my enums in it... You could place it directly in the class files listed above..
Example of my enum class
using System;
using System.Collections.Generic;
using System.Text;
namespace Cavalia
{
public enum AllowHtml //SMR- CSK integration
{
None = 0,
Limited = 1,
Full = 2
}
public enum RoleType
{
ViewRole = 0,
AddRole = 1,
EditRole = 2,
DeleteRole = 3,
CommentRole = 4,
RateRole = 5,
ModerateRole = 6
}
//These Roles are used to determine whom may manipulate sections
public enum AdminRoleType
{
MayAddSection = 0,
MayEditSection = 1,
MayDeleteSection = 2,
IsSectionOwner = 3
}
//*********************************************************************
//
// CommunityImageType Enumeration
//
// Represents the image type for a community image.
//
//*********************************************************************
public enum CommunityImageType
{
Global = 0,
Logo = 1,
Topic = 2
}
public enum IsBodyHtml
{
Html = 0,
Text = 1
}
}
-------------------------------------
Again not throughly tested as I was simply trying to get rid of warnings and I intend on re-writing both classes with Project Cavalia... However, figured I would share...
-- jody
My Blogs on .Net 2.0 and Ajaxhttp://csk.wbcb.com
http://ArtbyJody.com