Any idea why my visual studio doesn't send to windowsform from pi but it does send when i'm using my school's visual studio ( same version ). Do I have to download any specific thing or whatsoever to make it work? Please help.
Here's my code in case too. Would be cool if some1 can go through it and help me with it ( school's project ) Much appreciated !
string strConnectionString =
ConfigurationManager.ConnectionStrings["DataCommsDBConnection"].ConnectionString;
DataComms dataComms;
public delegate void myprocessDataDelegate(string strData);
private void saveWaterSensorDataToDB(string strTime, string strWaterValue, string strStatus)
{
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "INSERT MySensor (TimeOccurred, SensorValue, SensorStatus) +" +
"VALUES (#time, #value, #status)";
SqlCommand updateCmd = new SqlCommand(strCommandText, myConnect);
updateCmd.Parameters.AddWithValue("#time", strTime);
updateCmd.Parameters.AddWithValue("#value", strWaterValue);
updateCmd.Parameters.AddWithValue("#status", strStatus);
myConnect.Open();
int result = updateCmd.ExecuteNonQuery();
myConnect.Close();
}
private string extractStringValue(string strData, string ID)
{
string result = strData.Substring(strData.IndexOf(ID) + ID.Length);
return result;
}
private float extractFloatValue(string strData, string ID)
{
return (float.Parse(extractStringValue(strData, ID)));
}
private void handleWaterSensorData(string strData, string strTime, string ID)
{
string strWaterValue = extractStringValue(strData, ID);
txtWaterValue.Text = strWaterValue;
txtWaterLevel.Text = strWaterValue;
float fWaterValue = extractFloatValue(strData, ID);
string status = "";
if (fWaterValue <= 500)
status = "Dry";
else
status = "Wet";
txtRoomStatus.Text = status;
}
private void handleButtonData(string strData, string strTime, string ID)
{
string strbuttonValue = extractStringValue(strData, ID);
txtButtonValue.Text = strbuttonValue;
txtDoorBell.Text = strbuttonValue;
}
private void extractSensorData(string strData, string strTime)
{
if (strData.IndexOf("WaterLevel=") != -1)
handleWaterSensorData(strData, strTime, "WaterLevel=");
else if (strData.IndexOf("BUTTON=") != -1)
handleButtonData(strData, strTime, "BUTTON=");
}
public void handleSensorData(string strData)
{
string dt = DateTime.Now.ToString();
extractSensorData(strData, dt);
string strMessage = dt + ":" + strData;
lbDataComms.Items.Insert(0, strMessage);
}
public void processDataReceive(string strData)
{
myprocessDataDelegate d = new myprocessDataDelegate(handleSensorData);
lbDataComms.Invoke(d, new object[] { strData });
}
public void commsDataReceive(string dataReceived)
{
processDataReceive(dataReceived);
}
public void commsSendError(string errMsg)
{
MessageBox.Show(errMsg);
processDataReceive(errMsg);
}
private void InitComms()
{
dataComms = new DataComms();
dataComms.dataReceiveEvent += new DataComms.DataReceivedDelegate(commsDataReceive);
dataComms.dataSendErrorEvent += new DataComms.DataSendErrorDelegate(commsSendError);
}
public frmDataComms()
{
InitializeComponent();
}
private void frmDataComms_Load(object sender, EventArgs e)
{
InitComms();
}
private void btnClear_Click(object sender, EventArgs e)
{
lbDataComms.Items.Clear();
}
private void btnSendLight_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDWATER");
}
private void btnSendButton_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDBUTTON");
}
private void btnCmd_Click(object sender, EventArgs e)
{
dataComms.sendData(txtCmd.Text);
}
private void btnSendAll_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDALL");
}
private void btnSendTemp_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDTEMP");
}
}
Form ***
namespace DataCommsRpi
{
public sealed class StartupTask : IBackgroundTask
{
const int MODE_SENDWATER = 1;
const int MODE_SENDBUTTON = 2;
const int MODE_SENDALL = 3;
const int MODE_SENDTEMP = 4;
static int curMode;
Pin waterPin = Pin.AnalogPin2;
IButtonSensor button = DeviceFactory.Build.ButtonSensor(Pin.DigitalPin4);
Pin tempPin = Pin.AnalogPin0;
DataComms dataComms;
string strDataReceived = "";
private bool buttonPressed = false;
private bool prevButtonStatus = false;
int moistureAdcValue = 800;
double tempDegree = 20;
private bool moistureWet = false;
private bool moistureDry = false;
private bool tempHot = false;
private bool tempCold = false;
private void Sleep(int NoOfMs)
{
Task.Delay(NoOfMs).Wait();
}
private async void startWaterMonitoring()
{
int iPrevAdcValue = 800, iReadAdcValue, iDiff;
await Task.Delay(100);
while (true)
{
Sleep(500);
iReadAdcValue = DeviceFactory.Build.GrovePi().AnalogRead(waterPin);
if (iPrevAdcValue > iReadAdcValue)
iDiff = iPrevAdcValue - iReadAdcValue;
else
iDiff = iReadAdcValue - iPrevAdcValue;
iPrevAdcValue = iReadAdcValue;
if (iDiff < 100)
moistureAdcValue = iReadAdcValue;
}
}
private async void startTempMonitoring()
{
await Task.Delay(100);
int adcValue; double tempCalculated = 0, R;
while (true)
{
Sleep(1000);
adcValue = DeviceFactory.Build.GrovePi().AnalogRead(tempPin);
int B = 4250, R0 = 100000;
R = 100000 * (1023.0 - adcValue) / adcValue;
tempCalculated = 1 / (Math.Log(R / R0) / B + 1 / 298.15) - 273.15;
if (!Double.IsNaN(tempCalculated))
tempDegree = tempCalculated;
}
}
private async void startButtonMonitoring()
{
await Task.Delay(100);
while(true)
{
Sleep(100);
string buttonState = button.CurrentState.ToString();
if (buttonState.Equals("On"))
{
Sleep(100);
buttonState = button.CurrentState.ToString();
if(buttonState.Equals("On"))
{
buttonPressed = true;
}
}
}
}
private void commsDataReceive(string dataReceived)
{
strDataReceived = dataReceived;
Debug.WriteLine("Data Received : " + strDataReceived);
}
private void sendDataToWindows(string strDataOut)
{
try
{
dataComms.sendData(strDataOut);
Debug.WriteLine("Sending Msg : " + strDataOut);
}
catch(Exception)
{
Debug.WriteLine("ERROR. Did you forget to initComms()?");
}
}
private void initComms()
{
dataComms = new DataComms();
dataComms.dataReceiveEvent += new DataComms.DataReceivedDelegate(commsDataReceive);
}
private void handleModeSendWater()
{
if (moistureAdcValue <= 500)
moistureWet = true;
else
moistureWet = false;
if (moistureAdcValue <= 500 && moistureDry != moistureWet)
sendDataToWindows("WaterLevel=" + moistureAdcValue + " wet");
if (moistureAdcValue > 500 && moistureDry != moistureWet)
sendDataToWindows("WaterLevel=" + moistureAdcValue + " dry");
moistureDry = moistureWet;
if (strDataReceived.Equals("SENDBUTTON"))
{
curMode = MODE_SENDBUTTON;
Debug.WriteLine("===Entering MODE_SENDBUTTON===");
}
else if (strDataReceived.Equals("SENDALL"))
{
curMode = MODE_SENDALL;
Debug.WriteLine("===Entering MODE_SENDALL");
}
else if (strDataReceived.Equals("SENDTEMP"))
{
curMode = MODE_SENDTEMP;
Debug.WriteLine("===Entering MODE_SENDTEMP");
}
strDataReceived = "";
}
private void handleModeSendTemperature()
{
if (tempDegree <= 31)
tempCold = true;
else
tempCold = false;
if (tempDegree <= 31 && tempCold != tempHot)
{
Sleep(3000);
sendDataToWindows("Temperature = " + tempDegree.ToString("N2") + " : cold");
}
else if (tempDegree >= 32 && tempCold != tempHot)
{
Sleep(3000);
sendDataToWindows("Temperature = " + tempDegree.ToString("N2") + " : hot");
}
if (strDataReceived.Equals("SENDBUTTON"))
{
curMode = MODE_SENDBUTTON;
Debug.WriteLine("===Entering MODE_SENDBUTTON===");
}
else if (strDataReceived.Equals("SENDALL"))
{
curMode = MODE_SENDALL;
Debug.WriteLine("===Entering MODE_SENDALL");
}
else if (strDataReceived.Equals("SENDWATER"))
{
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER===");
}
}
private void handleModeSendButton()
{
if(buttonPressed != prevButtonStatus)
{
sendDataToWindows("BUTTON=" + buttonPressed);
}
prevButtonStatus = buttonPressed;
buttonPressed = false;
if(strDataReceived.Equals("SENDWATER"))
{
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER===");
}
else if(strDataReceived.Equals("SENDALL"))
{
curMode = MODE_SENDALL;
Debug.WriteLine("===Entering MODE_SENDALL");
}
else if (strDataReceived.Equals("SENDTEMP"))
{
curMode = MODE_SENDTEMP;
Debug.WriteLine("===Entering MODE_SENDTEMP");
}
}
private void handleModeSendAll()
{
Sleep(5000);
sendDataToWindows("Water Level=" + moistureAdcValue);
sendDataToWindows("Temperature = " + tempDegree.ToString("N2"));
if (strDataReceived.Equals("SENDWATER"))
{
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER");
}
else if (strDataReceived.Equals("SENDBUTTON"))
{
curMode = MODE_SENDBUTTON;
Debug.WriteLine("===Entering MODE_SENDBUTTON");
}
else if (strDataReceived.Equals("SENDTEMP"))
{
curMode = MODE_SENDTEMP;
Debug.WriteLine("===Entering MODE_SENDTEMP");
}
}
public void Run(IBackgroundTaskInstance taskInstance)
{
//
// TODO: Insert code to perform background work
//
// If you start any asynchronous methods here, prevent the task
// from closing prematurely by using BackgroundTaskDeferral as
// described in http://aka.ms/backgroundtaskdeferral
//
initComms();
startButtonMonitoring();
startWaterMonitoring();
startTempMonitoring();
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER===");
while (true)
{
Sleep(300);
if (curMode == MODE_SENDWATER)
handleModeSendWater();
else if (curMode == MODE_SENDBUTTON)
handleModeSendButton();
else if (curMode == MODE_SENDALL)
handleModeSendAll();
else if (curMode == MODE_SENDTEMP)
handleModeSendTemperature();
else
Debug.WriteLine("ERROR: Invalid Mode. Please check your logic");
}
}
}
}
Related
I was just wondering, how do I delete the selected datagridview item, therefore deleting the item member in the variable and therefore updating the table and textfile?
frmMainPage:
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Windows.Forms;
using AForge.Video;
using AForge.Imaging;
using AForge.Imaging.Filters;
using AForge;
using AForge.Video.DirectShow;
using System.Drawing.Imaging;
namespace BusinessSoftware
{
public partial class frmMainPage : Form
{
private FilterInfoCollection VideoCaptureDevices;
private VideoCaptureDevice FinalVideoSource;
Bitmap image;
int currentlySelectedRow;
string currentlySelectedName;
int currentlySelectedId;
int currentlySelectedAuthority;
bool isCurrentlyUserLoginPage;
bool isCurrentlyAdminLoginPage;
bool isCurrentlyForgotPasswordPage;
bool isCurrentlyViewEmployeesPage;
bool isCurrentlyScanBarcodePage;
bool isCurrentlyEmployeeFoundPage;
bool isCurrentlyEditEmployeeDetailsPage;
DataTable table = new DataTable();
bool isCurrentlyControlPanelPage;
string txtUsernameFieldPlaceholder;
string btnLoginValue;
string employeeDetailsFileContents;
string userLoginDetailsFileContents;
string[] employeeDetails;
string[] userLoginDetails;
string[] employeeInformationElements;
List<string> employeeDetailElements = new List<string>();
string[] userLoginInformationElements;
List<string> userLoginDetailElements = new List<string>();
string isAUser;
string enteredPassword;
string usernameOfForgottenUser;
string passwordOfForgottenUser;
public frmMainPage()
{
InitializeComponent();
}
private void frmMainPage_Load(object sender, EventArgs e)
{
HideEverything();
btnForgotPassword.Show();
txtUsernameField.Text = txtUsernameFieldPlaceholder;
txtPasswordField.Text = "Password";
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
GlobalVariables.emailSent = false;
btnLoginValue = "Login";
btnLogin.Text = btnLoginValue;
lblLoginTypePage.Text = "User Login";
isCurrentlyUserLoginPage = true;
isCurrentlyAdminLoginPage = false;
isCurrentlyForgotPasswordPage = false;
txtUsernameFieldPlaceholder = "Username";
txtUsernameField.Text = txtUsernameFieldPlaceholder;
GetAndStoreEmployeeInformation();
GetAndStoreUserInformation();
btnFocusOnThis.Text = "";
btnFocusOnThis.Focus();
}
private void btnLoginTypePage_Click(object sender, EventArgs e)
{
if (isCurrentlyUserLoginPage)
{
AdminLoginPage();
}
else if (isCurrentlyAdminLoginPage)
{
UserLoginPage();
}
else
{
UserLoginPage();
}
}
private void txtUsernameField_Leave(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(txtUsernameField.Text))
{
txtUsernameField.Text = txtUsernameFieldPlaceholder;
}
}
private void txtUsernameField_Enter(object sender, EventArgs e)
{
txtUsernameField.Text = "";
}
private void txtPasswordField_Leave(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(txtPasswordField.Text))
{
txtPasswordField.PasswordChar = '\0';
txtPasswordField.Text = "Password";
}
}
private void txtPasswordField_Enter(object sender, EventArgs e)
{
txtPasswordField.Text = "";
txtPasswordField.PasswordChar = '*';
}
private void frmMainPage_MouseClick(object sender, MouseEventArgs e)
{
if (txtPasswordField.Focused || txtUsernameField.Focused)
{
btnFocusOnThis.Focus();
}
}
private void frmLoginPage_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 13 && (txtPasswordField.Focused || txtUsernameField.Focused))
{
btnLogin.PerformClick();
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
if (isCurrentlyAdminLoginPage)
{
if (txtUsernameField.Text == "admin" && txtPasswordField.Text == "password")
{
}
}
else if (isCurrentlyUserLoginPage)
{
enteredPassword = txtPasswordField.Text;
isAUser =
(from p in GlobalVariables.users
where p.Username == txtUsernameField.Text
select p.Password).SingleOrDefault();
if (isAUser != null)
{
if (isAUser == enteredPassword)
{
GlobalVariables.currentUser = txtUsernameField.Text;
ControlPanelPage();
}
else
{
MessageBox.Show("Incorrect Password");
}
}
else
{
MessageBox.Show("User not found!");
}
}
else
{
usernameOfForgottenUser =
(from p in GlobalVariables.users
where p.Email == txtUsernameField.Text
select p.Username).SingleOrDefault();
passwordOfForgottenUser =
(from p in GlobalVariables.users
where p.Email == txtUsernameField.Text
select p.Password).SingleOrDefault();
if (passwordOfForgottenUser != null && usernameOfForgottenUser != null)
{
SendEmail();
}
else
{
MessageBox.Show("Email not registered to user!");
}
}
}
public void AdminLoginPage()
{
btnForgotPassword.Show();
btnFocusOnThis.Focus();
btnLoginTypePage.Text = "User Login";
txtUsernameField.Text = "Username";
lblLoginTypePage.Text = "Administrator Login";
btnLoginValue = "Login";
btnLogin.Text = btnLoginValue;
isCurrentlyUserLoginPage = false;
isCurrentlyAdminLoginPage = true;
isCurrentlyForgotPasswordPage = false;
txtPasswordField.Show();
}
public void ForgotPasswordPage()
{
isCurrentlyForgotPasswordPage = true;
isCurrentlyAdminLoginPage = false;
isCurrentlyUserLoginPage = false;
btnForgotPassword.Hide();
lblLoginTypePage.Text = "Forgot Password";
btnLoginTypePage.Text = "User Login";
btnLoginValue = "Send Email";
btnLogin.Text = btnLoginValue;
txtUsernameFieldPlaceholder = "Email";
txtUsernameField.Text = txtUsernameFieldPlaceholder;
isCurrentlyUserLoginPage = false;
isCurrentlyAdminLoginPage = false;
isCurrentlyForgotPasswordPage = true;
txtPasswordField.Hide();
}
public void UserLoginPage()
{
lblLoginTypePage.Text = "User Login";
btnLoginTypePage.Text = "Admin Login";
txtPasswordField.PasswordChar = '\0';
txtPasswordField.Text = "Password";
btnFocusOnThis.Focus();
btnForgotPassword.Show();
txtUsernameField.Show();
txtPasswordField.Show();
btnLogin.Show();
btnForgotPassword.Show();
btnLoginTypePage.Show();
btnQuit.Show();
lblLoginTypePage.Show();
txtUsernameFieldPlaceholder = "Username";
txtUsernameField.Text = txtUsernameFieldPlaceholder;
btnLoginValue = "Login";
btnLogin.Text = btnLoginValue;
isCurrentlyUserLoginPage = true;
isCurrentlyAdminLoginPage = false;
isCurrentlyForgotPasswordPage = false;
txtPasswordField.Show();
}
public void GetAndStoreEmployeeInformation()
{
employeeDetailsFileContents = System.IO.File.ReadAllText(#"EmployeeDetails.txt");
employeeDetails = employeeDetailsFileContents.Split("\n\r".ToArray(), StringSplitOptions.RemoveEmptyEntries);
GlobalVariables.employees.Clear();
foreach (string line in employeeDetails)
{
employeeInformationElements = line.Split(',');
List<string> employeeDetailElements = new List<string>();
foreach (string element in employeeInformationElements)
{
employeeDetailElements.Add(element);
}
GlobalVariables.employees.Add(new Employee
{
Name = employeeDetailElements[0],
Id = Convert.ToInt32(employeeDetailElements[1]),
Authority = Convert.ToInt32(employeeDetailElements[2])
});
}
}
public void GetAndStoreUserInformation()
{
userLoginDetailsFileContents = System.IO.File.ReadAllText(#"UserLoginDetails.txt");
userLoginDetails = userLoginDetailsFileContents.Split("\n\r".ToArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (string line in userLoginDetails)
{
userLoginInformationElements = line.Split(',');
List<string> userLoginDetailElements = new List<string>();
foreach (string element in userLoginInformationElements)
{
userLoginDetailElements.Add(element);
}
GlobalVariables.users.Add(new User
{
Username = userLoginDetailElements[0],
Email = userLoginDetailElements[1],
Password = userLoginDetailElements[2]
});
}
}
private void btnForgotPassword_Click(object sender, EventArgs e)
{
ForgotPasswordPage();
}
public void SendEmail()
{
string fromaddr = "exampleCompany#gmail.com";
string toaddr = txtUsernameField.Text;
string password = "founder1971";
MailMessage msg = new MailMessage();
msg.Subject = "Username & Password";
msg.From = new MailAddress(fromaddr);
msg.Body = "Your username is: " + usernameOfForgottenUser + "\n" + "Your password is: " + passwordOfForgottenUser + "\n\nRegards,\nThe IT Team.";
msg.To.Add(new MailAddress(toaddr));
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
NetworkCredential nc = new NetworkCredential(fromaddr, password);
smtp.Credentials = nc;
frmAlertBox frm = new frmAlertBox();
frm.Show();
smtp.Send(msg);
GlobalVariables.emailSent = true;
UserLoginPage();
}
public void HideLogin()
{
txtUsernameField.Hide();
txtPasswordField.Hide();
btnLogin.Hide();
btnForgotPassword.Hide();
btnLoginTypePage.Hide();
btnQuit.Hide();
lblLoginTypePage.Hide();
isCurrentlyUserLoginPage = false;
isCurrentlyAdminLoginPage = false;
isCurrentlyForgotPasswordPage = false;
}
public void ControlPanelPage()
{
HideLogin();
HideEverything();
isCurrentlyViewEmployeesPage = false;
isCurrentlyScanBarcodePage = false;
isCurrentlyEmployeeFoundPage = false;
isCurrentlyEditEmployeeDetailsPage = false;
isCurrentlyControlPanelPage = true;
btnLogOut.Show();
btnScanBarcode.Show();
btnViewEmployees.Show();
}
public void HideEverything()
{
btnDelete.Hide();
btnEditEmployeeDetails.Hide();
btnCancelUpdate.Hide();
btnAdd.Hide();
btnCancel.Hide();
btnEditDetails.Hide();
lblEmployeeName.Hide();
lblEmployeeId.Hide();
lblEmployeeAuthority.Hide();
btnForgotPassword.Hide();
btnScanBarcode.Hide();
btnViewEmployees.Hide();
btnLogOut.Hide();
dgvViewEmployees.Hide();
btnBack.Hide();
picScanBarcode.Hide();
txtAuthority.Hide();
txtId.Hide();
txtName.Hide();
lblName.Hide();
picEmployeeFoundImage.Hide();
lblId.Hide();
lblAuthority.Hide();
btnSaveAndUpdate.Hide();
txtScanBarcode.Hide();
picEmployeeImage.Hide();
btnCaptureNewImage.Hide();
txtEmployeeAuthority.Hide();
txtEmployeeId.Hide();
txtEmployeeName.Hide();
btnCaptureNewEmployeeImage.Hide();
}
private void btnQuit_Click(object sender, EventArgs e)
{
this.Close();
Application.Exit();
}
private void btnLogOut_Click(object sender, EventArgs e)
{
HideEverything();
UserLoginPage();
}
private void btnViewEmployees_Click(object sender, EventArgs e)
{
ViewEmployees();
}
public void ViewEmployees()
{
HideEverything();
btnDelete.Show();
btnAdd.Show();
btnEditEmployeeDetails.Show();
txtName.Enabled = false;
txtId.Enabled = false;
txtAuthority.Enabled = false;
btnCaptureNewImage.Show();
dgvViewEmployees.Show();
btnBack.Show();
dgvViewEmployees.DataSource = null;
dgvViewEmployees.Rows.Clear();
dgvViewEmployees.Columns.Clear();
picEmployeeImage.Show();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Id", typeof(string));
table.Columns.Add("Authority", typeof(string));
int x = 0;
Employee employee;
while (x < GlobalVariables.employees.Count())
{
employee = GlobalVariables.employees[x];
table.Rows.Add(employee.Name, employee.Id, employee.Authority);
x++;
}
dgvViewEmployees.DataSource = table;
txtAuthority.Show();
txtId.Show();
txtName.Show();
lblName.Show();
lblId.Show();
lblAuthority.Show();
}
public void ScanBarcode()
{
HideEverything();
picScanBarcode.Show();
btnBack.Show();
txtScanBarcode.Show();
}
public void EmployeeFound(string employeeId)
{
isCurrentlyEmployeeFoundPage = true;
HideEverything();
btnEditDetails.Show();
picEmployeeFoundImage.Show();
btnBack.Show();
lblEmployeeName.Show();
lblEmployeeId.Show();
lblEmployeeAuthority.Show();
txtEmployeeName.Show();
txtEmployeeId.Show();
txtEmployeeAuthority.Show();
string src = "Images\\" + employeeId + ".bmp";
picEmployeeFoundImage.Image = System.Drawing.Image.FromFile(src);
string EmployeeName =
(from x in GlobalVariables.employees
where x.Id == Convert.ToInt32(employeeId)
select x.Name).SingleOrDefault();
int EmployeeAuthority =
(from x in GlobalVariables.employees
where x.Id == Convert.ToInt32(employeeId)
select x.Authority).SingleOrDefault();
txtEmployeeName.Text = EmployeeName;
txtEmployeeId.Text = employeeId;
txtEmployeeAuthority.Text = Convert.ToString(EmployeeAuthority);
}
public void EditEmployeeDetails()
{
HideEverything();
}
private void btnBack_Click(object sender, EventArgs e)
{
HideEverything();
try {
FinalVideoSource.Stop();
} catch
{
}
ControlPanelPage();
isCurrentlyEmployeeFoundPage = false;
}
private void btnScanBarcode_Click(object sender, EventArgs e)
{
ScanBarcode();
}
private void dgvViewEmployees_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
if (e.StateChanged != DataGridViewElementStates.Selected) return;
dgvViewEmployees.Rows.GetRowCount(DataGridViewElementStates.Selected);
Int32 selectedRowCount =
dgvViewEmployees.Rows.GetRowCount(DataGridViewElementStates.Selected);
if (selectedRowCount > 0)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
currentlySelectedRow = dgvViewEmployees.SelectedRows[0].Index;
currentlySelectedName = Convert.ToString(dgvViewEmployees.Rows[currentlySelectedRow].Cells[0].Value);
currentlySelectedId = Convert.ToInt32(dgvViewEmployees.Rows[currentlySelectedRow].Cells[1].Value);
currentlySelectedAuthority = Convert.ToInt32(dgvViewEmployees.Rows[currentlySelectedRow].Cells[2].Value);
}
txtName.Text = currentlySelectedName;
txtId.Text = Convert.ToString(currentlySelectedId);
txtAuthority.Text = Convert.ToString(currentlySelectedAuthority);
try
{
string src = "Images\\" + currentlySelectedId + ".bmp";
picEmployeeImage.Image = System.Drawing.Image.FromFile(src);
picEmployeeImage.Size = new System.Drawing.Size(picEmployeeImage.Width, 300);
}
catch
{
picEmployeeImage.Image = null;
}
}
private void btnSaveAndUpdate_Click(object sender, EventArgs e)
{
SaveAndUpdate();
btnEditEmployeeDetails.Show();
btnSaveAndUpdate.Hide();
}
public void SaveAndUpdate()
{
int currentIndex = dgvViewEmployees.SelectedRows[0].Index;
dgvViewEmployees.Rows[currentIndex].Cells[0].Value = txtName.Text;
dgvViewEmployees.Rows[currentIndex].Cells[1].Value = txtId.Text;
dgvViewEmployees.Rows[currentIndex].Cells[2].Value = txtAuthority.Text;
string fileContents = "";
GlobalVariables.employees[currentIndex].Name = txtName.Text;
GlobalVariables.employees[currentIndex].Id = Convert.ToInt32(txtId.Text);
GlobalVariables.employees[currentIndex].Authority = Convert.ToInt32(txtAuthority.Text);
foreach (Employee employee in GlobalVariables.employees)
{
fileContents = fileContents + employee.Name + "," + employee.Id + "," + employee.Authority + Environment.NewLine;
}
File.Delete(#"EmployeeDetails.txt");
File.WriteAllText(#"EmployeeDetails.txt", fileContents);
GetAndStoreEmployeeInformation();
// ViewEmployees();
}
private void txtScanBarcode_TextChanged(object sender, EventArgs e)
{
if (txtScanBarcode.Text.Length == 6)
{
string isEmployeeFound =
(from x in GlobalVariables.employees
where x.Id == Convert.ToInt32(txtScanBarcode.Text)
select x.Name).SingleOrDefault();
if (isEmployeeFound != null)
{
EmployeeFound(txtScanBarcode.Text);
}
}
}
void VideoShow()
{
VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
FinalVideoSource = new VideoCaptureDevice(VideoCaptureDevices[0].MonikerString);
FinalVideoSource.NewFrame += new NewFrameEventHandler(FinalVideoSource_NewFrame);
FinalVideoSource.Start();
}
void FinalVideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
image = (Bitmap)eventArgs.Frame.Clone();
image = CropBitmap(image, 150, 100, 300, 200);
if (isCurrentlyEmployeeFoundPage == true)
{
picEmployeeFoundImage.Image = image;
} else
{
picEmployeeImage.Image = image;
}
}
private void btnCaptureNewImage_Click(object sender, EventArgs e)
{
if (btnCaptureNewImage.Text == "Capture New Image")
{
VideoShow();
btnCaptureNewImage.Text = "Take Photo";
}
else
{
FinalVideoSource.Stop();
TakePhoto();
btnCaptureNewImage.Text = "Capture New Image";
}
}
public Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight)
{
Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);
Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat);
return cropped;
}
public void TakePhoto()
{
Bitmap bm = new Bitmap(picEmployeeImage.Width, picEmployeeImage.Height);
bm = (Bitmap)picEmployeeImage.Image;
Bitmap bmp = new Bitmap(bm.Width, bm.Height);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(bm, 0, 0, bmp.Width, bmp.Height);
if (currentlySelectedId != 0)
{
bmp.Save(#"Images\\" + currentlySelectedId + ".bmp", ImageFormat.Bmp);
}
}
private void picEmployeeFoundImage_Click(object sender, EventArgs e)
{
}
private void btnEditDetails_Click(object sender, EventArgs e)
{
if (btnEditDetails.Text == "Save Details")
{
txtEmployeeName.Enabled = false;
txtEmployeeId.Enabled = false;
txtEmployeeAuthority.Enabled = false;
btnCancel.Hide();
btnEditDetails.Text = "Edit Details";
btnCaptureNewEmployeeImage.Hide();
}
else
{
txtEmployeeName.Enabled = true;
txtEmployeeId.Enabled = true;
txtEmployeeAuthority.Enabled = true;
btnCancel.Show();
btnEditDetails.Text = "Save Details";
btnCaptureNewEmployeeImage.Show();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
txtEmployeeName.Enabled = false;
txtEmployeeId.Enabled = false;
txtEmployeeAuthority.Enabled = false;
btnCancel.Hide();
btnEditDetails.Text = "Edit Details";
}
private void btnCaptureNewEmployeeImage_Click(object sender, EventArgs e)
{
if (btnCaptureNewImage.Text == "Capture New Image")
{
VideoShow();
btnCaptureNewImage.Text = "Take Photo";
}
else
{
FinalVideoSource.Stop();
TakePhoto();
btnCaptureNewImage.Text = "Capture New Image";
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
currentlySelectedAuthority = 0;
currentlySelectedId = 0;
currentlySelectedName = "";
//this.dgvViewEmployees.Rows.Add("five", "six", "seven");
btnAdd.Text = "Create";
txtEmployeeName.Enabled = true;
txtEmployeeId.Enabled = true;
txtEmployeeAuthority.Enabled = true;
}
private void btnEditEmployeeDetails_Click(object sender, EventArgs e)
{
btnCancelUpdate.Show();
txtName.Enabled = true;
txtId.Enabled = true;
txtAuthority.Enabled = true;
btnEditEmployeeDetails.Hide();
btnSaveAndUpdate.Show();
}
private void btnCancelUpdate_Click(object sender, EventArgs e)
{
btnCancelUpdate.Hide();
btnEditEmployeeDetails.Show();
btnSaveAndUpdate.Hide();
txtName.Enabled = false;
txtId.Enabled = false;
txtAuthority.Enabled = false;
}
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dgvViewEmployees.SelectedCells)
{
string nameToDelete = dgvViewEmployees.Rows[dgvViewEmployees.SelectedRows[0].Index].Cells["Name"].Value.ToString();
}
}
}
}
Classes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessSoftware
{
public class Employee
{
public string Name;
public int Id;
public int Authority;
}
public class User
{
public string Username;
public string Password;
public string Email;
}
public static class GlobalVariables
{
public static List<Employee> employees = new List<Employee>();
public static List<User> users = new List<User>();
public static string currentUser;
public static bool emailSent;
}
}
I have a code that executes every X seconds. And it updates lists that are linked to listboxes in my form.
I would like the listboxes to refresh when the lists are updated.
For now i update them by having a button "refresh" because the button has the access to the listboxes.
private void button3_Click(object sender, EventArgs e)
{
listBox1.DataSource = null;
listBox2.DataSource = null;
listBox3.DataSource = null;
listBox4.DataSource = null;
listBox1.DataSource = subject;
listBox2.DataSource = from;
listBox3.DataSource = date;
listBox4.DataSource = timeLeft;
}
Is there a way to do it without having this button ? Automatically ?
The whole code:
//class email
public class email
{
public string title { get; set; }
public DateTime date { get; set; }
public string sender { get; set; }
public bool treated { get; set; }
public bool toDelete { get; set; }
public email() { }
public email(string eTitle, DateTime eDate, string eSender, bool eTreated, bool eToDelete)
{
title = eTitle;
date = eDate;
sender = eSender;
treated = eTreated;
toDelete = eToDelete;
}
}
//Initialisation de la fenetre principale
public Form1()
{
InitializeComponent();
comboBox1.Text = "30";
label1.Text = "Process stopped";
listBox1.DataSource = subject;
listBox2.DataSource = from;
listBox3.DataSource = date;
listBox4.DataSource = timeLeft;
initiate();
System.Timers.Timer timer = new System.Timers.Timer(10000);
timer.Elapsed += OnTimedEvent;
timer.Enabled = true;
}
//Prise des informations outlook
private static void initiate()
{
if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
{
try
{
app = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
ns = app.GetNamespace("MAPI");
inbox = ns.Folders["Support N2 MAS"].Folders["Inbox"];
items = inbox.Items;
}
catch (COMException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("Please, start outlook..");
}
}
//Run
private void Run_Click(object sender, EventArgs e)
{
isRunning = true;
label1.Text = "Process running";
}
//Stop
private void Stop_Click(object sender, EventArgs e)
{
isRunning = false;
label1.Text = "Process stopped";
}
//Icone barre des taches
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
this.Show();
RemedyMailAlert.Visible = false;
isVisible = true;
}
//Traitement toutes les X secondes
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
if (isRunning)
{
if (Process.GetProcessesByName("OUTLOOK").Count() > 0)
{
try
{
DateTime dateToCheck = DateTime.Now.AddDays(-5);
currentList.Clear();
foreach (Object obj in items)
{
if (obj is Outlook.MailItem)
{
Outlook.MailItem mail = (Outlook.MailItem)obj;
if(mail.CreationTime > dateToCheck && !mail.Subject.ToString().Contains("INC000") && mail.CreationTime < DateTime.Now.AddMinutes(-reminder) && mail.UnRead)
{
email email = new email();
email.title = mail.Subject.ToString();
email.date = mail.CreationTime;
email.sender = mail.SenderName;
email.treated = false;
email.toDelete = false;
currentList.Add(email);
}
}
}
Compare();
Clean();
Display();
}
catch (COMException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show("Please, start outlook..");
}
}
else
{
//doesn't run so we don't do anything..
}
}
//Compare
public static void Compare()
{
for (int i = 0; i < currentList.Count; i++)
{
int a = 0;
for (int j = 0; j < listEmail.Count; j++)
{
if (listEmail[j].date == currentList[i].date && listEmail[j].title == currentList[i].title && listEmail[j].sender == currentList[i].sender)
{
a++;
}
}
if (a == 0)
{
listEmail.Add(currentList[i]);
}
}
}
//Clean
public static void Clean()
{
List<int> toDelete = new List<int>();
for (int i = 0; i < listEmail.Count; i++)
{
int a = 0;
for (int j = 0; j < currentList.Count; j++)
{
if (currentList[j].date != listEmail[i].date || listEmail[i].title != currentList[j].title)
{
a++;
}
}
if (a == currentList.Count)
{
toDelete.Add(i);
}
}
for (int i = 0; i < toDelete.Count; i++)
{
listEmail.RemoveAt(toDelete[i]);
}
}
//Display
public static void Display()
{
fillListBoxes();
//otherthings to come
}
//Traitement pour remplir les listbox
public static void fillListBoxes()
{
subject.Clear();
from.Clear();
date.Clear();
timeLeft.Clear();
for (int i = 0; i < listEmail.Count; i++)
{
subject.Add(listEmail[i].title);
from.Add(listEmail[i].sender);
date.Add(listEmail[i].date.ToShortTimeString());
int time = (int)(DateTime.Now - listEmail[i].date).TotalMinutes;
timeLeft.Add((60 - time).ToString());
listEmail[i].treated = true;
}
}
//reglage du temps du reminder
private void button1_Click(object sender, EventArgs e)
{
reminder = int.Parse(comboBox1.SelectedItem.ToString());
}
private void button3_Click(object sender, EventArgs e)
{
Display();
listBox1.DataSource = null;
listBox2.DataSource = null;
listBox3.DataSource = null;
listBox4.DataSource = null;
listBox1.DataSource = subject;
listBox2.DataSource = from;
listBox3.DataSource = date;
listBox4.DataSource = timeLeft;
}
private void button2_Click(object sender, EventArgs e)
{
this.Hide();
RemedyMailAlert.Visible = true;
isVisible = false;
}
}
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.
I am using this code for paging ,using this i am getting all records in datagridview ,i have set _PateSize = 10;why i am not getting only 10 rows in datagridview,and on click of next button next 10 rows,how do i make this code working ,where i am going wrong
public partial class ShowEngClgList : Form
{
private int _CurrentPage = 1;
private int _PateSize = 10;
public int PageSize
{
get
{
return _PateSize;
}
set
{
_PateSize = value;
}
}
private DataTable _DataSource;
public DataTable DataSource
{
get
{
return _DataSource;
}
set
{
_DataSource = value;
}
}
private int _Width;
public int ControlWidth
{
get
{
if (_Width == 0)
return dataGridView1.Width;
else
return _Width;
}
set
{
_Width = value;
dataGridView1.Width = _Width;
}
}
private int _Height;
public int ControlHeight
{
get
{
if (_Height == 0)
return dataGridView1.Height;
else
return _Height;
}
set
{
_Height = value;
dataGridView1.Height = _Height;
}
}
private string _FirstButtonText = string.Empty;
public string FirstButtonText
{
get
{
if (_FirstButtonText == string.Empty)
return btnFirst.Text;
else
return _FirstButtonText;
}
set
{
_FirstButtonText = value;
btnFirst.Text = _FirstButtonText;
}
}
private string _LastButtonText = string.Empty;
public string LastButtonText
{
get
{
if (_LastButtonText == string.Empty)
return btnLast.Text;
else
return _LastButtonText;
}
set
{
_LastButtonText = value;
btnLast.Text = _LastButtonText;
}
}
private string _PreviousButtonText = string.Empty;
public string PreviousButtonText
{
get
{
if (_PreviousButtonText == string.Empty)
return btnPrevious.Text;
else
return _PreviousButtonText;
}
set
{
_PreviousButtonText = value;
btnPrevious.Text = _PreviousButtonText;
}
}
private string _NextButtonText = string.Empty;
public string NextButtonText
{
get
{
if (_NextButtonText == string.Empty)
return btnNext.Text;
else
return _NextButtonText;
}
set
{
_NextButtonText = value;
btnNext.Text = _NextButtonText;
}
}
public void DataBind(DataTable dataTable)
{
DataSource = dataTable;
dataGridView1.DataSource = ShowData(1);
}
private DataTable ShowData(int pageNumber)
{
DataTable dt = new DataTable();
int startIndex = PageSize * (pageNumber - 1);
var result = DataSource.AsEnumerable().Where((s, k) => (k >= startIndex && k < (startIndex + PageSize)));
foreach (DataColumn colunm in DataSource.Columns)
{
dt.Columns.Add(colunm.ColumnName);
}
foreach (var item in result)
{
dt.ImportRow(item);
}
txtPaging.Text = string.Format("Page {0} Of {1} Pages", pageNumber, (DataSource.Rows.Count / PageSize) + 1);
return dt;
}
public OleDbConnection acccon = null;
public OleDbDataAdapter da = null;
public DataTable dt = null;
public ShowEngClgList()
{
InitializeComponent();
try
{
acccon = new OleDbConnection(#"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=db1.mdb");
acccon.Open();
}
catch (Exception err)
{
}
string sql = "Select EngClgName,EngClgAddress,EngClgEntranceType From EngColeges";
da = new OleDbDataAdapter(sql, acccon);
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
private void btnFirst_Click(object sender, EventArgs e)
{
if (_CurrentPage == 1)
{
MessageBox.Show("You are already on First Page.");
}
else
{
_CurrentPage = 1;
dataGridView1.DataSource = ShowData(_CurrentPage);
}
}
private void btnPrevious_Click(object sender, EventArgs e)
{
if (_CurrentPage == 1)
{
MessageBox.Show("You are already on First page, you can not go to previous of First page.");
}
else
{
_CurrentPage -= 1;
dataGridView1.DataSource = ShowData(_CurrentPage);
}
}
private void btnNext_Click(object sender, EventArgs e)
{
int lastPage = (DataSource.Rows.Count / PageSize) + 1;
if (_CurrentPage == lastPage)
{
MessageBox.Show("You are already on Last page, you can not go to next page of Last page.");
}
else
{
_CurrentPage += 1;
dataGridView1.DataSource = ShowData(_CurrentPage);
}
}
private void btnLast_Click(object sender, EventArgs e)
{
int previousPage = _CurrentPage;
_CurrentPage = (DataSource.Rows.Count / PageSize) + 1;
if (previousPage == _CurrentPage)
{
MessageBox.Show("You are already on Last Page.");
}
else
{
dataGridView1.DataSource = ShowData(_CurrentPage);
}
}
}
thanks in advance for any help
I have this program that creates threads on which i must create queue folders and
check them for files.
Now I noticed my program failed after processing a huge number of files without problems.
I produces a UnauthorizedAccessException so I went looking for that folder and it appears
the folder has been locked out totally?!
Could this be my anti-virus blocking access or is it something I must fix on my thread?
public class worker
{
public bool Stopping = false;
private System.Timers.Timer _timer;
private List<string> _files;
#region Feedback
public event FeedbackHandler Feedback;
public delegate void FeedbackHandler(object sender, string text);
#endregion
#region Properties
private string _name;
public string Name
{
get { return _name; }
}
private string _folder;
public string Folder
{
get { return _folder; }
set { _folder = value; }
}
private string _outfolder = Path.Combine(shared.Root, "out");
public string Outfolder
{
get { return _outfolder; }
set { _outfolder = value; }
}
private string _backupfolder = Path.Combine(shared.Root, "backup");
public string Backupfolder
{
get { return _backupfolder; }
set { _backupfolder = value; }
}
private string _filter = "*.*";
public string Filter
{
get { return _filter; }
set { _filter = value; }
}
private SearchOption _subfolders = SearchOption.TopDirectoryOnly;
public bool Subfolders
{
get { return (_subfolders == SearchOption.AllDirectories); }
set { if (value) { _subfolders = SearchOption.AllDirectories; } else { _subfolders = SearchOption.TopDirectoryOnly; } }
}
#endregion
#region Constructor
public worker(string Name)
{
_name = Name;
_folder = Path.Combine(shared.Root, "queues");
_folder = Path.Combine(_folder, Name);
}
#endregion
#region Destructor
~worker()
{
}
#endregion
#region Control
public void Start()
{
Stopping = false;
Directory.CreateDirectory(_folder);
_timer = new System.Timers.Timer(1);
_timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
_timer.Start();
Feedback(this, "[" + _name + "] started!");
}
public void Stop()
{
Stopping = true;
Feedback(this, "[" + _name + "] stopped...");
}
void _timer_Elapsed(object sender, ElapsedEventArgs e)
{
if (Stopping)
{
_timer.Stop();
_files.Clear();
return;
}
_timer.Stop();
Process();
_timer.Start();
}
#endregion
void Process()
{
if (Directory.Exists(_folder))
{
_files = Directory.GetFiles(_folder, _filter, _subfolders).ToList();
foreach (string _file in _files.ToArray())
{
if (Stopping) { break; }
document _document = new document(_file);
_document.Copy(_backupfolder);
_document.Move(_outfolder);
}
_files = new List<string>();
}
}
}
public class document
{
private string _header;
#region Feedback
public event FeedbackHandler Feedback;
public delegate void FeedbackHandler(object sender, string text);
#endregion
#region Properties
private string _file;
public string File
{
get { return _file; }
}
private job _job;
public job Job
{
get { return _job; }
}
#endregion
#region Constructor
public document(string File)
{
_file = File;
_header = shared.FileOperations.ReadHeader(_file);
_job = new job(_file, _header);
_job.ReadHeader();
}
#endregion Constructor
public void Copy(string Folder)
{
string _backupfile;
_backupfile = Path.Combine(Folder,_job.Name);
_backupfile = Path.Combine(_backupfile,_job.Company);
_backupfile = Path.Combine(_backupfile, DateTime.Now.ToString("yyyy"));
_backupfile = Path.Combine(_backupfile, DateTime.Now.ToString("MMMM"));
Directory.CreateDirectory(_backupfile);
_backupfile = Path.Combine(_backupfile, Path.GetFileName(_file));
shared.FileOperations.CopyFile(_file, _backupfile, true);
}
public void Move(string Folder)
{
string _outfile;
_outfile = Path.Combine(Folder, Path.GetFileNameWithoutExtension(_file));
shared.FileOperations.MoveFile(_file, _outfile, true);
}
}
public struct shared
{
public static string Root
{
get
{
string _base = System.AppDomain.CurrentDomain.BaseDirectory.ToString();
return Directory.GetParent(_base).Parent.FullName.ToString();
}
}
public struct Patterns
{
public const string Header = #"\^?JOB\s(?<JOB>[a-zA-Z0-9]+[0-9]{3})[D]?(?<ACTION>[JFE]+)(?<COMPANY>[A-Z]{2,2})\s" +
#"(?<EMAIL>-emto=.*)?" +
#"-C(?<COPIES>[0-9]{2,2})\s" +
#"-Z""(?<PRINTER>[A-Z0-9]+)""\s" +
#"(?:\^?PAGE 01|(?<FAX>\^?FAX.*)\s\^?PAGE 01?)";
public const string Jump = #"\^PAGE\s[0-9]+";
public const string Pages = #"(\$?PAGE\s)";
public const string Fax = #"\^?FAX FROM_COMPANY\s""(?<FROM>.*)""\s" +
#"\^?FAX FROM_FAX_NUM\s""(?<FFAX>.*)""\s" +
#"\^?FAX FROM_NAME\s""(?<FNAME>.*)""\s" +
#"\^?FAX TO_FAX_NUM\s""(?<TFAX>.*)""\s" +
#"\^?FAX TO_COMPANY\s""(?<TO>.*)""\s" +
#"\^?FAX TO_NAME\s""(?<TNAME>.*)""\s" +
#"\^?FAX WHO\s""(?<WHO>.*)""\s" +
#"\^?FAX ID\s+(?<ID>.*)";
public const string Mail = #"-em([^\s=]+)=(""[^""]*""|[^\s]+)";
public const string Seperator = #"^";
}
public struct FileOperations
{
// Encoding
public static Encoding ReadEncoding = Encoding.GetEncoding(1252);
public static Encoding WriteEncoding = Encoding.UTF8;
// Timeouts
static int Timeout = 1;
static int FileTimeout = 10000; // 10 seconds/file permitted..
// Header
public static string ReadHeader(string SourceFile)
{
return ReadHeader(SourceFile, Patterns.Jump);
}
public static string ReadHeader(string SourceFile, string Beacon)
{
WaitFile(SourceFile);
string r = null;
string l = null;
try
{
StreamReader _reader = new StreamReader(SourceFile, ReadEncoding);
Match _match;
do
{
l = _reader.ReadLine();
r += l + " ";
_match = Regex.Match(l, Beacon);
} while (!_match.Success);
_reader.Close();
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) { throw ex; }
}
return r;
}
// Read Contents
public static List<string> ReadFile(string SourceFile)
{
return ReadFile(SourceFile, Patterns.Seperator);
}
public static List<string> ReadFile(string SourceFile, string Seperator)
{
WaitFile(SourceFile);
List<string> lines = new List<string>();
try
{
StreamReader sr = new StreamReader(SourceFile, Encoding.GetEncoding(1250));
string tmp = null;
string line = null;
while (!sr.EndOfStream)
{
line = sr.ReadLine();
if (!string.IsNullOrEmpty(line) && line.Substring(0, 1) == Seperator)
{
if (!string.IsNullOrEmpty(tmp))
{
lines.Add(tmp);
}
tmp = line.Replace(Seperator, "^");
}
else
{
tmp += Environment.NewLine + line;
}
}
sr.Close();
if (!string.IsNullOrEmpty(tmp))
{
lines.Add(tmp);
}
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) {throw ex;}
}
return lines;
}
// Write Contents
public static void WriteFile(string DestinationFile, List<string> Lines)
{
try
{
File.WriteAllLines(DestinationFile, Lines.ToArray(), WriteEncoding);
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) { throw ex; }
}
}
public static void WriteFile(string DestinationFile, string Contents)
{
try
{
File.WriteAllText(DestinationFile, Contents);
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) { throw ex; }
}
}
// Move File
public static void MoveFile(string SourceFile, string DestinationFile, bool Overwrite)
{
WaitFile(SourceFile);
try
{
string _count = null;
string _destination = Path.GetDirectoryName(DestinationFile);
string _file = Path.GetFileNameWithoutExtension(DestinationFile);
string _extension = Path.GetExtension(DestinationFile);
string[] _files = Directory.GetFiles(_destination, _file + "*");
if (_files.Length > 0)
{
if (Overwrite)
{
for (int x = 0; x <= _files.Length - 1; x++)
{
File.Delete(_files[x]);
}
}
else
{
_count = "_" + (_files.Length - 1).ToString("D4");
}
}
DestinationFile = Path.Combine(_destination, _file + _count + _extension);
File.Move(SourceFile, DestinationFile);
}
catch (Exception ex)
{
if (Debugger.IsAttached) { throw ex; }
}
}
public static void CopyFile(string SourceFile, string DestinationFile, bool Overwrite)
{
WaitFile(SourceFile);
try
{
string _count = null;
string _destination = Path.GetDirectoryName(DestinationFile);
string _file = Path.GetFileNameWithoutExtension(DestinationFile);
string _extension = Path.GetExtension(DestinationFile);
string[] _files = Directory.GetFiles(_destination, _file + "*");
if (_files.Length > 0)
{
if (Overwrite)
{
for (int x = 0; x <= _files.Length - 1; x++)
{
File.Delete(_files[x]);
}
}
else
{
_count = "_" + (_files.Length - 1).ToString("D4");
}
}
DestinationFile = Path.Combine(_destination, _file + _count + _extension);
File.Copy(SourceFile, DestinationFile);
}
catch (Exception ex)
{
if (Debugger.IsAttached) { throw ex; }
}
}
// Delete File
public static void DeleteFile(string SourceFile)
{
WaitFile(SourceFile);
try
{
File.Delete(SourceFile);
}
catch (Exception ex)
{
// todo
if (Debugger.IsAttached) { throw ex; }
}
}
// Check File
static void WaitFile(string SourceFile)
{
Timeout = 1;
while (!File.Exists(SourceFile))
{
System.Threading.Thread.Sleep(Timeout);
Timeout++;
if (Timeout == FileTimeout)
{
// todo
if (Debugger.IsAttached) { throw new Exception("Timout exceeded!"); }
}
}
Timeout = 1;
while (!IsFileReady(SourceFile))
{
System.Threading.Thread.Sleep(Timeout);
Timeout++;
if (Timeout == FileTimeout)
{
// todo
if (Debugger.IsAttached) { throw new Exception("Timout exceeded!"); }
}
}
}
static bool IsFileReady(String SourceFile)
{
try
{
using (FileStream inputStream = File.Open(SourceFile, FileMode.Open, FileAccess.Read, FileShare.None))
{
if (inputStream.Length > 0)
{
return true;
}
else
{
return false;
}
}
}
catch (Exception)
{
return false;
}
}
}
public struct Functions
{
public static string CleanXML(string Text)
{
Text = Text.Replace(#"&", #"&");
Text = Text.Replace(#"<", #"<");
Text = Text.Replace(#">", #">");
Text = Text.Replace(#"""", #""");
Text = Text.Replace(#"'", #"'");
return Text;
}
}
}
void Work(string Name)
{
_worker = _workers.FirstOrDefault(w => w.Name == Name);
if (_worker == null)
{
_worker = new worker(Name);
_worker.Feedback+=new worker.FeedbackHandler(Feedback);
_worker.Folder = Path.Combine(_queuefolder, Name);
_worker.Outfolder = _outfolder;
_worker.Backupfolder = _backupfolder;
_workers.Add(_worker);
Thread _thread = new Thread(_worker.Start);
_thread.Start();
_thread.Join();
}
}
To clarify what i meant:
//worker class
private volatile bool _stopping;
private Thread _thread;
public void Start()
{
_stopping = false;
Directory.CreateDirectory(_folder);
_thread = new Thread(Process);
_thread.Start();
Feedback(this, "[" + _name + "] started!");
}
public void Stop()
{
_stopping = true;
_thread.Join();
Feedback(this, "[" + _name + "] stopped...");
}
private void Process()
{
while(!_stopping)
{
......
Thread.Sleep(100);
}
}
Because the way you are using timers... It's wrong. And while its interesting to know, why windows locks the folder, you should start from doing some refactoring. It might actually solve your problem along the way.