dynamically adding value entered into different control into xml using c# - c#

i am trying to insert the value from control into xml but the record is getting overwriting with the previous one that is only one entry remains in xml file.plz give me solution,my code is like:
namespace StudentApplicationForm
{
public class information
{
private String txtbox1;
private String txtbox2;
private String txtbox3;
public String StudentName
{
get { return txtbox1; }
set{ txtbox1 = value; }
}
public String StudentId
{
get { return txtbox2; }
set{ txtbox2 = value; }
}
public String StudentBranch
{
get { return txtbox3; }
set { txtbox3 = value; }
}
}
}//getter and setter methods
and the file actual insert logic is written is:
public void ok_Click(object sender, EventArgs e)
{
try
{
information info = new information();
List<information> i1 = new List<information>();
XmlSerializer serial = new XmlSerializer(typeof(List<information>));
info.StudentName = textBox1.Text;//id of control
info.StudentId = textBox2.Text;
if (radioButton1.Checked)
{
info.StudentBranch = radioButton1.Text;
}
if (radioButton2.Checked)
{
info.StudentBranch = radioButton2.Text;
}
if (radioButton3.Checked)
{
info.StudentBranch = radioButton3.Text;
}
i1.Add(info);
using (FileStream fs = newFileStream(Environment.CurrentDirectory + "\\mynew.xml", FileMode.Create, FileAccess.Write))
{
serial.Serialize(fs, i1);
MessageBox.Show("Created");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Are you tried like this,
i1.Add(new information{ StudentName = info.StudentName, StudentId = info.StudentId, StudentBranch = info.StudentBranch});

Related

Reordering DatagridViews Columns and Saving the new Position Programmatically

I have a datagridview in my Windows form.I need to allow the users to reorder the columns and then save the changes permanantly.I set
myGrid.AllowUserToOrderColumns = true;
But this only changes the display index on design only.
Maybe an old question but I figured out something I would consider simpler.
First, at the begining of your form class, add the following fields :
public partial class MyForm : Form
{
//So whenever you change the filename, you write it once,
//everyone will be updated
private const string ColumnOrderFileName = "ColumnOrder.bin";
//To prevent saving the data when we don't want to
private bool refreshing = false;
... // the rest of your class
Then, attach to the event ColumnDisplayIndexChanged with the following mehtod :
private void MyDataGridView_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
{
//Because when creating the DataGridView,
//this event will be raised many times and we don't want to save that
if (refreshing)
return;
//We make a dictionary to save each column order along with its name
Dictionary<string, int> order = new Dictionary<string, int>();
foreach (DataGridViewColumn c in dgvInterros.Columns)
{
order.Add(c.Name, c.DisplayIndex);
}
//Then we save this dictionary
//Note that you can do whatever you want with it...
using (FileStream fs = new FileStream(ColumnOrderFileName, FileMode.Create))
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(fs, order);
}
}
Then comes the OrderColumns method :
private void OrderColumns()
{
//Will happen the first time you launch the application,
// or whenever the file is deleted.
if (!File.Exists(ColumnOrderFileName))
return;
using (FileStream fs = new FileStream(ColumnOrderFileName, FileMode.Open))
{
IFormatter formatter = new BinaryFormatter();
Dictionary<string, int> order = (Dictionary<string, int>)formatter.Deserialize(fs);
//Now that the file is open, we run through columns and reorder them
foreach (DataGridViewColumn c in MyDataGridView.Columns)
{
//If columns were added between two versions, we don't bother with it
if (order.ContainsKey(c.Name))
{
c.DisplayIndex = order[c.Name];
}
}
}
}
And finally, when you fill your DataGridView :
private void FillDataGridView()
{
refreshing = true; //To prevent data saving while generating the columns
... //Fill you DataGridView here
OrderColumns(); //Reorder the column from the file
refreshing = false; //Then enable data saving when user will change the order
}
Entity:
public class Customer : INotifyPropertyChanged
{
string _firstname = "";
public string Firstname
{
get { return _firstname; }
set { _firstname = value; OnPropertyChanged("Firstname"); }
}
string _lastname = "";
public string Lastname
{
get { return _lastname; }
set { _lastname = value; OnPropertyChanged("Lastname"); }
}
int _age = 0;
public int Age
{
get { return _age; }
set { _age = value; OnPropertyChanged("Age"); }
}
public Customer()
{
}
protected void OnPropertyChanged(string name)
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(name));
}
public event PropertyChangedEventHandler PropertyChanged;
}
The serializable Proxy:
[Serializable]
public class DataGridViewColumnProxy
{
string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
int _index;
public int Index
{
get { return _index; }
set { _index = value; }
}
public DataGridViewColumnProxy(DataGridViewColumn column)
{
this._name = column.DataPropertyName;
this._index = column.DisplayIndex;
}
public DataGridViewColumnProxy()
{
}
}
[Serializable]
public class DataGridViewColumnCollectionProxy
{
List<DataGridViewColumnProxy> _columns = new List<DataGridViewColumnProxy>();
public List<DataGridViewColumnProxy> Columns
{
get { return _columns; }
set { _columns = value; }
}
public DataGridViewColumnCollectionProxy(DataGridViewColumnCollection columnCollection)
{
foreach (var col in columnCollection)
{
if (col is DataGridViewColumn)
_columns.Add(new DataGridViewColumnProxy((DataGridViewColumn)col));
}
}
public DataGridViewColumnCollectionProxy()
{
}
public void SetColumnOrder(DataGridViewColumnCollection columnCollection)
{
foreach (var col in columnCollection)
if (col is DataGridViewColumn)
{
DataGridViewColumn column = (DataGridViewColumn)col;
DataGridViewColumnProxy proxy = this._columns.FirstOrDefault(p => p.Name == column.DataPropertyName);
if (proxy != null)
column.DisplayIndex = proxy.Index;
}
}
}
My Form1 for testing:
public partial class Form1 : Form
{
BindingSource _customers = GetCustomerList();
public BindingSource Customers
{
get { return _customers; }
set { _customers = value; }
}
public Form1()
{
InitializeComponent();
dataGridView1.DataSource = Customers;
LoadDataGridOrderFromFile("myDataGrid.xml", dataGridView1.Columns);
}
private static BindingSource GetCustomerList()
{
BindingSource customers = new BindingSource();
customers.Add(new Customer() { Firstname = "John", Lastname = "Doe", Age = 28 });
customers.Add(new Customer() { Firstname = "Joanne", Lastname = "Doe", Age = 25 });
return customers;
}
static object fileAccessLock = new object();
private static void SaveDataGridOrderToFile(string path, DataGridViewColumnCollection colCollection)
{
lock (fileAccessLock)
using (FileStream fs = new FileStream(path, FileMode.Create))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataGridViewColumnCollectionProxy));
xmlSerializer.Serialize(fs, new DataGridViewColumnCollectionProxy(colCollection));
}
}
private static void LoadDataGridOrderFromFile(string path, DataGridViewColumnCollection colCollection)
{
if (File.Exists(path))
{
lock (fileAccessLock)
using (FileStream fs = new FileStream(path, FileMode.Open))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(DataGridViewColumnCollectionProxy));
DataGridViewColumnCollectionProxy proxy = (DataGridViewColumnCollectionProxy)xmlSerializer.Deserialize(fs);
proxy.SetColumnOrder(colCollection);
}
}
}
private void dataGridView1_ColumnDisplayIndexChanged(object sender, DataGridViewColumnEventArgs e)
{
SaveDataGridOrderToFile("myDataGrid.xml", dataGridView1.Columns);
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.ColumnDisplayIndexChanged +=dataGridView1_ColumnDisplayIndexChanged;
}
}
It will save the DataPropertyName and the DisplayIndex into a xml file. You can extend / modify it easily where your data have to be stored by implementing your custom save and load methods.
This May Help you
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
m_Grid.AllowUserToOrderColumns = true;
SetDisplayOrder();
}
private void OnFormClosing(object sender, FormClosingEventArgs e)
{
CacheDisplayOrder();
}
private void CacheDisplayOrder()
{
IsolatedStorageFile isoFile =
IsolatedStorageFile.GetUserStoreForAssembly();
using (IsolatedStorageFileStream isoStream = new
IsolatedStorageFileStream("DisplayCache", FileMode.Create,
isoFile))
{
int[] displayIndices =new int[m_Grid.ColumnCount];
for (int i = 0; i < m_Grid.ColumnCount; i++)
{
displayIndices[i] = m_Grid.Columns[i].DisplayIndex;
}
XmlSerializer ser = new XmlSerializer(typeof(int[]));
ser.Serialize(isoStream,displayIndices);
}
}
private void SetDisplayOrder()
{
IsolatedStorageFile isoFile =
IsolatedStorageFile.GetUserStoreForAssembly();
string[] fileNames = isoFile.GetFileNames("*");
bool found = false;
foreach (string fileName in fileNames)
{
if (fileName == "DisplayCache")
found = true;
}
if (!found)
return;
using (IsolatedStorageFileStream isoStream = new
IsolatedStorageFileStream("DisplayCache", FileMode.Open,
isoFile))
{
try
{
XmlSerializer ser = new XmlSerializer(typeof(int[]));
int[] displayIndicies =
(int[])ser.Deserialize(isoStream);
for (int i = 0; i < displayIndicies.Length; i++)
{
m_Grid.Columns[i].DisplayIndex = displayIndicies[i];
}
}
catch { }
}
}
}

Saving keeps overwriting itself C#

I am making an application which will save and load products. These products have three properties of a product name, customer name and firmware location. However, when I try to save them, it will only save one and keeps overwriting with the most recent product saved. The following is my code for the product class:
public class Product
{
//private product data
private string productName;
public string getProductName()
{
return this.productName;
}
public void setProductName (string inProductName)
{
this.productName = inProductName;
}
private string customerName;
public string getCustomerName()
{
return this.customerName;
}
public void setCustomerName (string inCustomerName)
{
this.customerName = inCustomerName;
}
private string firmwareLocation;
public string getFirmwareLocation()
{
return this.firmwareLocation;
}
public void setFirmwareLocation (string inFirmwareLocation)
{
this.firmwareLocation = inFirmwareLocation;
}
//constructor
public Product (string inProductName, string inCustomerName, string inFirmwareLocation)
{
productName = inProductName;
customerName = inCustomerName;
firmwareLocation = inFirmwareLocation;
}
//save method
public void Save (System.IO.TextWriter textOut)
{
textOut.WriteLine(productName);
textOut.WriteLine(customerName);
textOut.WriteLine(firmwareLocation);
}
public bool Save (string filename)
{
System.IO.TextWriter textOut = null;
try
{
textOut = new System.IO.StreamWriter(filename);
Save(textOut);
}
catch
{
return false;
}
finally
{
if (textOut != null)
{
textOut.Close();
}
}
return true;
}
At the end is my save methods.
Here is the code for when the user presses the add product button:
private void Add_Click(object sender, RoutedEventArgs e)
{
//get input from user
string inputCustomerName = customerNameTextBox.Text;
string inputProductName = productNameTextBox.Text;
string inputFirmwareLocation = firmwareTextBox.Text;
try
{
Product newProduct = new Product(inputProductName, inputCustomerName, inputFirmwareLocation);
newProduct.Save("products.txt");
MessageBox.Show("Product added");
}
catch
{
MessageBox.Show("Product could not be added");
}
}
You are not appending the text to your file, thats why it keeps overwriting the last entry over and over again.
Try to change your save method to:
public bool Save (string filename)
{
System.IO.TextWriter textOut = null;
try
{
textOut = new System.IO.StreamWriter(filename, true);
Save(textOut);
}
catch
{
return false;
}
finally
{
if (textOut != null)
{
textOut.Close();
}
}
return true;
}
Notice the "true" as the second parameter in the StreamWriter constructor. This tells the StreamWriter to append the new line.

C# How to load data to messagebox

I have:
private void Tab2KsiazkiBTSzczegoly_Click(object sender, EventArgs e)
{
string KodKsiazki;
KodKsiazki = DataWyszukajKsiazki.Rows[DataWyszukajKsiazki.CurrentCell.RowIndex].Cells[2].Value.ToString();
TSzczegolyDb _szczegoly = new TSzczegolyDb();
Global.listSzczegoly = _szczegoly.GetSZCZEGOLY(KodKsiazki);
//StringBuilder sb = new StringBuilder();
//foreach (DataGridViewCell cell in DataWyszukajKsiazki.SelectedCells)
//{
// sb.AppendLine(cell.Value.ToString());
//}
//MessageBox.Show(sb.ToString());
//}
MessageBox.Show(_szczegoly.ToString());
}
class like that:
public class TSzczegolyDb : Core.CoreMSSQL
{
static string connectionString = TconStrDb.GetConectionString();
public TSzczegolyDb()
: base(connectionString)
{
}
public List<TSzczegolyDto> GetSZCZEGOLY(string co)
{
List<TSzczegolyDto> list = null;
list = new List<TSzczegolyDto>();
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT Tytul, Autorzy, ISBN10, ISBN13, IlStron, Wydawnictwo, Gatunek, Opis FROM dbo.TKsiazki WHERE dbo.TKsiazki.KodKsiazki = '" + co + "'";
SqlDataReader reader = ExecuteQuery(command);
while (reader.Read())
{
TSzczegolyDto message = new TSzczegolyDto();
if (!reader.IsDBNull(0))
{
message.Tytuł = reader.GetString(0);
}
if (!reader.IsDBNull(1))
{
message.Autorzy = reader.GetString(1);
}
if (!reader.IsDBNull(2))
{
message.ISBN10 = reader.GetString(2);
}
if (!reader.IsDBNull(3))
{
message.ISBN13 = reader.GetString(3);
}
if (!reader.IsDBNull(4))
{
message.IlStron = reader.GetInt32(4);
}
if (!reader.IsDBNull(5))
{
message.Wydawnictwo = reader.GetString(5);
}
if (!reader.IsDBNull(6))
{
message.Gatunek = reader.GetString(6);
}
if (!reader.IsDBNull(7))
{
message.Opis = reader.GetString(7);
}
list.Add(message);
}
return list;
}
and second:
public class TSzczegolyDto
{
private string _tytul;
public string Tytuł
{
get { return _tytul; }
set { _tytul = value; }
}
private string _autorzy;
public string Autorzy
{
get { return _autorzy; }
set { _autorzy = value; }
}
private string _ISBN10;
public string ISBN10
{
get { return _ISBN10; }
set { _ISBN10 = value; }
}
private string _ISBN13;
public string ISBN13
{
get { return _ISBN13; }
set { _ISBN13 = value; }
}
private long _ilstron;
public long IlStron
{
get { return _ilstron; }
set { _ilstron = value; }
}
private string _wydawnictwo;
public string Wydawnictwo
{
get { return _wydawnictwo; }
set { _wydawnictwo = value; }
}
private string _gatunek;
public string Gatunek
{
get { return _gatunek; }
set { _gatunek = value; }
}
private string _opis;
public string Opis
{
get { return _opis; }
set { _opis = value; }
}
}
I want show _szczegoly on MessageBox but when I try to MessageBox.Show(_szczegoly.ToString()); then is wrong. In _szczegoly I have string and long type data.
How to create messagebox with this data?
I think you are trying to show an Object with a MessageBox, you need to override the ToString() method to show propertly:
class TSzczegolyDb
{
public override string ToString()
{
return this.Property1 + this.Property2 /*....*/;
}
}

append text to textbox from another class using background worker

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.

Submit button not working

After filling the form when i am clicking on submit button...nothing is happening i mean no events are performed. Pls help me... here is my code..
PatientProperty.cs
public class PatientProperty
{
private string Pdisease;
private string Pname;
private string Pcategory;
private string Paddr;
private DateTime Dateofjoining;
private int Page;
public string PNAME
{
get
{
return Pname;
}
set
{
Pname = value;
}
}
public string PADDRESS
{
get
{
return Paddr;
}
set
{
Paddr = value;
}
}
public int PAGE
{
get
{
return Page;
}
set
{
Page = value;
}
}
public string PDISEASE
{
get
{
return Pdisease;
}
set
{
Pdisease = value;
}
}
public string PCATEGORY
{
get
{
return Pcategory;
}
set
{
Pcategory = value;
}
}
public DateTime DATEOFJOINING
{
get
{
return Dateofjoining;
}
set
{
Dateofjoining = value;
}
}
}
PatientRegistration.cs
public class PatientRegistration
{
string str = ConfigurationManager.ConnectionStrings["HealthCare"].ConnectionString.ToString();
public void InsertPatient(PatientProperty obj)
{
using (var con = new SqlConnection(str))
{
using (var com = new SqlCommand("PatientRegister", con))
{
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("Pname", obj.PNAME);
com.Parameters.AddWithValue("Paddr", obj.PADDRESS);
com.Parameters.AddWithValue("Page", obj.PAGE);
com.Parameters.AddWithValue("Pdisease", obj.PDISEASE);
com.Parameters.AddWithValue("Pcategory", obj.PCATEGORY);
com.Parameters.AddWithValue("Dateofjoining", obj.DATEOFJOINING); con.Open();
com.ExecuteNonQuery();
con.Close();
}
}
}
}
PatientRegistrationBussiness.cs
public class PatientRegistrationBussiness
{
public void AddPatient(PatientProperty obj)
{
PatientRegistration PR = new PatientRegistration();
PR.InsertPatient(obj);
}
}
protected void Button1_Click(object sender, System.EventArgs e)
{
string name = TextBox2.Text;
string address = TextBox3.Text;
string category = RadioButtonList1.Text;
int age =Convert.ToInt32(TextBox4.Text);
string disease = TextBox5.Text;
DateTime date =Convert.ToDateTime(TextBox6.Text);
PatientRegistrationBussiness obj = new PatientRegistrationBussiness();
try
{
PatientProperty PP = new PatientProperty();
PP.PNAME = name;
PP.PADDRESS = address;
PP.PAGE = age;
PP.PDISEASE = disease;
PP.PCATEGORY = category.ToString();
PP.DATEOFJOINING = date;
obj.AddPatient(PP);
Response.Write("Patient details have been successfully added");
TextBox2.Text = string.Empty;
TextBox3.Text = string.Empty;
TextBox4.Text = string.Empty;
TextBox5.Text = string.Empty;
TextBox6.Text = string.Empty;
RadioButtonList1.SelectedIndex = 0;
}
catch (Exception ex)
{
ex.Message.ToString();
}
finally
{
obj = null;
}
}
You have to hook up your events e.g. this.Load += new EventHandler(Page_Load); unless you set the AutoEventWireup="true".
Try putting a breakpoint in the Button1_Click method. In particular, I expect that an exception is being thrown and lost:
catch (Exception ex)
{
ex.Message.ToString();
}
does nothing! Either show the message to the user, or log it somewherre (perhaps Trace.WriteLine(ex)).
Also - don't set obj to null - there is no purpose.

Categories

Resources