473,399 Members | 3,919 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

Threading with an object and Session

Hello,

I'm writing a newsletter application which uses backgroundthreading. I'm using Session variable to report on progresswhile it loops through a dataset. The 'Status.aspx' pagerefreshes every 5 seconds while outputing the Session variables.My problem is, once the page redirects to 'Status.aspx' its showthe that's it only gets half through the dataset. If I increaseThread.Sleep to 2000 goes all the way through. I don't get anyerror message, it's like the MailObj disappears once the pageredirects. Do I need to use something like Context.Items.Add ?

Any ideas would be great:)

Gavin Lyons


private void Send_Click(object sender,System.Web.UI.ImageClickEventArgs e)
{
if (Subject.Text!="")
{
string SQLString = "SELECT * FROM Members";
i386.Newsletter.mailer MailObj = new mailer();
MailObj.SMTPhost = "mail.smtp.com";
MailObj.From = From.SelectedValue;
MailObj.Body = Body();
MailObj.Sessions = true;
MailObj.EmailAddressField = "UserID";
MailObj.EmailNameField = "<!--FirstName--> <!--LastName-->";
MailObj.DataSet = i386.DatabaseSystem.GetDataSet(SQLString,"WebConfi gDatabaseConnection");
MailObj.WebContext =(System.Web.HttpContext)Session["WebContext"];

Thread thread = new Thread(new ThreadStart(MailObj.Send));
thread.Priority = ThreadPriority.Lowest;
thread.Start();
Thread.Sleep(500);
Response.Redirect("status.aspx", true);

}
else
Label_Message.Text="Missing data!";
}

public class mailer
{
private string _SMTPhost="localhost";
private string _Body="";
private string _From="";
private string _FromName="";
private string _Subject="";
private string _DatabaseConnection;
private string _EmailAddressField;
private string _EmailNameField;
private System.Web.HttpContext _WebContext;
private DataSet _DataSet;
private bool _Sessions=true;
public string SMTPhost
{
get {return _SMTPhost;}
set {_SMTPhost=value;}
}
public string EmailNameField
{
get {return _EmailNameField;}
set {_EmailNameField=value;}
}
public string EmailAddressField
{
get {return _EmailAddressField;}
set {_EmailAddressField=value;}
}
public string Body
{
get {return _Body;}
set {_Body=value;}
}
public string Subject
{
get {return _Subject;}
set {_Subject=value;}
}
public string From
{
get {return _From;}
set {_From=value;}
}
public string FromName
{
get {return _FromName;}
set {_FromName=value;}
}
public bool Sessions
{
get {return _Sessions;}
set {_Sessions=value;}
}
public DataSet DataSet
{
set {_DataSet=value;}
get {return _DataSet;}
}
public System.Web.HttpContext WebContext
{
set {_WebContext=value;}
get {return _WebContext;}
}
private string ReplaceFields(DataRow DR, string String)
{
string ReplStr = String;
foreach (DataColumn Column in DR.Table.Columns)
{
ReplStr = ReplStr.Replace("<!--" + Column.ToString() + "-->",DR[Column.ToString()].ToString());
}
return ReplStr;
}
public void Send()
{
try
{
#region Initialise Sessions
if (this.Sessions)
{
lock(WebContext.Session.SyncRoot )//lock the session object
{
StringBuilder sb = new StringBuilder(); // for reporting

WebContext.Session["StatusLine"] = "Retrieving data tosend ..";
WebContext.Session["EmailReport"] = sb;
WebContext.Session["EmailCounter"] = "0";
WebContext.Session["TotalEmailsToSend"] =0;
WebContext.Session["Done"] = "false";
WebContext.Session["TotalEmailsToSend"] =this.DataSet.Tables[0].Rows.Count.ToString();
}
}
else
{
WebContext.Response.Write("Retrieving data to send ..");
}
#endregion
// Newsletter Merging
int startAt = Environment.TickCount;
int EmailCounter = 0;
bool TestMode = true;
foreach (DataRow DR in this.DataSet.Tables[0].Rows)
{
#region loop sending

// SMTP stmpobj = new SMTP(this.SMTPhost);
// EmailMessage emailmsg = new EmailMessage();

string BodyForEmail = ReplaceFields(DR, this.Body);
string ToForEmail = DR[this.EmailAddressField].ToString();
string ToNameForEmail = ReplaceFields(DR,this.EmailNameField);
string SubjectForEmail = ReplaceFields(DR, this.Subject);


if (this.Sessions)
{
lock(WebContext.Session.SyncRoot )
{
WebContext.Session[ "StatusLine" ] = "Processing " +ToForEmail;
}
}
try
{
if (!TestMode)
{
//stmpobj.Send(emailmsg)
}
else
{

WebContext.Response.Write("Sending to "+ ToForEmail + "("+ ToNameForEmail + ") " + WebContext.Session[ "StatusLine"].ToString() + "<br/>");
}
if (this.Sessions)
{ // Reporting
((StringBuilder)WebContext.Session["EmailReport"]).Append(EmailCounter+ "," + DR["UserID"].ToString() +
", " + DateTime.Now.ToString() + ", Successful<BR>" );//Reporting
}
}
catch (Exception ErrorMsg)
{
if (this.Sessions)
{ // Reporting
((StringBuilder)WebContext.Session["EmailReport"]).Append(EmailCounter+ "," + DR["UserID"].ToString() +
", " + DateTime.Now.ToString() + ", Failed:" +ErrorMsg.Message + "<BR>" );
}
}
EmailCounter++;
if (this.Sessions)
{
lock(WebContext.Session.SyncRoot)
WebContext.Session[ "EmailCounter" ] = EmailCounter;
}
#endregion
}
#region Sessions Final Values
if (this.Sessions)
{
lock( WebContext.Session.SyncRoot )
{
int ms = Environment.TickCount - startAt;
int seconds = ms/1000;
WebContext.Session[ "SecondsForMailMerge" ] =seconds.ToString();
WebContext.Session["Done"] = true;
WebContext.Session["StatusLine"] = "NewsletterCompleted!";
}
}
#endregion
// this.DataSet.Dispose();
}
catch (Exception ex)
{
#region Session Report with Error
if (this.Sessions)
{
lock(WebContext.Session.SyncRoot )
{
WebContext.Session["MailMergeException"] = ex;
}
}
#endregion
WebContext.Response.Write("Mailer Error:" + ex.Message);
}
}
}
--------------------------------
From: Gavin Lyons

-----------------------
Posted by a user from .NET 247 (http://www.dotnet247.com/)

<Id>f7YLYLMHKUi+IHe+JkwBWg==</Id>
Nov 19 '05 #1
2 2075
A background thread should not access the HttpContext or the Request. Both
of these are invalid once the page is done processing. Have the background
thread post the mail body directly to the session, or to some other global
scope. A subsequent request can then discover and use it.

David

"Gavin Lyons via .NET 247" <an*******@dotnet247.com> wrote in message
news:eZ**************@tk2msftngp13.phx.gbl...
Hello,

I'm writing a newsletter application which uses background threading. I'm
using Session variable to report on progress while it loops through a
dataset. The 'Status.aspx' page refreshes every 5 seconds while outputing
the Session variables. My problem is, once the page redirects to
'Status.aspx' its show the that's it only gets half through the dataset. If
I increase Thread.Sleep to 2000 goes all the way through. I don't get any
error message, it's like the MailObj disappears once the page redirects. Do
I need to use something like Context.Items.Add ?

Any ideas would be great:)

Gavin Lyons


private void Send_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
if (Subject.Text!="")
{
string SQLString = "SELECT * FROM Members";
i386.Newsletter.mailer MailObj = new mailer();
MailObj.SMTPhost = "mail.smtp.com";
MailObj.From = From.SelectedValue;
MailObj.Body = Body();
MailObj.Sessions = true;
MailObj.EmailAddressField = "UserID";
MailObj.EmailNameField = "<!--FirstName--> <!--LastName-->";
MailObj.DataSet = i386.DatabaseSystem.GetDataSet(SQLString,
"WebConfigDatabaseConnection");
MailObj.WebContext = (System.Web.HttpContext)Session["WebContext"];

Thread thread = new Thread(new ThreadStart(MailObj.Send));
thread.Priority = ThreadPriority.Lowest;
thread.Start();
Thread.Sleep(500);
Response.Redirect("status.aspx", true);

}
else
Label_Message.Text="Missing data!";
}

public class mailer
{
private string _SMTPhost="localhost";
private string _Body="";
private string _From="";
private string _FromName="";
private string _Subject="";
private string _DatabaseConnection;
private string _EmailAddressField;
private string _EmailNameField;
private System.Web.HttpContext _WebContext;
private DataSet _DataSet;
private bool _Sessions=true;
public string SMTPhost
{
get {return _SMTPhost;}
set {_SMTPhost=value;}
}
public string EmailNameField
{
get {return _EmailNameField;}
set {_EmailNameField=value;}
}
public string EmailAddressField
{
get {return _EmailAddressField;}
set {_EmailAddressField=value;}
}
public string Body
{
get {return _Body;}
set {_Body=value;}
}
public string Subject
{
get {return _Subject;}
set {_Subject=value;}
}
public string From
{
get {return _From;}
set {_From=value;}
}
public string FromName
{
get {return _FromName;}
set {_FromName=value;}
}
public bool Sessions
{
get {return _Sessions;}
set {_Sessions=value;}
}
public DataSet DataSet
{
set {_DataSet=value;}
get {return _DataSet;}
}
public System.Web.HttpContext WebContext
{
set {_WebContext=value;}
get {return _WebContext;}
}
private string ReplaceFields(DataRow DR, string String)
{
string ReplStr = String;
foreach (DataColumn Column in DR.Table.Columns)
{
ReplStr = ReplStr.Replace("<!--" + Column.ToString() + "-->",
DR[Column.ToString()].ToString());
}
return ReplStr;
}
public void Send()
{
try
{
#region Initialise Sessions
if (this.Sessions)
{
lock(WebContext.Session.SyncRoot )//lock the session object
{
StringBuilder sb = new StringBuilder(); // for reporting

WebContext.Session["StatusLine"] = "Retrieving data to send ..";
WebContext.Session["EmailReport"] = sb;
WebContext.Session["EmailCounter"] = "0";
WebContext.Session["TotalEmailsToSend"] =0;
WebContext.Session["Done"] = "false";
WebContext.Session["TotalEmailsToSend"] =
this.DataSet.Tables[0].Rows.Count.ToString();
}
}
else
{
WebContext.Response.Write("Retrieving data to send ..");
}
#endregion
// Newsletter Merging
int startAt = Environment.TickCount;
int EmailCounter = 0;
bool TestMode = true;
foreach (DataRow DR in this.DataSet.Tables[0].Rows)
{
#region loop sending

// SMTP stmpobj = new SMTP(this.SMTPhost);
// EmailMessage emailmsg = new EmailMessage();

string BodyForEmail = ReplaceFields(DR, this.Body);
string ToForEmail = DR[this.EmailAddressField].ToString();
string ToNameForEmail = ReplaceFields(DR, this.EmailNameField);
string SubjectForEmail = ReplaceFields(DR, this.Subject);
if (this.Sessions)
{
lock(WebContext.Session.SyncRoot )
{
WebContext.Session[ "StatusLine" ] = "Processing " + ToForEmail;
}
}
try
{
if (!TestMode)
{
//stmpobj.Send(emailmsg)
}
else
{

WebContext.Response.Write("Sending to "+ ToForEmail + "(" + ToNameForEmail +
") " + WebContext.Session[ "StatusLine" ].ToString() + "<br/>");
}
if (this.Sessions)
{ // Reporting
((StringBuilder)WebContext.Session["EmailReport"]).Append(EmailCounter+ ","
+ DR["UserID"].ToString() +
", " + DateTime.Now.ToString() + ", Successful<BR>" );// Reporting
}
}
catch (Exception ErrorMsg)
{
if (this.Sessions)
{ // Reporting
((StringBuilder)WebContext.Session["EmailReport"]).Append(EmailCounter+ ","
+ DR["UserID"].ToString() +
", " + DateTime.Now.ToString() + ", Failed:" + ErrorMsg.Message + "<BR>" );
}
}
EmailCounter++;
if (this.Sessions)
{
lock(WebContext.Session.SyncRoot)
WebContext.Session[ "EmailCounter" ] = EmailCounter;
}
#endregion
}
#region Sessions Final Values
if (this.Sessions)
{
lock( WebContext.Session.SyncRoot )
{
int ms = Environment.TickCount - startAt;
int seconds = ms/1000;
WebContext.Session[ "SecondsForMailMerge" ] = seconds.ToString();
WebContext.Session["Done"] = true;
WebContext.Session["StatusLine"] = "Newsletter Completed!";
}
}
#endregion
// this.DataSet.Dispose();
}
catch (Exception ex)
{
#region Session Report with Error
if (this.Sessions)
{
lock(WebContext.Session.SyncRoot )
{
WebContext.Session["MailMergeException"] = ex;
}
}
#endregion
WebContext.Response.Write("Mailer Error:" + ex.Message);
}
}
}
--------------------------------
From: Gavin Lyons

-----------------------
Posted by a user from .NET 247 (http://www.dotnet247.com/)

<Id>f7YLYLMHKUi+IHe+JkwBWg==</Id>
Nov 19 '05 #2
If you need to do the operation asyncronusly then take all the data of
the request and session, populate an object then put this object on a
message queue

Have another application read messages of the queue and process them

Nov 19 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
by: Roberto López | last post by:
Hi, I´m doing an asp.net application that uploads and downloads files and folders between the client and the server on my intranet. To do this I have create threads and it runs Ok but I need to...
2
by: al | last post by:
Greeting, I have this sub in a page that runs a thread to change direction of a page then redirects to a new page(please wait message page)which checks for a global flag and returns to previous...
8
by: MattB | last post by:
Hello I am starting a new thread in a button click event. This thread calls an method which sends emails, I don't want the page to wait for the emails to finish going out as it slows the user...
1
by: Alex Brown | last post by:
We are switching from InProc mode to StateServer mode and have a somewhat unusual problem that I have not seen discussed. Sometime we pass the session object to a thread by reference and the...
4
by: Makarand Keer | last post by:
Hi All I have problem in using Threading. I have ASP.NET application in which I am using multithreading to start a process. Now the object instances which are used in this thread access...
10
by: jt | last post by:
The program works like this: There is a form with a button. When the form is loaded, a separate thread is started which is retreiving/updating data in the database every x seconds. When clicked...
2
by: Jeremy Cowles | last post by:
Hi all, Here is the issue: On postback, I spawn a new thread using the following code: Dim NewThread As New Thread(AddressOf ProcessFile) NewThread.Priority = ThreadPriority.Lowest...
10
by: Janto Dreijer | last post by:
I have been having problems with the Python 2.4 and 2.5 interpreters on both Linux and Windows crashing on me. Unfortunately it's rather complex code and difficult to pin down the source. So...
7
by: darrel | last post by:
This is a long-overdue item on my punch list that I haven't had much time to address in the past. I'm trying to get it off my plate this week. ;o) We have a home-grown CMS that works pretty well....
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.