473,567 Members | 2,909 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Threading guru required!

I am trying to write my first program using threading..basi cally I am
moving messages from an Outlook inbox and want to show the user where
the process is up to without having to wait until it has finished. I am
trying to follow this example :
http://www.codeproject.com/cs/miscct...ressdialog.asp

But although the messages still get moved, the progress window never
does anything. Here is my code in full, if anybody who knows anything
about threading could help me, it would be much appreciated!

Form1.cs :

using System;
using System.Collecti ons.Generic;
using System.Componen tModel;
using System.Data;
using System.Data.Sql Client;
using System.Drawing;
using System.Text;
using System.Windows. Forms;
using Outlook;

namespace WindowsApplicat ion1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeCompo nent();
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Disp ose();
}
}
base.Dispose(di sposing);
}

private void btnGo_Click(obj ect sender, EventArgs e)
{
ProgressWindow progress = new ProgressWindow( );
progress.Text = "Work";
System.Threadin g.ThreadPool.Qu eueUserWorkItem (new
System.Threadin g.WaitCallback( DoSomeWork), progress);
progress.ShowDi alog();
}

private void DoSomeWork(obje ct status)
{
IProgressCallba ck callback = status as IProgressCallba ck;

try
{
Outlook.Applica tion oApp = new
Outlook.Applica tionClass();

//Get MAPI namespace
Outlook.NameSpa ce oNS = oApp.GetNamespa ce("mapi");

string strUserName =
System.Environm ent.UserName.To String();

try
{
oNS.Logon(strUs erName,
System.Reflecti on.Missing.Valu e, false, true);
}
catch
{
throw new LogonException( );
}

//Get Messages collection of Inbox
Outlook.MAPIFol der oInbox =
oNS.GetDefaultF older(Outlook.O lDefaultFolders .olFolderInbox) ;

try
{
Outlook.MAPIFol der destfolderTest =
oInbox.Folders. Item("Archive") ;
}
catch
{
throw new MissingFolderEx ception();
}

Outlook.MAPIFol der destfolder =
oInbox.Folders. Item("Archive") ;

Outlook.Items oItems = oInbox.Items;

int intTotalNumberO fItemsInInbox = oItems.Count;

if (intTotalNumber OfItemsInInbox == 0)
throw new NoMessagesExcep tion();

//Get unread e-mail messages
//oItems = oItems.Restrict ("[Unread] = true");
//int intTotalUnread = oItems.Count;

//DataTable dt = new DataTable();
//DataRow dr;

//dt.Columns.Add( "ReceivedByName ");
//dt.Columns.Add( "SenderName ");
//dt.Columns.Add( "ReceivedTime") ;
//dt.Columns.Add( "Subject");
//dt.Columns.Add( "Body");

//Outlook.MailIte m oMsg;
//int i;

//database connection
SqlConnection objConn = new SqlConnection() ;
objConn.Connect ionString = "server=e2bvsql 4\\inst1; user
id=datawriter; password=rover9 ; database=Survey Results";

try
{
objConn.Open();
}
catch
{
throw new DatabaseExcepti on();
}

//string strInsertQuery = "";

callback.Begin( 0, intTotalNumberO fItemsInInbox);

for (int i = 0; i < oItems.Count; i++)
{
callback.SetTex t(String.Format ("Performing op: {0}",
i));
callback.StepTo (i);

if (callback.IsAbo rting)
{
return;
}

oItems = oInbox.Items;
MoveMail(oItems , destfolder, objConn);

if (oItems.Count == 1)
{
i = -1;
}
else
{
i = 0;
}
}

objConn.Close() ;

//Loop through each unread message
//for (i = 1; i < intTotalNumberO fItemsInInbox + 1; i++)
//{
// //check if appointment or meeting request
// if (oItems.Item(i) is Outlook.MailIte m)
// {
// oMsg = (Outlook.MailIt em)oItems.Item( i);

//dr = dt.NewRow();
//dr["ReceivedByName "] = oMsg.ReceivedBy Name.ToString() ;
//dr["SenderName "] = oMsg.SenderName .ToString();
//dr["ReceivedTi me"] = oMsg.ReceivedTi me.ToString();
//dr["Subject"] = oMsg.Subject.To String();
//dr["Body"] = oMsg.Body.ToStr ing();
//dt.Rows.Add(dr) ;

////subject
//if ((oMsg.Subject == null) || (oMsg.Subject == ""))
//{
// oMsg.Subject = "blank";
//}
//else
//{
// //escape quotes in subject
// oMsg.Subject = oMsg.Subject.Re place("'", "''");
//}

//if (oMsg.ReceivedB yName == null)
//{
// if (oMsg.SenderNam e.IndexOf("'") != -1)
// {
// string strSenderName =
oMsg.SenderName .Replace("'", "''");

// strInsertQuery = "INSERT INTO SeedingResults
(SenderName, ReceivedTime, Subject) VALUES ('" + strSenderName + "','" +
oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() + "')";
// }
// else
// {
// strInsertQuery = "INSERT INTO SeedingResults
(SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.SenderName .ToString() + "','" + oMsg.ReceivedTi me.ToString() +
"','" + oMsg.Subject.To String() + "')";
// }
//}
//else
//{
// if (oMsg.SenderNam e.IndexOf("'") != -1)
// {
// string strSenderName2 =
oMsg.SenderName .Replace("'", "''");

// strInsertQuery = "INSERT INTO SeedingResults
(ReceivedByName , SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.ReceivedBy Name.ToString() + "','" + strSenderName2 + "','" +
oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() + "')";
// }
// else
// {
// strInsertQuery = "INSERT INTO SeedingResults
(ReceivedByName , SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.ReceivedBy Name.ToString() + "','" + oMsg.SenderName .ToString() +
"','" + oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() +
"')";
// }
//}

////write to database
//SqlCommand objInsertComman d = new
SqlCommand(strI nsertQuery, objConn);

//try
//{
//objConn.Open();

//objInsertComman d.ExecuteNonQue ry();

//objConn.Close() ;
//}
//catch
//{
// throw new DatabaseExcepti on();
//}

//move record to archive folder
//oMsg.Move(destf older);
// }
//}

//dataGridView1.D ataSource = dt;
//GridView1.DataS ource = dt;
//GridView1.DataB ind();

//Log off
oNS.Logoff();

//Clean up
oApp = null;
oNS = null;
oItems = null;
//oMsg = null;

//inform user of success
lblStatus.ForeC olor = System.Drawing. Color.Blue;
lblStatus.Text = "**Inbox messages successfully
transferred**";
}
catch (LogonException le)
{
lblStatus.ForeC olor = System.Drawing. Color.Red;
lblStatus.Text = "**Outlook Logon Error**";
}
catch (MissingFolderE xception mfe)
{
lblStatus.ForeC olor = System.Drawing. Color.Red;
lblStatus.Text = "**Please create Archive folder within
local Inbox folder**";
}
catch (NoMessagesExce ption nme)
{
lblStatus.ForeC olor = System.Drawing. Color.Red;
lblStatus.Text = "**There are no messages in the local
Inbox to be transferred**";
}
catch (DatabaseExcept ion se)
{
lblStatus.ForeC olor = System.Drawing. Color.Red;
lblStatus.Text = "**Database Error**";
}
catch( System.Threadin g.ThreadAbortEx ception )
{
// We want to exit gracefully here (if we're lucky)
}
catch( System.Threadin g.ThreadInterru ptedException )
{
// And here, if we can
}
catch
{
lblStatus.ForeC olor = System.Drawing. Color.Red;
lblStatus.Text = "**General Exception**";
}
finally
{
if (callback != null)
{
callback.End();
}
}
}

private void MoveMail(Outloo k.Items col, Outlook.MAPIFol der
destfolder, SqlConnection objConn)
{
string strInsertQuery = "";

for (int i = 1; i < col.Count + 1; i++)
{
if (col.Item(i) is Outlook.MailIte m)
{
Outlook.MailIte m oMsg =
(Outlook.MailIt em)col.Item(i);

//subject
if ((oMsg.Subject == null) || (oMsg.Subject == ""))
{
oMsg.Subject = "blank";
}
else
{
//escape quotes in subject
oMsg.Subject = oMsg.Subject.Re place("'", "''");
}

if (oMsg.ReceivedB yName == null)
{
if (oMsg.SenderNam e.IndexOf("'") != -1)
{
string strSenderName =
oMsg.SenderName .Replace("'", "''");

strInsertQuery = "INSERT INTO SeedingResults
(SenderName, ReceivedTime, Subject) VALUES ('" + strSenderName + "','" +
oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() + "')";
}
else
{
strInsertQuery = "INSERT INTO SeedingResults
(SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.SenderName .ToString() + "','" + oMsg.ReceivedTi me.ToString() +
"','" + oMsg.Subject.To String() + "')";
}
}
else
{
if (oMsg.SenderNam e.IndexOf("'") != -1)
{
string strSenderName2 =
oMsg.SenderName .Replace("'", "''");

strInsertQuery = "INSERT INTO SeedingResults
(ReceivedByName , SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.ReceivedBy Name.ToString() + "','" + strSenderName2 + "','" +
oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() + "')";
}
else
{
strInsertQuery = "INSERT INTO SeedingResults
(ReceivedByName , SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.ReceivedBy Name.ToString() + "','" + oMsg.SenderName .ToString() +
"','" + oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() +
"')";
}
}

//write to database
SqlCommand objInsertComman d = new
SqlCommand(strI nsertQuery, objConn);

try
{
objInsertComman d.ExecuteNonQue ry();
}
catch
{
throw new DatabaseExcepti on();
}

oMsg.Move(destf older);
}
}
}
}
}

IProcessCallbac k.cs :

using System;

namespace WindowsApplicat ion1
{
/// <summary>
/// This defines an interface which can be implemented by UI
elements
/// which indicate the progress of a long operation.
/// (See ProgressWindow for a typical implementation)
/// </summary>
public interface IProgressCallba ck
{
/// <summary>
/// Call this method from the worker thread to initialize
/// the progress callback.
/// </summary>
/// <param name="minimum"> The minimum value in the progress
range (e.g. 0)</param>
/// <param name="maximum"> The maximum value in the progress
range (e.g. 100)</param>
void Begin(int minimum, int maximum);

/// <summary>
/// Call this method from the worker thread to initialize
/// the progress callback, without setting the range
/// </summary>
void Begin();

/// <summary>
/// Call this method from the worker thread to reset the range
in the progress callback
/// </summary>
/// <param name="minimum"> The minimum value in the progress
range (e.g. 0)</param>
/// <param name="maximum"> The maximum value in the progress
range (e.g. 100)</param>
/// <remarks>You must have called one of the Begin() methods
prior to this call.</remarks>
void SetRange(int minimum, int maximum);

/// <summary>
/// Call this method from the worker thread to update the
progress text.
/// </summary>
/// <param name="text">The progress text to display</param>
/// <remarks>You must have called one of the Begin() methods
prior to this call.</remarks>
void SetText(String text);

/// <summary>
/// Call this method from the worker thread to increase the
progress counter by a specified value.
/// </summary>
/// <param name="val">The amount by which to increment the
progress indicator</param>
/// <remarks>You must have called one of the Begin() methods
prior to this call.</remarks>
void StepTo(int val);

/// <summary>
/// Call this method from the worker thread to step the progress
meter to a particular value.
/// </summary>
/// <param name="val">The value to which to step the
meter</param>
/// <remarks>You must have called one of the Begin() methods
prior to this call.</remarks>
void Increment(int val);

/// <summary>
/// If this property is true, then you should abort work
/// </summary>
/// <remarks>You must have called one of the Begin() methods
prior to this call.</remarks>
bool IsAborting
{
get;
}

/// <summary>
/// Call this method from the worker thread to finalize the
progress meter
/// </summary>
/// <remarks>You must have called one of the Begin() methods
prior to this call.</remarks>
void End();
}
}

ProgressWindow. cs :

using System;
using System.Drawing;
using System.Collecti ons;
using System.Componen tModel;
using System.Windows. Forms;

namespace MWA.Progress
{
/// <summary>
/// Summary description for ProgressWindow.
/// </summary>
public class ProgressWindow : System.Windows. Forms.Form,
IProgressCallba ck
{
private System.Windows. Forms.Button cancelButton;
private System.Windows. Forms.Label label;
private System.Windows. Forms.ProgressB ar progressBar;

/// <summary>
/// Required designer variable.
/// </summary>
private System.Componen tModel.Containe r components = null;

public delegate void SetTextInvoker( String text);
public delegate void IncrementInvoke r( int val );
public delegate void StepToInvoker( int val );
public delegate void RangeInvoker( int minimum, int maximum );

private String titleRoot = "";
private System.Threadin g.ManualResetEv ent initEvent = new
System.Threadin g.ManualResetEv ent(false);
private System.Threadin g.ManualResetEv ent abortEvent = new
System.Threadin g.ManualResetEv ent(false);
private bool requiresClose = true;

public ProgressWindow( )
{
//
// Required for Windows Form Designer support
//
InitializeCompo nent();
}

#region Implementation of IProgressCallba ck
/// <summary>
/// Call this method from the worker thread to initialize
/// the progress meter.
/// </summary>
/// <param name="minimum"> The minimum value in the progress range
(e.g. 0)</param>
/// <param name="maximum"> The maximum value in the progress range
(e.g. 100)</param>
public void Begin( int minimum, int maximum )
{
initEvent.WaitO ne();
Invoke( new RangeInvoker( DoBegin ), new object[] { minimum, maximum
} );
}

/// <summary>
/// Call this method from the worker thread to initialize
/// the progress callback, without setting the range
/// </summary>
public void Begin()
{
initEvent.WaitO ne();
Invoke( new MethodInvoker( DoBegin ) );
}

/// <summary>
/// Call this method from the worker thread to reset the range in the
progress callback
/// </summary>
/// <param name="minimum"> The minimum value in the progress range
(e.g. 0)</param>
/// <param name="maximum"> The maximum value in the progress range
(e.g. 100)</param>
/// <remarks>You must have called one of the Begin() methods prior to
this call.</remarks>
public void SetRange( int minimum, int maximum )
{
initEvent.WaitO ne();
Invoke( new RangeInvoker( DoSetRange ), new object[] { minimum,
maximum } );
}

/// <summary>
/// Call this method from the worker thread to update the progress
text.
/// </summary>
/// <param name="text">The progress text to display</param>
public void SetText( String text )
{
Invoke( new SetTextInvoker( DoSetText), new object[] { text } );
}

/// <summary>
/// Call this method from the worker thread to increase the progress
counter by a specified value.
/// </summary>
/// <param name="val">The amount by which to increment the progress
indicator</param>
public void Increment( int val )
{
Invoke( new IncrementInvoke r( DoIncrement ), new object[] { val } );
}

/// <summary>
/// Call this method from the worker thread to step the progress meter
to a particular value.
/// </summary>
/// <param name="val"></param>
public void StepTo( int val )
{
Invoke( new StepToInvoker( DoStepTo ), new object[] { val } );
}
/// <summary>
/// If this property is true, then you should abort work
/// </summary>
public bool IsAborting
{
get
{
return abortEvent.Wait One( 0, false );
}
}

/// <summary>
/// Call this method from the worker thread to finalize the progress
meter
/// </summary>
public void End()
{
if( requiresClose )
{
Invoke( new MethodInvoker( DoEnd ) );
}
}
#endregion

#region Implementation members invoked on the owner thread
private void DoSetText( String text )
{
label.Text = text;
}

private void DoIncrement( int val )
{
progressBar.Inc rement( val );
UpdateStatusTex t();
}

private void DoStepTo( int val )
{
progressBar.Val ue = val;
UpdateStatusTex t();
}

private void DoBegin( int minimum, int maximum )
{
DoBegin();
DoSetRange( minimum, maximum );
}

private void DoBegin()
{
cancelButton.En abled = true;
ControlBox = true;
}

private void DoSetRange( int minimum, int maximum )
{
progressBar.Min imum = minimum;
progressBar.Max imum = maximum;
progressBar.Val ue = minimum;
titleRoot = Text;
}

private void DoEnd()
{
Close();
}
#endregion

#region Overrides
/// <summary>
/// Handles the form load, and sets an event to ensure that
/// intialization is synchronized with the appearance of the form.
/// </summary>
/// <param name="e"></param>
protected override void OnLoad(System.E ventArgs e)
{
base.OnLoad( e );
ControlBox = false;
initEvent.Set() ;
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Disp ose();
}
}
base.Dispose( disposing );
}

/// <summary>
/// Handler for 'Close' clicking
/// </summary>
/// <param name="e"></param>
protected override void
OnClosing(Syste m.ComponentMode l.CancelEventAr gs e)
{
requiresClose = false;
AbortWork();
base.OnClosing( e );
}
#endregion

#region Implementation Utilities
/// <summary>
/// Utility function that formats and updates the title bar text
/// </summary>
private void UpdateStatusTex t()
{
Text = titleRoot + String.Format( " - {0}% complete",
(progressBar.Va lue * 100 ) / (progressBar.Ma ximum - progressBar.Min imum)
);
}

/// <summary>
/// Utility function to terminate the thread
/// </summary>
private void AbortWork()
{
abortEvent.Set( );
}
#endregion

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeCompo nent()
{
this.progressBa r = new System.Windows. Forms.ProgressB ar();
this.label = new System.Windows. Forms.Label();
this.cancelButt on = new System.Windows. Forms.Button();
this.SuspendLay out();
//
// progressBar
//
this.progressBa r.Anchor = ((System.Window s.Forms.AnchorS tyles.Bottom
| System.Windows. Forms.AnchorSty les.Left)
| System.Windows. Forms.AnchorSty les.Right);
this.progressBa r.Location = new System.Drawing. Point(8, 80);
this.progressBa r.Name = "progressBa r";
this.progressBa r.Size = new System.Drawing. Size(192, 23);
this.progressBa r.TabIndex = 1;
//
// label
//
this.label.Anch or = (((System.Windo ws.Forms.Anchor Styles.Top |
System.Windows. Forms.AnchorSty les.Bottom)
| System.Windows. Forms.AnchorSty les.Left)
| System.Windows. Forms.AnchorSty les.Right);
this.label.Loca tion = new System.Drawing. Point(8, 8);
this.label.Name = "label";
this.label.Size = new System.Drawing. Size(272, 64);
this.label.TabI ndex = 0;
this.label.Text = "Starting operation...";
//
// cancelButton
//
this.cancelButt on.Anchor = (System.Windows .Forms.AnchorSt yles.Bottom
| System.Windows. Forms.AnchorSty les.Right);
this.cancelButt on.DialogResult =
System.Windows. Forms.DialogRes ult.Cancel;
this.cancelButt on.Enabled = false;
this.cancelButt on.Location = new System.Drawing. Point(208, 80);
this.cancelButt on.Name = "cancelButt on";
this.cancelButt on.TabIndex = 2;
this.cancelButt on.Text = "Cancel";
//
// ProgressWindow
//
this.AutoScaleB aseSize = new System.Drawing. Size(5, 13);
this.ClientSize = new System.Drawing. Size(290, 114);
this.Controls.A ddRange(new System.Windows. Forms.Control[] {
this.cancelButt on,
this.progressBa r,
this.label});
this.FormBorder Style =
System.Windows. Forms.FormBorde rStyle.FixedDia log;
this.MaximizeBo x = false;
this.Name = "ProgressWindow ";
this.StartPosit ion =
System.Windows. Forms.FormStart Position.Center Parent;
this.Text = "ProgressWindow ";
this.ResumeLayo ut(false);

}
#endregion
}
}


*** Sent via Developersdex http://www.developersdex.com ***
Mar 16 '07 #1
7 2359
Continued...

if (oMsg.SenderNam e.IndexOf("'") != -1)
// {
// string strSenderName2 =
oMsg.SenderName .Replace("'", "''");

// strInsertQuery = "INSERT INTO SeedingResults
(ReceivedByName , SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.ReceivedBy Name.ToString() + "','" + strSenderName2 + "','" +
oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() + "')";
// }
// else
// {
// strInsertQuery = "INSERT INTO SeedingResults
(ReceivedByName , SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.ReceivedBy Name.ToString() + "','" + oMsg.SenderName .ToString() +
"','" + oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() +
"')";
// }
//}

////write to database
//SqlCommand objInsertComman d = new
SqlCommand(strI nsertQuery, objConn);

//try
//{
//objConn.Open();

//objInsertComman d.ExecuteNonQue ry();

//objConn.Close() ;
//}
//catch
//{
// throw new DatabaseExcepti on();
//}

//move record to archive folder
//oMsg.Move(destf older);
// }
//}

//dataGridView1.D ataSource = dt;
//GridView1.DataS ource = dt;
//GridView1.DataB ind();

//Log off
oNS.Logoff();

//Clean up
oApp = null;
oNS = null;
oItems = null;
//oMsg = null;

//inform user of success
lblStatus.ForeC olor = System.Drawing. Color.Blue;
lblStatus.Text = "**Inbox messages successfully
transferred**";
}
catch (LogonException le)
{
lblStatus.ForeC olor = System.Drawing. Color.Red;
lblStatus.Text = "**Outlook Logon Error**";
}
catch (MissingFolderE xception mfe)
{
lblStatus.ForeC olor = System.Drawing. Color.Red;
lblStatus.Text = "**Please create Archive folder within
local Inbox folder**";
}
catch (NoMessagesExce ption nme)
{
lblStatus.ForeC olor = System.Drawing. Color.Red;
lblStatus.Text = "**There are no messages in the local
Inbox to be transferred**";
}
catch (DatabaseExcept ion se)
{
lblStatus.ForeC olor = System.Drawing. Color.Red;
lblStatus.Text = "**Database Error**";
}
catch( System.Threadin g.ThreadAbortEx ception )
{
// We want to exit gracefully here (if we're lucky)
}
catch( System.Threadin g.ThreadInterru ptedException )
{
// And here, if we can
}
catch
{
lblStatus.ForeC olor = System.Drawing. Color.Red;
lblStatus.Text = "**General Exception**";
}
finally
{
if (callback != null)
{
callback.End();
}
}
}

private void MoveMail(Outloo k.Items col, Outlook.MAPIFol der
destfolder, SqlConnection objConn)
{
string strInsertQuery = "";

for (int i = 1; i < col.Count + 1; i++)
{
if (col.Item(i) is Outlook.MailIte m)
{
Outlook.MailIte m oMsg =
(Outlook.MailIt em)col.Item(i);

//subject
if ((oMsg.Subject == null) || (oMsg.Subject == ""))
{
oMsg.Subject = "blank";
}
else
{
//escape quotes in subject
oMsg.Subject = oMsg.Subject.Re place("'", "''");
}

if (oMsg.ReceivedB yName == null)
{
if (oMsg.SenderNam e.IndexOf("'") != -1)
{
string strSenderName =
oMsg.SenderName .Replace("'", "''");

strInsertQuery = "INSERT INTO SeedingResults
(SenderName, ReceivedTime, Subject) VALUES ('" + strSenderName + "','" +
oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() + "')";
}
else
{
strInsertQuery = "INSERT INTO SeedingResults
(SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.SenderName .ToString() + "','" + oMsg.ReceivedTi me.ToString() +
"','" + oMsg.Subject.To String() + "')";
}
}
else
{
if (oMsg.SenderNam e.IndexOf("'") != -1)
{
string strSenderName2 =
oMsg.SenderName .Replace("'", "''");

strInsertQuery = "INSERT INTO SeedingResults
(ReceivedByName , SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.ReceivedBy Name.ToString() + "','" + strSenderName2 + "','" +
oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() + "')";
}
else
{
strInsertQuery = "INSERT INTO SeedingResults
(ReceivedByName , SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.ReceivedBy Name.ToString() + "','" + oMsg.SenderName .ToString() +
"','" + oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() +
"')";
}
}

//write to database
SqlCommand objInsertComman d = new
SqlCommand(strI nsertQuery, objConn);

try
{
objInsertComman d.ExecuteNonQue ry();
}
catch
{
throw new DatabaseExcepti on();
}

oMsg.Move(destf older);
}
}
}
}
}

*** Sent via Developersdex http://www.developersdex.com ***
Mar 16 '07 #2
Continued...

IProcessCallbac k.cs :

using System;

namespace WindowsApplicat ion1
{
/// <summary>
/// This defines an interface which can be implemented by UI
elements
/// which indicate the progress of a long operation.
/// (See ProgressWindow for a typical implementation)
/// </summary>
public interface IProgressCallba ck
{
/// <summary>
/// Call this method from the worker thread to initialize
/// the progress callback.
/// </summary>
/// <param name="minimum"> The minimum value in the progress
range (e.g. 0)</param>
/// <param name="maximum"> The maximum value in the progress
range (e.g. 100)</param>
void Begin(int minimum, int maximum);

/// <summary>
/// Call this method from the worker thread to initialize
/// the progress callback, without setting the range
/// </summary>
void Begin();

/// <summary>
/// Call this method from the worker thread to reset the range
in the progress callback
/// </summary>
/// <param name="minimum"> The minimum value in the progress
range (e.g. 0)</param>
/// <param name="maximum"> The maximum value in the progress
range (e.g. 100)</param>
/// <remarks>You must have called one of the Begin() methods
prior to this call.</remarks>
void SetRange(int minimum, int maximum);

/// <summary>
/// Call this method from the worker thread to update the
progress text.
/// </summary>
/// <param name="text">The progress text to display</param>
/// <remarks>You must have called one of the Begin() methods
prior to this call.</remarks>
void SetText(String text);

/// <summary>
/// Call this method from the worker thread to increase the
progress counter by a specified value.
/// </summary>
/// <param name="val">The amount by which to increment the
progress indicator</param>
/// <remarks>You must have called one of the Begin() methods
prior to this call.</remarks>
void StepTo(int val);

/// <summary>
/// Call this method from the worker thread to step the progress
meter to a particular value.
/// </summary>
/// <param name="val">The value to which to step the
meter</param>
/// <remarks>You must have called one of the Begin() methods
prior to this call.</remarks>
void Increment(int val);

/// <summary>
/// If this property is true, then you should abort work
/// </summary>
/// <remarks>You must have called one of the Begin() methods
prior to this call.</remarks>
bool IsAborting
{
get;
}

/// <summary>
/// Call this method from the worker thread to finalize the
progress meter
/// </summary>
/// <remarks>You must have called one of the Begin() methods
prior to this call.</remarks>
void End();
}
}
*** Sent via Developersdex http://www.developersdex.com ***
Mar 16 '07 #3
Continued...

And progressmenu.cs is also copied from the example code I mentioned.
*** Sent via Developersdex http://www.developersdex.com ***
Mar 16 '07 #4
IMO, that is a lot of code for a free forum... you may get takers, but
you'd do a *lot* better if you could demonstrate something simple (and
useful to you) but a bit shorter - e.g.

using System;
using System.Windows. Forms;
using System.Componen tModel;
using System.Threadin g;

class Program {

static void Main() {
Worker worker = new Worker();
using (Form f = new Form()) {
worker.Progress Changed += delegate(object sender,
ProgressChanged EventArgs args) {
f.BeginInvoke(( MethodInvoker)d elegate { // switch back
to UI thread to update Text
f.Text = args.ProgressPe rcentage.ToStri ng() + "%
complete";
});
};
f.Load += delegate { // start the worker on a background
thread at form load
ThreadPool.Queu eUserWorkItem(w orker.DoWork);
};
Application.Run (f);
}
}
}

class Worker {
public event ProgressChanged EventHandler ProgressChanged ;
public void DoWork(object state) {
Random rand = new Random();
for (int i = 0; i < 100; i++) {
Thread.Sleep(ra nd.Next(750)); // simulate busy
OnProgressChang ed(i, state);
}
}
protected void OnProgressChang ed(int percent, object state) {
ProgressChanged EventHandler handler = ProgressChanged ;
if (handler != null) handler(this, new
ProgressChanged EventArgs(perce nt, state));
}
}
Mar 16 '07 #5
Apologies, the only bits that are really relevany are in the first 2
posts, the rest are classes copied directly from the example I referred
to. The bit I am having problems with is here :

private void btnGo_Click(obj ect sender, EventArgs e)
{
ProgressWindow progress = new ProgressWindow( );
progress.Text = "Work";
System.Threadin g.ThreadPool.Qu eueUserWorkItem (new
System.Threadin g.WaitCallback( DoSomeWork), progress);
progress.ShowDi alog();
}

private void DoSomeWork(obje ct status)
{
IProgressCallba ck callback = status as IProgressCallba ck;

try
{
Outlook.Applica tion oApp = new
Outlook.Applica tionClass();

//Get MAPI namespace
Outlook.NameSpa ce oNS = oApp.GetNamespa ce("mapi");

string strUserName =
System.Environm ent.UserName.To String();

try
{
oNS.Logon(strUs erName,
System.Reflecti on.Missing.Valu e, false, true);
}
catch
{
throw new LogonException( );
}

//Get Messages collection of Inbox
Outlook.MAPIFol der oInbox =
oNS.GetDefaultF older(Outlook.O lDefaultFolders .olFolderInbox) ;

try
{
Outlook.MAPIFol der destfolderTest =
oInbox.Folders. Item("Archive") ;
}
catch
{
throw new MissingFolderEx ception();
}

Outlook.MAPIFol der destfolder =
oInbox.Folders. Item("Archive") ;

Outlook.Items oItems = oInbox.Items;

int intTotalNumberO fItemsInInbox = oItems.Count;

if (intTotalNumber OfItemsInInbox == 0)
throw new NoMessagesExcep tion();

//Get unread e-mail messages
//oItems = oItems.Restrict ("[Unread] = true");
//int intTotalUnread = oItems.Count;

//DataTable dt = new DataTable();
//DataRow dr;

//dt.Columns.Add( "ReceivedByName ");
//dt.Columns.Add( "SenderName ");
//dt.Columns.Add( "ReceivedTime") ;
//dt.Columns.Add( "Subject");
//dt.Columns.Add( "Body");

//Outlook.MailIte m oMsg;
//int i;

//database connection
SqlConnection objConn = new SqlConnection() ;
objConn.Connect ionString = "server=e2bvsql 4\\inst1; user
id=datawriter; password=rover9 ; database=Survey Results";

try
{
objConn.Open();
}
catch
{
throw new DatabaseExcepti on();
}

//string strInsertQuery = "";

callback.Begin( 0, 2);

for (int i = 0; i < oItems.Count; i++)
{
callback.SetTex t(String.Format ("Performing op: {0}",
i));
callback.StepTo (i);

if (callback.IsAbo rting)
{
return;
}

oItems = oInbox.Items;
MoveMail(oItems , destfolder, objConn);

if (oItems.Count == 1)
{
i = -1;
}
else
{
i = 0;
}
}

objConn.Close() ;

//Loop through each unread message
//for (i = 1; i < intTotalNumberO fItemsInInbox + 1; i++)
//{
// //check if appointment or meeting request
// if (oItems.Item(i) is Outlook.MailIte m)
// {
// oMsg = (Outlook.MailIt em)oItems.Item( i);

//dr = dt.NewRow();
//dr["ReceivedByName "] = oMsg.ReceivedBy Name.ToString() ;
//dr["SenderName "] = oMsg.SenderName .ToString();
//dr["ReceivedTi me"] = oMsg.ReceivedTi me.ToString();
//dr["Subject"] = oMsg.Subject.To String();
//dr["Body"] = oMsg.Body.ToStr ing();
//dt.Rows.Add(dr) ;

////subject
//if ((oMsg.Subject == null) || (oMsg.Subject == ""))
//{
// oMsg.Subject = "blank";
//}
//else
//{
// //escape quotes in subject
// oMsg.Subject = oMsg.Subject.Re place("'", "''");
//}

//if (oMsg.ReceivedB yName == null)
//{
// if (oMsg.SenderNam e.IndexOf("'") != -1)
// {
// string strSenderName =
oMsg.SenderName .Replace("'", "''");

// strInsertQuery = "INSERT INTO SeedingResults
(SenderName, ReceivedTime, Subject) VALUES ('" + strSenderName + "','" +
oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() + "')";
// }
// else
// {
// strInsertQuery = "INSERT INTO SeedingResults
(SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.SenderName .ToString() + "','" + oMsg.ReceivedTi me.ToString() +
"','" + oMsg.Subject.To String() + "')";
// }
//}
//else
//{
// if (oMsg.SenderNam e.IndexOf("'") != -1)
// {
// string strSenderName2 =
oMsg.SenderName .Replace("'", "''");

// strInsertQuery = "INSERT INTO SeedingResults
(ReceivedByName , SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.ReceivedBy Name.ToString() + "','" + strSenderName2 + "','" +
oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() + "')";
// }
// else
// {
// strInsertQuery = "INSERT INTO SeedingResults
(ReceivedByName , SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.ReceivedBy Name.ToString() + "','" + oMsg.SenderName .ToString() +
"','" + oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() +
"')";
// }
//}

////write to database
//SqlCommand objInsertComman d = new
SqlCommand(strI nsertQuery, objConn);

//try
//{
//objConn.Open();

//objInsertComman d.ExecuteNonQue ry();

//objConn.Close() ;
//}
//catch
//{
// throw new DatabaseExcepti on();
//}

//move record to archive folder
//oMsg.Move(destf older);
// }
//}

//dataGridView1.D ataSource = dt;
//GridView1.DataS ource = dt;
//GridView1.DataB ind();

if (callback.IsAbo rting)
{
return;
}

//Log off
oNS.Logoff();

//Clean up
oApp = null;
oNS = null;
oItems = null;
//oMsg = null;

//inform user of success
//lblStatus.ForeC olor = System.Drawing. Color.Blue;
//lblStatus.Text = "**Inbox messages successfully
transferred**";
}
catch (LogonException le)
{
//lblStatus.ForeC olor = System.Drawing. Color.Red;
//lblStatus.Text = "**Outlook Logon Error**";
}
catch (MissingFolderE xception mfe)
{
//lblStatus.ForeC olor = System.Drawing. Color.Red;
//lblStatus.Text = "**Please create Archive folder
within local Inbox folder**";
}
catch (NoMessagesExce ption nme)
{
//lblStatus.ForeC olor = System.Drawing. Color.Red;
//lblStatus.Text = "**There are no messages in the local
Inbox to be transferred**";
}
catch (DatabaseExcept ion se)
{
//lblStatus.ForeC olor = System.Drawing. Color.Red;
//lblStatus.Text = "**Database Error**";
}
catch( System.Threadin g.ThreadAbortEx ception )
{
// We want to exit gracefully here (if we're lucky)
}
catch( System.Threadin g.ThreadInterru ptedException )
{
// And here, if we can
}
catch
{
//lblStatus.ForeC olor = System.Drawing. Color.Red;
//lblStatus.Text = "**General Exception**";
}
finally
{
if (callback != null)
{
callback.End();
}
}
}

private void MoveMail(Outloo k.Items col, Outlook.MAPIFol der
destfolder, SqlConnection objConn)
{
string strInsertQuery = "";

for (int i = 1; i < col.Count + 1; i++)
{
if (col.Item(i) is Outlook.MailIte m)
{
Outlook.MailIte m oMsg =
(Outlook.MailIt em)col.Item(i);

//subject
if ((oMsg.Subject == null) || (oMsg.Subject == ""))
{
oMsg.Subject = "blank";
}
else
{
//escape quotes in subject
oMsg.Subject = oMsg.Subject.Re place("'", "''");
}

if (oMsg.ReceivedB yName == null)
{
if (oMsg.SenderNam e.IndexOf("'") != -1)
{
string strSenderName =
oMsg.SenderName .Replace("'", "''");

strInsertQuery = "INSERT INTO SeedingResults
(SenderName, ReceivedTime, Subject) VALUES ('" + strSenderName + "','" +
oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() + "')";
}
else
{
strInsertQuery = "INSERT INTO SeedingResults
(SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.SenderName .ToString() + "','" + oMsg.ReceivedTi me.ToString() +
"','" + oMsg.Subject.To String() + "')";
}
}
else
{
if (oMsg.SenderNam e.IndexOf("'") != -1)
{
string strSenderName2 =
oMsg.SenderName .Replace("'", "''");

strInsertQuery = "INSERT INTO SeedingResults
(ReceivedByName , SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.ReceivedBy Name.ToString() + "','" + strSenderName2 + "','" +
oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() + "')";
}
else
{
strInsertQuery = "INSERT INTO SeedingResults
(ReceivedByName , SenderName, ReceivedTime, Subject) VALUES ('" +
oMsg.ReceivedBy Name.ToString() + "','" + oMsg.SenderName .ToString() +
"','" + oMsg.ReceivedTi me.ToString() + "','" + oMsg.Subject.To String() +
"')";
}
}

//write to database
SqlCommand objInsertComman d = new
SqlCommand(strI nsertQuery, objConn);

try
{
objInsertComman d.ExecuteNonQue ry();
}
catch
{
throw new DatabaseExcepti on();
}

oMsg.Move(destf older);
}
}
}

I'm not sure where to put the threading code as I have 2 loops that
perform the majority of the work.

*** Sent via Developersdex http://www.developersdex.com ***
Mar 16 '07 #6
On Mar 16, 1:36 pm, Mike P <mike.p...@gmai l.comwrote:
Apologies, the only bits that are really relevany are in the first 2
posts, the rest are classes copied directly from the example I referred
to. The bit I am having problems with is here :
<snip>

That's still a lot of code to go through. It would be better to
present something as short as possible but still complete and
demonstrating the problem.

See http://pobox.com/~skeet/csharp/complete.html

Jon

Mar 16 '07 #7
Mike P <mi*******@gmai l.comwrote:
I am trying to write my first program using threading..
In that case I'd strongly recommend against using a GUI at all.

My threading pages give mostly examples which don't have a GUI,
precisely because in WinForms there are extra rules you have to obey,
and it's useful to be able to learn the basics without those extra
rules.

See http://pobox.com/~skeet/csharp/threads

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Mar 16 '07 #8

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

Similar topics

8
8179
by: Z D | last post by:
Hello, I'm having a strange problem that is probably due to my lack of understanding of how threading & COM Interop works in a WinForms.NET application. Here's the situation: I have a 3rd party COM component that takes about 5 seconds to run one of its functions (Network IO bound call). Since I dont want my GUI to freeze
4
1334
by: Phillip N Rounds | last post by:
I'm cursed by being a linear thinker. Anyway, I have an application (service) where I can't decide on the appropriate way to implement threading. I have a timer which periodically initiates Process A Process A does something, then has to call N instances of Process B, where N varies from instance to instance of Process A. Process B then...
3
1087
by: chxant | last post by:
Hi, I tried a simple example of multi-threading, but it's not working. test() is never excecuted. What's wrong?? This is the code: using System; using System.Collections; using System.ComponentModel;
0
1974
by: Colmeister | last post by:
I recently read Jason Clark's excellent article on Unhandled Exceptions (http://msdn.microsoft.com/msdnmag/issues/04/06/NET/default.aspx) and have attempted to incorporate the features he talks about in a new application I'm writing. However, when I try to use ThreadStart to do some work in a separate thread from my GUI, the methods Jason...
9
1746
by: AdrianJMartin | last post by:
Hi all, I have a need for a STA thread from asp.net. I can create the thread and it runs fine. But when it is finished, the thread still 'hangs' arround. Visible only to the debugger..... I get the "The thread has exited with code 0 (0x12fc)." in the debugger each time the thread seemly end, but its still there in the thread window....
6
1890
by: hzgt9b | last post by:
Using VS 2003, .NET: I developed a windows application that performs several actions based on an input file. The application displays a progress bar as each action executes. Based on new requirements, this application needs to be able to shell off other processes and wait while in the mean time displaying a progress bar of the process's. I...
14
1616
by: Simon Verona | last post by:
I think I'm doing this wrong : I have a class with a public shared method such as follows: public shared sub myFunction dim frm as new myFrm dim t as new Threading.Thread(Addressof myFrm.myShowDialog t.start end sub
24
1884
by: Maric Michaud | last post by:
This is a recurrent problem I encounter when I try to sell python solutions to my customers. I'm aware that this problem is sometimes overlooked, but here is the market's law. I've heard of a bunch of arguments to defend python's choice of GIL, but I'm not quite sure of their technical background, nor what is really important and what is...
3
1443
by: Barkingmadscot | last post by:
I am having problems with Multi-threading and write to Key Access Database I have a log file that and collecting infomation from getting the info is a problem or is writing it the database, the log files a big and it takes time to read down as it get further in to log said, a 100,000 line in I have changed it to mutli-threading which...
0
7590
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7905
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. ...
1
7651
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7960
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...
0
6272
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...
1
5488
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...
0
3630
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2093
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
1
1205
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.