473,659 Members | 2,591 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Threading with an object and Session

Hello,

I'm writing a newsletter application which uses backgroundthrea ding. 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.A dd ?

Any ideas would be great:)

Gavin Lyons


private void Send_Click(obje ct sender,System.W eb.UI.ImageClic kEventArgs e)
{
if (Subject.Text!= "")
{
string SQLString = "SELECT * FROM Members";
i386.Newsletter .mailer MailObj = new mailer();
MailObj.SMTPhos t = "mail.smtp.com" ;
MailObj.From = From.SelectedVa lue;
MailObj.Body = Body();
MailObj.Session s = true;
MailObj.EmailAd dressField = "UserID";
MailObj.EmailNa meField = "<!--FirstName--> <!--LastName-->";
MailObj.DataSet = i386.DatabaseSy stem.GetDataSet (SQLString,"Web ConfigDatabaseC onnection");
MailObj.WebCont ext =(System.Web.Ht tpContext)Sessi on["WebContext "];

Thread thread = new Thread(new ThreadStart(Mai lObj.Send));
thread.Priority = ThreadPriority. Lowest;
thread.Start();
Thread.Sleep(50 0);
Response.Redire ct("status.aspx ", true);

}
else
Label_Message.T ext="Missing data!";
}

public class mailer
{
private string _SMTPhost="loca lhost";
private string _Body="";
private string _From="";
private string _FromName="";
private string _Subject="";
private string _DatabaseConnec tion;
private string _EmailAddressFi eld;
private string _EmailNameField ;
private System.Web.Http Context _WebContext;
private DataSet _DataSet;
private bool _Sessions=true;
public string SMTPhost
{
get {return _SMTPhost;}
set {_SMTPhost=valu e;}
}
public string EmailNameField
{
get {return _EmailNameField ;}
set {_EmailNameFiel d=value;}
}
public string EmailAddressFie ld
{
get {return _EmailAddressFi eld;}
set {_EmailAddressF ield=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=valu e;}
}
public bool Sessions
{
get {return _Sessions;}
set {_Sessions=valu e;}
}
public DataSet DataSet
{
set {_DataSet=value ;}
get {return _DataSet;}
}
public System.Web.Http Context WebContext
{
set {_WebContext=va lue;}
get {return _WebContext;}
}
private string ReplaceFields(D ataRow DR, string String)
{
string ReplStr = String;
foreach (DataColumn Column in DR.Table.Column s)
{
ReplStr = ReplStr.Replace ("<!--" + Column.ToString () + "-->",DR[Column.ToString ()].ToString());
}
return ReplStr;
}
public void Send()
{
try
{
#region Initialise Sessions
if (this.Sessions)
{
lock(WebContext .Session.SyncRo ot )//lock the session object
{
StringBuilder sb = new StringBuilder() ; // for reporting

WebContext.Sess ion["StatusLine "] = "Retrieving data tosend ..";
WebContext.Sess ion["EmailRepor t"] = sb;
WebContext.Sess ion["EmailCount er"] = "0";
WebContext.Sess ion["TotalEmailsToS end"] =0;
WebContext.Sess ion["Done"] = "false";
WebContext.Sess ion["TotalEmailsToS end"] =this.DataSet.T ables[0].Rows.Count.ToS tring();
}
}
else
{
WebContext.Resp onse.Write("Ret rieving data to send ..");
}
#endregion
// Newsletter Merging
int startAt = Environment.Tic kCount;
int EmailCounter = 0;
bool TestMode = true;
foreach (DataRow DR in this.DataSet.Ta bles[0].Rows)
{
#region loop sending

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

string BodyForEmail = ReplaceFields(D R, this.Body);
string ToForEmail = DR[this.EmailAddre ssField].ToString();
string ToNameForEmail = ReplaceFields(D R,this.EmailNam eField);
string SubjectForEmail = ReplaceFields(D R, this.Subject);


if (this.Sessions)
{
lock(WebContext .Session.SyncRo ot )
{
WebContext.Sess ion[ "StatusLine " ] = "Processing " +ToForEmail;
}
}
try
{
if (!TestMode)
{
//stmpobj.Send(em ailmsg)
}
else
{

WebContext.Resp onse.Write("Sen ding to "+ ToForEmail + "("+ ToNameForEmail + ") " + WebContext.Sess ion[ "StatusLine "].ToString() + "<br/>");
}
if (this.Sessions)
{ // Reporting
((StringBuilder )WebContext.Ses sion["EmailRepor t"]).Append(EmailC ounter+ "," + DR["UserID"].ToString() +
", " + DateTime.Now.To String() + ", Successful<BR>" );//Reporting
}
}
catch (Exception ErrorMsg)
{
if (this.Sessions)
{ // Reporting
((StringBuilder )WebContext.Ses sion["EmailRepor t"]).Append(EmailC ounter+ "," + DR["UserID"].ToString() +
", " + DateTime.Now.To String() + ", Failed:" +ErrorMsg.Messa ge + "<BR>" );
}
}
EmailCounter++;
if (this.Sessions)
{
lock(WebContext .Session.SyncRo ot)
WebContext.Sess ion[ "EmailCount er" ] = EmailCounter;
}
#endregion
}
#region Sessions Final Values
if (this.Sessions)
{
lock( WebContext.Sess ion.SyncRoot )
{
int ms = Environment.Tic kCount - startAt;
int seconds = ms/1000;
WebContext.Sess ion[ "SecondsForMail Merge" ] =seconds.ToStri ng();
WebContext.Sess ion["Done"] = true;
WebContext.Sess ion["StatusLine "] = "NewsletterComp leted!";
}
}
#endregion
// this.DataSet.Di spose();
}
catch (Exception ex)
{
#region Session Report with Error
if (this.Sessions)
{
lock(WebContext .Session.SyncRo ot )
{
WebContext.Sess ion["MailMergeExcep tion"] = ex;
}
}
#endregion
WebContext.Resp onse.Write("Mai ler 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 2088
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*******@dotn et247.com> wrote in message
news:eZ******** ******@tk2msftn gp13.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.A dd ?

Any ideas would be great:)

Gavin Lyons


private void Send_Click(obje ct sender, System.Web.UI.I mageClickEventA rgs e)
{
if (Subject.Text!= "")
{
string SQLString = "SELECT * FROM Members";
i386.Newsletter .mailer MailObj = new mailer();
MailObj.SMTPhos t = "mail.smtp.com" ;
MailObj.From = From.SelectedVa lue;
MailObj.Body = Body();
MailObj.Session s = true;
MailObj.EmailAd dressField = "UserID";
MailObj.EmailNa meField = "<!--FirstName--> <!--LastName-->";
MailObj.DataSet = i386.DatabaseSy stem.GetDataSet (SQLString,
"WebConfigDatab aseConnection") ;
MailObj.WebCont ext = (System.Web.Htt pContext)Sessio n["WebContext "];

Thread thread = new Thread(new ThreadStart(Mai lObj.Send));
thread.Priority = ThreadPriority. Lowest;
thread.Start();
Thread.Sleep(50 0);
Response.Redire ct("status.aspx ", true);

}
else
Label_Message.T ext="Missing data!";
}

public class mailer
{
private string _SMTPhost="loca lhost";
private string _Body="";
private string _From="";
private string _FromName="";
private string _Subject="";
private string _DatabaseConnec tion;
private string _EmailAddressFi eld;
private string _EmailNameField ;
private System.Web.Http Context _WebContext;
private DataSet _DataSet;
private bool _Sessions=true;
public string SMTPhost
{
get {return _SMTPhost;}
set {_SMTPhost=valu e;}
}
public string EmailNameField
{
get {return _EmailNameField ;}
set {_EmailNameFiel d=value;}
}
public string EmailAddressFie ld
{
get {return _EmailAddressFi eld;}
set {_EmailAddressF ield=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=valu e;}
}
public bool Sessions
{
get {return _Sessions;}
set {_Sessions=valu e;}
}
public DataSet DataSet
{
set {_DataSet=value ;}
get {return _DataSet;}
}
public System.Web.Http Context WebContext
{
set {_WebContext=va lue;}
get {return _WebContext;}
}
private string ReplaceFields(D ataRow DR, string String)
{
string ReplStr = String;
foreach (DataColumn Column in DR.Table.Column s)
{
ReplStr = ReplStr.Replace ("<!--" + Column.ToString () + "-->",
DR[Column.ToString ()].ToString());
}
return ReplStr;
}
public void Send()
{
try
{
#region Initialise Sessions
if (this.Sessions)
{
lock(WebContext .Session.SyncRo ot )//lock the session object
{
StringBuilder sb = new StringBuilder() ; // for reporting

WebContext.Sess ion["StatusLine "] = "Retrieving data to send ..";
WebContext.Sess ion["EmailRepor t"] = sb;
WebContext.Sess ion["EmailCount er"] = "0";
WebContext.Sess ion["TotalEmailsToS end"] =0;
WebContext.Sess ion["Done"] = "false";
WebContext.Sess ion["TotalEmailsToS end"] =
this.DataSet.Ta bles[0].Rows.Count.ToS tring();
}
}
else
{
WebContext.Resp onse.Write("Ret rieving data to send ..");
}
#endregion
// Newsletter Merging
int startAt = Environment.Tic kCount;
int EmailCounter = 0;
bool TestMode = true;
foreach (DataRow DR in this.DataSet.Ta bles[0].Rows)
{
#region loop sending

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

string BodyForEmail = ReplaceFields(D R, this.Body);
string ToForEmail = DR[this.EmailAddre ssField].ToString();
string ToNameForEmail = ReplaceFields(D R, this.EmailNameF ield);
string SubjectForEmail = ReplaceFields(D R, this.Subject);
if (this.Sessions)
{
lock(WebContext .Session.SyncRo ot )
{
WebContext.Sess ion[ "StatusLine " ] = "Processing " + ToForEmail;
}
}
try
{
if (!TestMode)
{
//stmpobj.Send(em ailmsg)
}
else
{

WebContext.Resp onse.Write("Sen ding to "+ ToForEmail + "(" + ToNameForEmail +
") " + WebContext.Sess ion[ "StatusLine " ].ToString() + "<br/>");
}
if (this.Sessions)
{ // Reporting
((StringBuilder )WebContext.Ses sion["EmailRepor t"]).Append(EmailC ounter+ ","
+ DR["UserID"].ToString() +
", " + DateTime.Now.To String() + ", Successful<BR>" );// Reporting
}
}
catch (Exception ErrorMsg)
{
if (this.Sessions)
{ // Reporting
((StringBuilder )WebContext.Ses sion["EmailRepor t"]).Append(EmailC ounter+ ","
+ DR["UserID"].ToString() +
", " + DateTime.Now.To String() + ", Failed:" + ErrorMsg.Messag e + "<BR>" );
}
}
EmailCounter++;
if (this.Sessions)
{
lock(WebContext .Session.SyncRo ot)
WebContext.Sess ion[ "EmailCount er" ] = EmailCounter;
}
#endregion
}
#region Sessions Final Values
if (this.Sessions)
{
lock( WebContext.Sess ion.SyncRoot )
{
int ms = Environment.Tic kCount - startAt;
int seconds = ms/1000;
WebContext.Sess ion[ "SecondsForMail Merge" ] = seconds.ToStrin g();
WebContext.Sess ion["Done"] = true;
WebContext.Sess ion["StatusLine "] = "Newsletter Completed!";
}
}
#endregion
// this.DataSet.Di spose();
}
catch (Exception ex)
{
#region Session Report with Error
if (this.Sessions)
{
lock(WebContext .Session.SyncRo ot )
{
WebContext.Sess ion["MailMergeExcep tion"] = ex;
}
}
#endregion
WebContext.Resp onse.Write("Mai ler 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
1417
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 show to the user the progress of the operation and here is the problem. I try to access to the Session Variables from inside the thread to show it on a page that automatically refresh, BUT, I have discovered that there is no access to the...
2
249
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 page if true. The problem when I assign thread priority to highest, it just works like a dream, otherwise, it produces an error: ----The type System.Web.HttpException in Assembly System.Web, Version=1.0.5000.0,
8
1502
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 down. I have to set a session to null in the same click method but when I do this I get this funny error.
1
1389
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 thread will modify objects in the session. The thread does some work and updates status in the session object. The client refreshes every few seconds and checks the status (it is a long running task). This works fine in InProc mode. However, this...
4
7925
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 HttpContext.Current to get Session Variable value. Here my code fails. Thread on which the process is running does not have HTTPContext.Current object. How can I pass-on HTTPContext.Current info to thread. I used WindowsImpersonationContext for...
10
4568
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 on the button, data is retrieved from the database. This looks to work fine. However, sometimes after clicking on the butten to retrieve the data i got an error message (on the separate thread): "The connection is already Open"
2
1307
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 NewThread.Start() Response.Redirect("loading.aspx")
10
2169
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 I've been trying to reduce the code. In the process it's started to crash in different ways. I'm not sure if any of it is related. The following is only crashing Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) on win32 in two different(?) ways.
7
1082
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. One issue we have is that whenever a page is saved in the CMS, we grab the info about the user that is saving the page and save it along with the page (so we can track who has changed what). This works most of the time.
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8751
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8629
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7360
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6181
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5650
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4338
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2757
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1739
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.