views:

174

answers:

1

Hi all.. I wrote this program, that is supposed to read about 5000 email address and send an pre-defined html mail. I am using the background worker component.

The problem is this: I have wired up the method who is supposed to send the mail. But I am calling another method that is supposed to append the body html to the salutation, like

public string GiveMeFullHtml(string personname)
 ... "Dear Mr. John Doe" + HTML ... 

It seems that when it hits this method call, operation completes. IUt only sends the first mail and completes. I think because the HTML string method is on another thread or sth like that. Can you give me a little insight. Do I have to get everything done in the very same method when using multi-threading? Thanks in advance

The full code:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Telerik.WinControls.UI; using System.Net; using System.Net.Mail;

namespace WinSendMail {

public partial class Form1 : Form
{
    DataTable adrs = new DataTable("Addresses");
    string headerHtml = @"<div style='font-family: Verdana; font-size: 16px; color: #333'><table style='width: 375pt; background-color: #e5eaf1;' border='0' cellspacing='0' cellpadding='0'><tbody><tr><td style='background: #e5eaf1;'>";

    public Form1()
    {
        InitializeComponent();
    }

    int totalAdresCount = 0;
    protected DataTable AdresleriAl()
    {
        using (DAL dal = new DAL())
        {
            DataTable dt = dal.GetTable("SELECT [ID],[Eposta],[Ad_Soyad] FROM [UYELER] WHERE [ID] IN (5923,5924,5875) ORDER BY [ID] ASC", false, null);
               totalAdresCount = dt.Rows.Count;
               labAdresAlindi.Text = totalAdresCount.ToString() + "addresses found";
            return dt;
        }
    }
    private void btnAdresAl_Click(object sender, EventArgs e)
    {
        adrs = AdresleriAl();
        btnAdresAl.Text = totalAdresCount.ToString() + " members found";
        btnAdresAl.Enabled = false;
        foreach (DataRow r in adrs.Rows)
        {
            string line = r[1].ToString() + " ( " + r[2].ToString() + " : " + r[0].ToString() + " )";
            string email = r[1].ToString();

            RadListBoxItem item = new RadListBoxItem(line, email);
            radListBox1.Items.Add(item);
        }
    }
    private void Form1_Load(object sender, EventArgs e)
    {
        SablonlariGetir();
    }
    //protected string OzellestirilmisSablonHTML(int id)
    //{
        //string adsoyad = String.Empty;
        //string tckimlik = String.Empty;
        //string basvuruno = String.Empty;
        //string eposta = String.Empty;
        //string sifre = String.Empty;

        //string sSql = "SELECT [Ad_Soyad],[TC_Kimlik_No],[Basvuru_No],[Eposta],[Sifre] from [UYELER] WHERE [ID]=" + id.ToString();
        //using (DAL dal = new DAL())
        //{
        //    string[] dudeData = dal.SelectRow(sSql, false, null);
        //    if (null == dudeData) return null;
        //    basvuruno = dudeData[2];
        //    if (String.IsNullOrEmpty(basvuruno)) { return null; };
        //    adsoyad = dudeData[0];
        //    tckimlik = dudeData[1];
        //    eposta = dudeData[3];
        //    sifre = dudeData[4];
        //}
        /////Mesaj kişi kısmını oluştur
        /////
        //string ozelmesaj = "";
        //ozelmesaj = headerHtml;
        //ozelmesaj += "<img alt='' src='http://imageurl'&gt;&lt;br/&gt;&lt;br/&gt;";
        //ozelmesaj += "<div style='padding: 10px; font-family: Tahoma; font-size:14px'>";
        //ozelmesaj += "Sayın <strong>" + adsoyad + @"</strong>,&nbsp;&nbsp;";
        //ozelmesaj += "<i>(T.C. Kimlik No: " + tckimlik + ")</i><br/><br/>";
        ////ozelmesaj += "Başvuru bilgilerinizi, üyelik test duyurusunu ve Başkanımız ın<br/>mesajını bilginize sunarız.";

        //ozelmesaj += "Başkanımız Alphan Manas'ın mesajını bilginize sunarız.";

        //ozelmesaj += "<hr/>";
        ////ozelmesaj += "<strong>Şifreniz: </strong>" + sifre + "<br/>";
        ////ozelmesaj += "<strong>Giriş Sayfası: </strong>" + "<a href='#' target='_new'>click here</a>" + "<br />";
        ////ozelmesaj += "<strong>Başvuru No: </strong>" + basvuruno + "<br/>";
        ////ozelmesaj += "<strong>E-posta Adresi: </strong>" + eposta + "<br/>";
        //ozelmesaj += "</div>";
        //ozelmesaj += "</td></tr>";

        //ozelmesaj = ozelmesaj + htmlEditor1.InnerHtml;

        //return ozelmesaj;
    //}
    protected void SablonlariGetir()
    {
        string sSql = "SELECT [ID],[Subject] FROM [Sablonlar] ORDER BY [ID] DESC";
        using (DAL dal = new DAL())
        {
            DataTable dt = dal.GetTable(sSql, false, null);
            if (dt == null) return;
            radComboBox1.Items.Clear();
            foreach (DataRow row in dt.Rows)
            {
                radComboBox1.Items.Add(new RadComboBoxItem(row[1].ToString(), row[0].ToString()));
            }
            radComboBox1.SelectedIndex = radComboBox1.Items.Count - 1;
        }
    }
    private void radComboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (radComboBox1.SelectedValue == null) return;
        slcSubjectText = radComboBox1.SelectedText;
        string sql = "SELECT [Subject],[Body] FROM [Sablonlar] WHERE [ID]=" + radComboBox1.SelectedValue;
        using (DAL dal = new DAL())
        {
            string htmlcode = dal.SelectRow(sql, false, null)[1];
            htmlEditor1.InnerHtml = htmlcode;
        }
    }
    protected void MailGonder(string to, string subject, string body)
    {
        //MailAddress adr1 = new MailAddress("[email protected]","Mensa Türkiye");
        //MailAddress adr2 = new MailAddress(to,"");
        //MailMessage msg = new MailMessage(adr1,adr2);
        //msg.ReplyTo = new MailAddress("[email protected]");
        //msg.BodyEncoding = System.Text.Encoding.UTF8;
        //msg.Subject = subject;
        //msg.IsBodyHtml = true;
        //msg.Body = body;
        //SmtpClient client = new SmtpClient("127.0.0.1", 25);
        //client.Credentials = new NetworkCredential("user", "pass");
        //try
        //{
        //    client.Send(msg);
        //    System.Threading.Thread.Sleep(50);
        //}
        //catch (Exception e)
        //{
        //    MessageBox.Show(e.Message);
        //}   
    }

    protected void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
    {
        //string msg = count.ToString() + " mails sent";
        //MessageBox.Show(msg);
    }

    private void ToggleStuff(bool state)
    {
        htmlEditor1.ReadOnly = !state;
        radButton1.Enabled = state;
        button2.Enabled = state;
        radListBox1.Enabled = state;
        radComboBox1.Enabled = state;
    }

    protected void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
    {
        labProgres.Text = count.ToString() + " / " + totalAdresCount.ToString() + " posta gönderildi.";
    }

    int count = 0;
    string slcSubjectText = "Mensa Türkiye";

    void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        DataTable dtKisiler = e.Argument as DataTable;
        foreach (DataRow row in dtKisiler.Rows)
        {
            string to = row[1].ToString();
            string body = "";

            ////////////////////////
            string adsoyad = String.Empty;
            string tckimlik = String.Empty;
            string basvuruno = String.Empty;
            string eposta = String.Empty;
            string sifre = String.Empty;

            string sSql = "SELECT [Ad_Soyad],[TC_Kimlik_No],[Basvuru_No],[Eposta],[Sifre] from [UYELER] WHERE [ID]=" + id.ToString();
            using (DAL dal = new DAL())
            {
                string[] dudeData = dal.SelectRow(sSql, false, null);
                basvuruno = dudeData[2];
                adsoyad = dudeData[0];
                tckimlik = dudeData[1];
                eposta = dudeData[3];
                sifre = dudeData[4];
            }
            ///Mesaj kişi kısmını oluştur
            ///
            string ozelmesaj = "";
            ozelmesaj = headerHtml;
            ozelmesaj += "<img alt='' src='http://www.mensa-turkey.org/mail_banner.jpg'&gt;&lt;br/&gt;&lt;br/&gt;";
            ozelmesaj += "<div style='padding: 10px; font-family: Tahoma; font-size:14px'>";
            ozelmesaj += "Sayın <strong>" + adsoyad + @"</strong>,&nbsp;&nbsp;";
            ozelmesaj += "<i>(T.C. Kimlik No: " + tckimlik + ")</i><br/><br/>";
            //ozelmesaj += "Başvuru bilgilerinizi, üyelik test duyurusunu ve Başkanımız Alphan Manas'ın<br/>mesajını bilginize sunarız.";

            ozelmesaj += "Başkanımız Alphan Manas'ın mesajını bilginize sunarız.";

            ozelmesaj += "<hr/>";
            //ozelmesaj += "<strong>Şifreniz: </strong>" + sifre + "<br/>";
            //ozelmesaj += "<strong>Giriş Sayfası: </strong>" + "<a href='http://www.mensa-turkey.org/index.asp?id=25' target='_new'>http://www.mensa-turkey.org/index.asp?id=25&lt;/a&gt;" + "<br />";
            //ozelmesaj += "<strong>Başvuru No: </strong>" + basvuruno + "<br/>";
            //ozelmesaj += "<strong>E-posta Adresi: </strong>" + eposta + "<br/>";
            ozelmesaj += "</div>";
            ozelmesaj += "</td></tr>";

            ozelmesaj = ozelmesaj + htmlEditor1.InnerHtml;
            body = ozelmesaj;

            ////////////////////////
            if (body != null)
            {
                htmlEditor1.InnerHtml = body;
                try
                {
                    MailAddress adr1 = new MailAddress("[email protected]", "Mensa Türkiye");
                    MailAddress adr2 = new MailAddress(to, "");
                    MailMessage msg = new MailMessage(adr1, adr2);
                    msg.ReplyTo = new MailAddress("[email protected]");
                    msg.BodyEncoding = System.Text.Encoding.UTF8;
                    msg.Subject = slcSubjectText;
                    msg.IsBodyHtml = true;
                    msg.Body = body;
                    SmtpClient client = new SmtpClient("212.154.55.179", 25);
                    client.Credentials = new NetworkCredential("webform", "aaa-12345");
                    try
                    {
                        client.Send(msg);
                        count++;
                        System.Threading.Thread.Sleep(50);
                        backgroundWorker1.ReportProgress(count);
                    }
                    catch (Exception x)
                    {
                        MessageBox.Show(x.Message);
                    }

                }
                catch (Exception)
                {

                }
            }
        }
    }

    private void radButton1_Click(object sender, EventArgs e)
    {
        if (radListBox1.Items.Count <= 0)
        {
            MessageBox.Show("Gönderecek kimse yok");
            return;
        }
        if (string.IsNullOrEmpty(radComboBox1.SelectedText) || string.IsNullOrEmpty(htmlEditor1.InnerHtml))
        {
            MessageBox.Show("Başlık / Mesaj eksik");
            return;
        }
        ToggleStuff(false);
        backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
        backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
        backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.RunWorkerAsync(adrs);
    }

    private void btnCheckCode_Click(object sender, EventArgs e)
    {
        HTMLView view = new HTMLView();
        view.SetHtmlCode(htmlEditor1.InnerHtml);
        view.ShowDialog();
    }

}

}

A: 

Think about this way:

static readonly string mail = "{0} {1}";
static readonly string HTML = "...";

in you main method:

BackgroundWorker bgWorker = new BackgroundWorker();

bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);

bgWorker.RunWorkerCompleted += new 
    RunWorkerCompletedEventHandler(bgWorker_RunWorkerCompleted);

bgWorker.RunWorkerAsync();

in the bgWorker_DoWork run:

foreach (var userName in userlist)
{
   //send the mail using string.Format(mail, userName, HTML)
}
mine is such ugly code right ... I know :(
AIC
Hmm.. string.Format .. is that because static methods can be accesses by different threads? is there anything like that?
AIC
Yes the "Static" was the exact answer I was after, Thank you very very much :)
AIC
No problem, I'll appreciate it if you could accept it as your answer.Good luck.