I want to add two lists to the box. It doesn't have a problem with adding items to the listbox, but a problem occurs when I try to click on one of the items and show a related form with details filled in to allow users to make amendments. Obviously the form didn't show, but instead an error occurs, no matter if I was try to open the form "delivery" or "pickup". The problem still occurs on one line
Error:
An unhandled exception of type 'System.InvalidCastException' occurred
in coursework2.exe
Additional information: Unable to cast object of type 'System.String'
to type 'coursework2.Pickup'.
namespace coursework2
{
public partial class MainForm : Form
{
private DeliveryForm deliveryform = new DeliveryForm();
private List<Visit> requests = new List<Visit>();
private Visit theVisit = new Visit();
private PickupForm pickupform = new PickupForm();
public void requestVisit(Visit newVisit)
{
requests.Add(newVisit);
}
public MainForm()
{
InitializeComponent();
}
private void btnNpickup_Click(object sender, EventArgs e)
{
pickupform.pickup = new Pickup();
pickupform.ShowDialog();
if (pickupform.pickup != null)
{
Pickup newPu = pickupform.pickup;
theVisit.addPick(newPu);
List<String> listOfPic = theVisit.listofPicks();
listboxVisits.Items.AddRange(listOfPic.ToArray());
}
updateList();
//this will upload details from pickup form to the list
}
private void groupBox2_Enter(object sender, EventArgs e)
{
}
private void MainForm_Load(object sender, EventArgs e)
{
}
private void btnNdelivery_Click(object sender, EventArgs e)
{
deliveryform.delivery = new Delivery();
deliveryform.ShowDialog();
if (deliveryform.delivery != null)
{
Delivery newDe = deliveryform.delivery;
theVisit.addDeliver(newDe);
List<String> listOfDel = theVisit.listofDeliver();
listboxVisits.Items.AddRange(listOfDel.ToArray());
}
updateList();
//this will upload detail of the delivery to the list
}
private void btnVall_Click(object sender, EventArgs e)
{
}
private void updateList()
{
listboxVisits.Items.Clear();
List<String> listofVis = theVisit.LisitVisits();
listboxVisits.Items.AddRange(listofVis.ToArray());
}
private void listboxVisits_SelectedIndexChanged(object sender, EventArgs e)
{
listboxVisits.FormattingEnabled = false;
int index = listboxVisits.SelectedIndex;
if (listboxVisits.SelectedItems.Count>0)
{
object object1 = listboxVisits.SelectedItems[0];
if (object1 is Delivery)
{
Delivery deliver = (Delivery)object1;
deliveryform.delivery = deliver;
deliveryform.ShowDialog();
}
else
{
Pickup pick = (Pickup)object1;// this is where error occur
pickupform.pickup = pick;
pickupform.ShowDialog();
}
}
this is the pickup class
public class Pickup
{
private string pickupname;
private string pickupaddress;
private Visit collects;
private Delivery sends;
private DateTime pdatetime;
private string dname;
private string daddress;
private DateTime dtime;
public string PickupName
{
get { return pickupname; }
set { pickupname = value; }
}
public string PickupAddress
{
get { return pickupaddress; }
set { pickupaddress = value; }
}
public string Dname
{
get { return dname; }
set { dname = value; }
}
public string Daddress
{
get { return daddress; }
set {daddress = value; }
}
public DateTime Pdatetime
{
get { return pdatetime; }
set { pdatetime = value; }
}
public DateTime Dtime
{
get { return dtime; }
set { dtime = value; }
}
public override string ToString()
{
return pickupname + " " + pickupaddress + " " + pdatetime.ToString()+" "+dname+" "+daddress+" "+dtime.ToString()+" Pickup ";
}
}
this is the visit class
public class Visit : Customer
{
private Customer requester;
private DateTime datetime;
private Delivery reciever;
private Pickup collect;
public DateTime DateTime
{
get { return datetime; }
set { datetime = value; }
}
private List<Pickup> picks = new List<Pickup>();
private List<Visit> visits = new List<Visit>();
private List<Delivery> deliver = new List<Delivery>();
public void addDeliver(Delivery de)
{
//adding new Delivery ToString the visit
deliver.Add(de);
}
public List<String> listofDeliver()
{
List<string> listofDeliver = new List<string>();
foreach (Delivery de in deliver)
{
String deAsString = de.ToString();
listofDeliver.Add(deAsString);
}
return listofDeliver;
}
public Delivery getDeliver(int index)
{
int count = 0;
foreach (Delivery de in deliver)
{
if (index == count)
return de;
count++;
}
return null;
}
public void addPick(Pickup pu)
{
picks.Add(pu);
}
public List<String> listofPicks()
{
List<string> listofPicks = new List<string>();
foreach (Pickup pu in picks)
{
String puAsString = pu.ToString();
listofPicks.Add(puAsString);
}
return listofPicks;
}
public Pickup getPicks(int index)
{
int count = 0;
foreach (Pickup pu in picks)
{
if (index == count)
return pu;
count++;
}
return null;
}
public List<String> LisitVisits()
{
List<String> visits = new List<string>();
visits.AddRange(listofDeliver());
visits.AddRange(listofPicks());
return visits;
}
public Visit getVisits(int index)
{
int count = 0;
foreach (Visit vis in visits)
{
if (index == count)
return vis;
count++;
}
return null;
}
public string VisitDetails()
{
return collect.PickupName + " " + collect.PickupAddress + " Pickup " + reciever.DeliveryName + " " + reciever.DeliveryAddress + " Delivery";
}
}
Related
There is a way to get all items selected with the mouse in a list view when virtual mode is enabled for this winform.
Example of an working code in use, I can retrieve only one selected file for now. Not too much examples finded on the web and could be identified as duplicate but is not conclusive for me, or the answer is to simple.
private void FilesFoundList_RetrieveVirtualItem(object sender, RetrieveVirtualItemEventArgs e)
{
try
{
if (e.ItemIndex >= 0 && e.ItemIndex < ListFilesInfos.Count)
{
try
{
var acc = ListFilesInfos[e.ItemIndex];
//with colors
e.Item = new ListViewItem(new string[] { acc.TagItem, acc.FileName, acc.FilePath.ToString() })
{ Tag = acc,
BackColor = SearchLabColor(0, Path.GetExtension(acc.FileName.ToString()), acc.FilePath.ToString(), acc.FileName.ToString()),
ForeColor = SearchLabColor(1, Path.GetExtension(acc.FileName.ToString()), acc.FilePath.ToString(), acc.FileName.ToString()),
UseItemStyleForSubItems = false
}; // Set Tag object property to our actual AccountInfo object
}
catch { this.Refresh(); }
}
}
catch
{
}
}
private void ShowItemsVirtual(List<SearchFilesInfo> infos)
{
try
{
FilesFoundList.VirtualListSize = infos.Count; // Set number of items in list view
}
catch { this.Refresh(); }
}
private void FilesFoundList_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
{
if (FilesFoundList.VirtualMode == true)
{
SelectedFiles.GlobalVar = (e.Item.SubItems[2]).Text.ToString() + (e.Item.SubItems[1]).Text.ToString();
}
}
You could abbreviate your code to:
List<multiSearchSelect> multiSearchSelect = new List<multiSearchSelect>();
private void FilesFoundList_VirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e)
{
if (FilesFoundList.VirtualMode == true)
{
multiSearchSelect=
FilesFoundList.SelectedIndices
.Select(i=> new multiSearchSelect()
{
fileName = FilesFoundList.Items[i].SubItems[1].Text,
filePath = FilesFoundList.Items[item].SubItems[2].Text
});
}
}
class multiSearchSelect
{
public string fileName { set; get; }
public string filePath { set; get; }
}
I will post my solution that fits to my purpose. I have added ItemsSelectionRangeChanged event and get the list of file selected.
List<multiSearchSelect> multiSearchSelect = new List<multiSearchSelect>();
private void FilesFoundList_VirtualItemsSelectionRangeChanged(object sender, ListViewVirtualItemsSelectionRangeChangedEventArgs e)
{
if (FilesFoundList.VirtualMode == true)
{
multiSearchSelect.Clear();
ListView.SelectedIndexCollection col = FilesFoundList.SelectedIndices;
if (col.Count > 1)
{
foreach (int item in col)
{
multiSearchSelect.Add(new multiSearchSelect
{
fileName = FilesFoundList.Items[item].SubItems[1].Text,
filePath = FilesFoundList.Items[item].SubItems[2].Text
});
}
}
}
}
class multiSearchSelect
{
public string fileName { set; get; }
public string filePath { set; get; }
}
I want to create a generic Datagrid that can paginate. When I call the constructor of my DataGrid_UC and pass 20 Employees it does stores all 20 Employees in AllObject Observable Collection. And filter out the CurrentPageItems to be 5. But upon setting datagrid.ItemsSource = CurrentPageItems it throws null exception but CurrentPageItems does contain 5 items.
DataGrid_UC.xaml
public partial class DataGrid_UC : UserControl
{
private ObservableCollection<object> _currentPageItems;
public ObservableCollection<object> CurrentPageItems
{
get
{
return _currentPageItems;
}
private set
{
if (_currentPageItems != value)
{
_currentPageItems = value;
}
}
}
// Default Entries per page Number
private int _pageSize = 5;
public int PageSize
{
get
{
return _pageSize;
}
set
{
if (_pageSize != value)
{
_pageSize = value;
Reset();
}
}
}
public int TotalPagesNumber
{
get
{
if (AllObjects != null && PageSize > 0)
{
return (AllObjects.Count - 1) / PageSize + 1;
}
return 0;
}
}
private int _currentPageNumber = 1;
public int CurrentPageNumber
{
get
{
return _currentPageNumber;
}
protected set
{
if (_currentPageNumber != value)
{
_currentPageNumber = value;
}
}
}
protected ObservableCollection<object> AllObjects { get; set; }
public DataGrid_UC()
{
InitializeComponent();
dataGrid.ItemsSource = CurrentPageItems;
}
public DataGrid_UC(IEnumerable<object> allObjects, int? entriesPerPage = null)
{
AllObjects = new ObservableCollection<object>(allObjects);
if (entriesPerPage != null)
PageSize = (int)entriesPerPage;
SetCurrentPageItems();
}
#region Public Methods
public void GoToNextPage()
{
if (CurrentPageNumber != TotalPagesNumber)
{
CurrentPageNumber++;
SetCurrentPageItems();
}
}
public void GoToPreviousPage()
{
if (CurrentPageNumber > 1)
{
CurrentPageNumber--;
SetCurrentPageItems();
}
}
#endregion
#region Private Methods
public void SetCurrentPageItems()
{
int upperLimit = CurrentPageNumber * PageSize;
CurrentPageItems =
new ObservableCollection<object>(
AllObjects.Where(x => AllObjects.IndexOf(x) > upperLimit - (PageSize + 1) && AllObjects.IndexOf(x) < upperLimit));
dataGrid.ItemsSource = CurrentPageItems;
}
private void Reset()
{
CurrentPageNumber = 1;
SetCurrentPageItems();
}
#endregion
private void next_Click(object sender, RoutedEventArgs e)
{
if (CurrentPageNumber != TotalPagesNumber)
{
CurrentPageNumber++;
SetCurrentPageItems();
}
}
private void previous_Click(object sender, RoutedEventArgs e)
{
if (CurrentPageNumber > 1)
{
CurrentPageNumber--;
SetCurrentPageItems();
}
}
}
Main Window.xaml
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
List<Employee> emp = new List<Employee>();
for (int i = 0; i < 20; i++)
{
Employee e = new Employee();
e.ID = i;
e.Name = "Test " + i;
emp.Add(e);
}
DataGrid_UC d = new DataGrid_UC(emp, 5);
newContentControl.Content = d;
}
}
The dataGrid member is null because your second constructor is missing the InitializeComponent call, which (among other things) initializes the class members defined in XAML by x:Name.
So change the constructor like this:
public DataGrid_UC(IEnumerable<object> allObjects, int? entriesPerPage = null)
{
InitializeComponent();
AllObjects = new ObservableCollection<object>(allObjects);
...
}
I am a beginner to C# programming.
When I run this program, the eventhandler named - newMessagePublishedEventHandler of the class MessagePool is always null while executing the OnNewMessagePublished() function of the same class.
Can anyone please tell me why? and also how could I resolve this?
namespace ConsoleApp
{
public class MessageEventArgs : System.EventArgs
{
private int publisherId;
private string message;
public MessageEventArgs(int publisherId, string messageText)
{
this.publisherId = publisherId;
this.message = messageText;
}
public int PublisherId
{
get { return publisherId; }
}
public string Message
{
get { return message; }
}
}
public class Publisher
{
private int publisherId;
public Publisher(int publisherId)
{
this.publisherId = publisherId;
}
public int PublisherId
{
get { return publisherId; }
}
public void Publish(string message)
{
MessagePool.GetInstance().Publisher_PostMessage(this.publisherId, message);
Console.WriteLine("published message - " + message);
}
}
public class MessagePool
{
private static MessagePool theOnlyInstanceOfMessageBroker;
public static MessagePool GetInstance()
{
if (theOnlyInstanceOfMessageBroker == null)
{
return new MessagePool();
}
else
{
return theOnlyInstanceOfMessageBroker;
}
}
private MessagePool()
{
}
private EventHandler newMessagePublishedEventHandler;
public event EventHandler NewMessagePublished
{
add
{
newMessagePublishedEventHandler += value;
}
remove
{
newMessagePublishedEventHandler -= value;
}
}
public void Publisher_PostMessage(int publisherId, string message)
{
DateTime publishedTime = DateTime.Now;
this.OnNewMessagePublished(publisherId, message);
}
private void OnNewMessagePublished(int publisherId, string message)
{
MessageEventArgs eventArgs = new MessageEventArgs(publisherId, message);
if (newMessagePublishedEventHandler != null)
{
newMessagePublishedEventHandler(this, eventArgs);
}
}
}
public class Subscriber
{
private int subscriberId;
public Subscriber(int subscriberId)
{
this.subscriberId = subscriberId;
this.SubscribeToMessagebroker();
}
public int SubscriberId
{
get { return subscriberId; }
}
private void SubscribeToMessagebroker()
{
MessagePool.GetInstance().NewMessagePublished -= Subscriber_NewMessageArrived;
MessagePool.GetInstance().NewMessagePublished += Subscriber_NewMessageArrived;
}
private void Subscriber_NewMessageArrived(object sender, EventArgs eventArgs)
{
if (eventArgs != null && eventArgs is MessageEventArgs)
{
var data = eventArgs as MessageEventArgs;
if (data != null)
Console.WriteLine("Recieved message : '" + data.Message + "' from " + data.PublisherId);
}
}
}
class Program
{
static void Main(string[] args)
{
Subscriber subscriber = new Subscriber(1);
Publisher publisher = new Publisher(1001);
publisher.Publish("Hey man.. whats up?");
Console.ReadLine();
}
}
}
MessagePool is not a proper Singleton, you are always returning a new MessagePool.
public class MessagePool
{
private static MessagePool theOnlyInstanceOfMessageBroker;
private static object _syncRoot = new object();
public static MessagePool GetInstance()
{
if (theOnlyInstanceOfMessageBroker == null)
{
lock(_syncRoot)
{
if (theOnlyInstanceOfMessageBroker == null)
theOnlyInstanceOfMessageBroker = new MessagePool();
}
}
return theOnlyInstanceOfMessageBroker;
}
private MessagePool()
{
}
//...
}
I have three classes, and the code is provided below.
Network - Add and Remove Phone, Process Calls. Phone1 and Phone2 can call each other when added to the network.
But I am having an issue when I am connecting both the phone to the network and trying to call phone1 to phone2; it is keeping giving me "receiver busy". I have tried to do a little debugging and read the status of phone2 when calling from phone1, but it returns an empty string (which should actually return "A", when it is added to the network as I am setting its value to "A").
public partial class network : Form
{
phone1 p1 = new phone1();
phone2 p2 = new phone2();
public network()
{
InitializeComponent();
}
public Boolean numberValidator(int number)
{
Boolean exist = false;
if (comboBox2.Items.Equals(number))
{
exist = true;
}
return exist;
}
public void processCall(int rNumber)
{
if (!numberValidator(rNumber))
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Not connected";
}
else
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Call in progress";
p2.receiveCall(1);
p1.setStatus("Busy");
/*
if (p2.btnCallPressStatus())
{
p1.TextBox1.Clear();
p1.TextBox1.Text = "Call initiated";
}*/
}
}
private void button1_Click(object sender, EventArgs e)
{
if (comboBox1.SelectedIndex == 0)
{
p1.Show();
comboBox2.Items.Add(1);
p1.setStatus("A");
}
if (comboBox1.SelectedIndex == 1)
{
p2.Show();
comboBox2.Items.Add(2);
p2.setStatus("A");
}
}
}
----------Phone1 Class---------
public partial class phone1 : Form
{
public phone1()
{
InitializeComponent();
}
string status;
public void setStatus(string Status)
{
status = Status;
}
public string returnStatus()
{
return status;
}
public void receiveCall(int callerNumber)
{
setStatus("Busy");
btnCall.Text = "Answer";
textBox1.Text = "Phone " + callerNumber + " Calling.";
}
public void makeCall(int number)
{
phone2 p2 = new phone2();
network net = new network();
MessageBox.Show(p2.returnStatus()); // this line not returing status of phone2
if (p2.returnStatus() == "A")
{
net.processCall(number);
}
else
{
textBox1.Text = "Receiver Busy";
}
}
public TextBox TextBox1
{
get
{
return textBox1;
}
}
private void btnCall_Click(object sender, EventArgs e)
{
string number = textBox1.Text;
int numberInt = Convert.ToInt16(number);
makeCall(numberInt);
}
string phoneNo = "";
private void btn2_Click(object sender, EventArgs e)
{
phoneNo = phoneNo + btn2.Text;
textBox1.Text = phoneNo;
}
}
-------------phone2 Class--------------
public partial class phone2 : phone1
{
public phone2()
{
InitializeComponent();
}
}
The routine makeCall is creating a new instance of phone2 and calling returnStatus next. The problem is that the string "status" is not Being initialized with any value when p2 is created, so, the returno value will never be "A" and you will always fail the test.
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
Class for downloading attachment looks like:
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()
{
}
}
}
Form looks like this:
namespace DownloadAttachmentExchange
{
public partial class Form1 : Form
{
private string path = "";
public string date = "";
public string attachment = "";
public string subject = "";
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;
}
//("\n" + CurrentDate.ToString() + " , Message id: " + ID + " , Message subject: " + Subject + " , Attachment name: " + AttachementName + "\r");
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//e.Result = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
logOutputTxt.Text = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
//backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}
//private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
//{
// if (e.Cancelled)
// {
// logOutputTxt.Text = "Thread is somehow cancelled, please contact developer for this issue...!";
// }
// else if (e.Error != null)
// {
// logOutputTxt.Text = e.Error.Message;
// }
// else
// {
// logOutputTxt.Text += e.Result;
// }
//}
}
}
as you can see I'm calling background worker from class ExchangeDwnClass which I believe is OK, by using:
form.backgroundWorker1.RunWorkerAsync();
and when I run debugger it really jumps to background worker
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
logOutputTxt.Text = "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
//backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
}
for some reason Form textbox control is not refreshing output.
p.s. I have created also on RunWorkerCompleted method but also without luck...
Any clue how can I work things out?
OK, the problem was that I have created another object in form ExchangeDowClass for Form1, instead of passing a reference object into method GetAttachments
complete code for Form1:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DownloadAttachmentExchange
{
public partial class Form1 : Form
{
private string path = "";
public string subject = "";
public string attachment = "";
public string date = "";
public string sender = "";
public Form1()
{
InitializeComponent();
}
ExchangeDwnClass exchange = new ExchangeDwnClass();
BackgroundWorker bgrWorker = new BackgroundWorker();
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.EmailFetch=Convert.ToInt32(fetchUpDown.Value);
exchange.FilterSender = fromFilterTxt.Text;
exchange.Exchange = exchangeTxt.Text;
exchange.Password = passwdTxt.Text;
exchange.Username = userTxt.Text;
backgroundWorker1.RunWorkerAsync();
}
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;
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
//logOutputTxt.Text += "\n" + date + " , Message subject: " + subject + " , Attachment name: " + attachment + "\r"
//backgroundWorker1.ReportProgress(0);
exchange.GetAttachments(this);
}
private void Form1_Load(object sender, EventArgs e)
{
this.backgroundWorker1.ProgressChanged += new System.ComponentModel.ProgressChangedEventHandler(this.backgroundWorker1_ProgressChanged);
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
logOutputTxt.Text += "\n" + date + " , Sender: "+sender+" , Message subject: " + subject + " , Attachment name: " + attachment + "\r";
}
}
}
and for ExchangeDwnClass:
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(Form1 form)
{
try
{
serv.Credentials = new WebCredentials(Username, Password);
serv.AutodiscoverUrl("username#domain.lan");
ItemView view = new ItemView(EmailFetch);
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().ToLower().Contains(FilterSender) && msg.From.ToString().ToLower().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))
{
file.Load(Path +"\\"+ file.Name);
form.attachment = file.Name.ToString();
form.subject = item.Subject.ToString();
//ID = item.Id.ToString();
form.date = DateTime.Now.ToString();
form.sender = msg.Sender.ToString();
form.backgroundWorker1.ReportProgress(0);
Thread.Sleep(60000);
}
}
}
}
//item.Delete(DeleteMode.HardDelete);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
public void StopDownloadingAttachment()
{
}
}
}
Plus I had to use ProgressChanged method to refresh control...
I still have some minor bugs like double output in textbox form, but this is basically small issue.
I hope this code will be useful to others.
Cheers.