Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
sorry for bugging you guys with such a small problem, but I cannot find a solution. I have created one class for getting attachments from exchange server and Form for adding server configuration and textbox which I attend to use for the log output. I have added backgroundWorker to create separate thread and when class gets right attachment and collect info for the output, it redirects to backgroundWorker DoWork method. The problem is that UI of the textbox is simply doesn't want to append text


Form class:
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DownloadAttachmentExchange
{
    public partial class Form1 : Form
    {
        private string path = "";
        public string date = "";
        public string attachment = "";
        public string subject = "";
        //string text = "";
        public Form1()
        {
            InitializeComponent();
        }
        ExchangeDwnClass exchange = new ExchangeDwnClass();
        private void button3_Click(object sender, EventArgs e)
        {
            if(folderBrowserDialog1.ShowDialog(this)== DialogResult.OK)
            {
                path = folderBrowserDialog1.SelectedPath;   
                exchange.Path = path;
                pathTxt.Text = path;
            }
        }

        private void onBtn_Click(object sender, EventArgs e)
        {
            exchange.Username = userTxt.Text;
            exchange.Password = passwdTxt.Text;
            exchange.FilterSender = fromFilterTxt.Text;
            exchange.EmailFetch = Convert.ToInt32(fetchUpDown.Value);
            exchange.Exchange = exchangeTxt.Text;
            exchange.GetAttachments();
        }

        private void filterExcelCheck_CheckedChanged(object sender, EventArgs e)
        {
            if (filterExcelCheck.CheckState == CheckState.Checked)
            {
                exchange.FilterExcel = ".xlsx";
            }
            else
            {
                exchange.FilterExcel = "";
            }
        }

        private void filterCSVCheck_CheckedChanged(object sender, EventArgs e)
        {
            if (filterCSVCheck.CheckState == CheckState.Checked)
            {
                exchange.FilterCsv = ".csv";
            }
            else
            {
                exchange.FilterCsv = "";
            }
        }

        private void exchangeTxt_MouseHover(object sender, EventArgs e)
        {
            tipLbl.Visible = true;
            tipLbl.Text = "It is usually same as email address...";
        }

        private void exchangeTxt_MouseLeave(object sender, EventArgs e)
        {
            tipLbl.Visible = false;
        }

        public delegate void MethodInvoker();

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //this.Invoke(new BindTextBoxControl(UpdateTextbox), new object[] { "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r" });
            
            this.Invoke((MethodInvoker)delegate()
            {
                logOutputTxt.Text += "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
            });
        }
        delegate void BindTextBoxControl(string text);
        //private void UpdateTextbox(string _Text)
        //{
        //    logOutputTxt.Text += _Text;
        //}
    }
}


Download attachment from Exchange class:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Exchange;
using Microsoft.Exchange.WebServices;
using Microsoft.Exchange.WebServices.Data;
using System.Threading;

namespace DownloadAttachmentExchange
{
    class ExchangeDwnClass
    {
        private string path_ = "";
        private string filterSender_ = "";
        private string subject_ = "";
        private string id_ = "";
        private string username_ = "";
        private string password_ = "";
        private string exchange_ = "";
        private string filterExcel_ = "";
        private string filterCSV_ = "";
        private string attachmentName_ = "";
        private int emailFetch_ = 0;
        private DateTime current_;

        ExchangeService serv = new ExchangeService(ExchangeVersion.Exchange2010_SP1);
        

        public string Path
        {
            get { return path_; }
            set { path_ = value; }
        }
        public string FilterSender
        {
            get { return filterSender_; }
            set { filterSender_ = value; }
        }
        public string Subject
        {
            get { return subject_; }
            set { subject_ = value; }
        }
        public string ID
        {
            get { return id_; }
            set { id_ = value; }
        }
        public string Username
        {
            get { return username_; }
            set { username_ = value; }
        }
        public string Password
        {
            get { return password_; }
            set { password_ = value; }
        }
        public string Exchange
        {
            get { return exchange_; }
            set { exchange_ = value; }
        }
        public string FilterExcel
        {
            get { return filterExcel_; }
            set { filterExcel_ = value; }    
        }
        public string FilterCsv
        {
            get { return filterCSV_; }
            set { filterCSV_ = value; }
        }
        public string AttachementName
        {
            get { return attachmentName_; }
            set { attachmentName_ = value; }
        }
        public int EmailFetch
        {
            get { return emailFetch_; }
            set { emailFetch_ = value; }
        }
        public DateTime CurrentDate
        {
            get { return current_; }
            set { current_ = value; }
        }
        
        public void GetAttachments()
        {
            try
            {  
                serv.Credentials = new WebCredentials(Username, Password);
                serv.AutodiscoverUrl(Exchange);

                ItemView view = new ItemView(10);
                FindItemsResults<Item> result = serv.FindItems(WellKnownFolderName.Inbox, new ItemView(EmailFetch));

                if (result != null && result.Items != null && result.Items.Count > 0)
                {
                    foreach (Item item in result.Items)
                    {
                        EmailMessage msg = EmailMessage.Bind(serv, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments, ItemSchema.HasAttachments, EmailMessageSchema.From, EmailMessageSchema.Sender));
                        if (msg.Sender.ToString().Contains(FilterSender) && msg.From.ToString().Contains(FilterSender))
                        {
                            foreach (Attachment att in msg.Attachments)
                            {
                                if (att is FileAttachment)
                                {
                                    FileAttachment file = att as FileAttachment;
                                    if (file.Name.Contains(FilterExcel) || file.Name.Contains(FilterCsv))
                                    {
                                        Form1 form = new Form1();
                                        file.Load(Path +"\\"+ file.Name);
                                        AttachementName = file.Name.ToString();
                                        Subject = item.Subject.ToString();
                                        ID = item.Id.ToString();
                                        CurrentDate = DateTime.Now;                                 
                                        form.date = CurrentDate.ToString();
                                        form.subject = Subject;
                                        form.attachment = AttachementName;         
                                        form.backgroundWorker1.RunWorkerAsync();
                                        Thread.Sleep(60000);
                                    }
                                }
                            }
                        }
                        //item.Delete(DeleteMode.HardDelete);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.ReadLine();
        }
        public void StopDownloadingAttachment()
        { 
            
        }
    }
}


I get an error:

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

Any idea how to fix this?
Posted

1 solution

Sounds like the form hasn't finished being instantiated and loading before the method is being invoked.

As a trial, you could drop in a 500ms delay to allow the form to fully load. You could start off a System.Timer in the constructor and then using the timer elapsed event to do the invoking and then just dispose of the timer.

I had to do something similar in this UltraDynamo (Part 2) - It is all about the sensors[^], Scroll down to the "Pseudo Event - What is that for?" section for the description.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900