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;
}
}
Related
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");
}
}
}
}
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 want to do is for the existing state of the checkbox to be copied once I click a button:
protected void MROSelector_SelectedIndexChanged(object sender, EventArgs e)
{
//Checkbox checking for MRO/MRO50k
if (MROSelector.SelectedIndex == 0)
{
acdMroProj.Visible = true;
acdMroProj_50k.Visible = false;
acdMroProj_50k.Enabled = false;
acdMroProj.Enabled = true;
}
else
{
acdMroProj.Visible = false;
acdMroProj_50k.Visible = true;
acdMroProj.Enabled = false;
acdMroProj_50k.Enabled = true;
}
}
This is the code for both my checkboxes:
public partial class MRO50k : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{ }
private string GetCheckedCBL()
{
string str = "";
bool b = (CheckBoxList1.Items[0].Selected ^ CheckBoxList1.Items[1].Selected);
if (b)
{
if (CheckBoxList1.Items[0].Selected) { str = CheckBoxList1.Items[0].Value; }
if (CheckBoxList1.Items[1].Selected) { str = CheckBoxList1.Items[1].Value; }
}
return str;
}
public string GetSelectedMROProjFilter { get { return GetCheckedCBL(); } }
}
public partial class MROProj : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{ }
private string GetCheckboxListSelection()
{
string str = "";
bool b = (CheckBoxList1.Items[0].Selected ^ CheckBoxList1.Items[1].Selected);
if (b)
{
if (CheckBoxList1.Items[0].Selected) { str = CheckBoxList1.Items[0].Value; }
if (CheckBoxList1.Items[1].Selected) { str = CheckBoxList1.Items[1].Value; }
}
return str;
}
public string GetStrSelection { get { return GetCheckboxListSelection(); } }
}
I have put random numbers into arrays but now I want to prevent it from being shown double in the Listbox. I already got a beginning to start with:
private bool InArray(int getal, int[] getallen, int aantal)
{
}
I think the solution is something like when the number is already in it return true and else just keep going with the code, but I can't think of how I can do this.
This is my code:
namespace Trekking
{
public partial class Form1 : Form
{
private Trekking trekking;
public Form1()
{
InitializeComponent();
btnLaatZien.Enabled = false;
btnSerie.Enabled = false;
btnSorteer.Enabled = false;
btnStart.Enabled = true;
btnStop.Enabled = false;
btnTrek.Enabled = false;
}
private void btnStart_Click(object sender, EventArgs e)
{
int AantalGewenst = Convert.ToInt32(tbInvoerAantalGewenst.Text);
int Maxwaarde = Convert.ToInt32(tbInvoerMaxwaarde.Text);
trekking = new Trekking(Maxwaarde, AantalGewenst);
btnTrek.Enabled = true;
btnStop.Enabled = true;
btnStart.Enabled = false;
if (Maxwaarde > 90)
{
MessageBox.Show("Uw getal mag niet boven de 90 zijn!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else if (Maxwaarde < 0)
{
MessageBox.Show("Dit aantal is niet mogelijk!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else if (AantalGewenst > 45)
{
MessageBox.Show("Uw getal mag niet boven de 45 zijn!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
if (AantalGewenst < 1)
{
MessageBox.Show("Dit aantal is niet mogelijk!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else if (Maxwaarde / AantalGewenst < 2)
{
MessageBox.Show("Uw maxwaarde moet minstens het dubbele van Aantal Gewenst zijn!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else
{
if (AantalGewenst <= 45)
btnStart.Enabled = false;
btnTrek.Enabled = true;
btnStop.Enabled = true;
}
}
public void getSingleNumber(int hoeveel)
{
int Getal = trekking.GeefGetal(hoeveel);
lbResultaat.Items.Add(Getal);
}
public void getTrekkingData()
{
for (int p = 0; p < trekking.AantalGewenst; p++)
{
int alleGetallen = trekking.GeefGetal(p);
lbResultaat.Items.Add(alleGetallen);
}
}
int count = 0;
private void btnTrek_Click(object sender, EventArgs e)
{
int gewenst = trekking.AantalGewenst;
label3.Text = Convert.ToString(count);
btnStop.Enabled = true;
btnSerie.Enabled = false;
trekking.TrekGetal();
getSingleNumber(count);
count++;
if (count == trekking.AantalGewenst)
{
MessageBox.Show("Alle gewenste trekkingen zijn uitgevoerd");
btnTrek.Enabled = false;
btnStop.Enabled = true;
btnSerie.Enabled = false;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
lbResultaat.Items.Clear();
btnLaatZien.Enabled = false;
btnSerie.Enabled = false;
btnSorteer.Enabled = false;
btnStart.Enabled = true;
btnStop.Enabled = false;
btnTrek.Enabled = false;
tbInvoerAantalGewenst.Enabled = true;
tbInvoerMaxwaarde.Enabled = true;
count = 0;
}
private void tbInvoerMaxwaarde_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
e.Handled = !(Char.IsDigit(ch) || (ch == '-') || (ch < ' '));
}
private void k(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
e.Handled = !(Char.IsDigit(ch) || (ch == '-') || (ch < ' '));
}
private bool InArray(int getal, int[] getallen, int aantal)
{
}
}
}
The class:
namespace Trekking
{
class Trekking
{
//attributes
private Random random;
private int[] getallen;
//properties
public int Maxwaarde { get; private set; } //maximum waarde van te trekken getal
public int AantalGetrokken { get; private set; } //aantal getrokken getallen
public int AantalGewenst { get; private set; } //aantal te trekken getallen
public bool IsTenEinde { get; private set; } //true als alle getallen gerokken
//constructor en methoden
public Trekking(int Maxwaarde, int AantalGewenst)
{
this.Maxwaarde = Maxwaarde;
this.AantalGewenst = AantalGewenst;
AantalGetrokken = 0;
IsTenEinde = false;
random = new Random();
getallen = new int[AantalGewenst];
}
//methods
public void TrekGetal()
{
int erbijArray;
for (int i = 0; i < AantalGewenst; i++)
{
erbijArray = random.Next(1, Maxwaarde);
getallen[i] = erbijArray;
AantalGetrokken++;
}
}
public int GeefGetal(int number)
{
return getallen[number];
}
//sorteert getrokken getallen in array "getallen"
public void Sort()
{
Array.Sort(getallen);
}
}
}
I simplified your problem (leaving out min, max, max number etc).
Basically, you can keep a list of things you already encountered:
public class Lottery
{
public HashSet<int> _previousNumbers = new HashSet<int>();
private Random random = new Random();
public int GetNextNumber()
{
int next;
do
{
next = random.Next();
}
while (_previousNumbers.Contains(next));
_previousNumbers.Add(next);
return next;
}
}
A set does not contain duplicates and is efficient in its Contains implementation.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to make a Simon Says game for Windoes Phone 8, and I've hit a wall and can't figure out what's wrong... I'd greatly appreciate some help.
The problems are with the "continueGame" and "initializeColorSequence" paramenters.
Cheers.
{
namespace SimonSez
{
public sealed partial class MainPage : PhoneApplicationPage
{
#region Variables
//Variables
const int colours_amount = 4;
const int colour1 = 1;
const int colour2 = 2;
const int colour3 = 3;
const int colour4= 4;
const int max_seq_count = 100; // TODO: Make 100 for release version
const String startgame_click = "Click to begin!";
const String win = "YOU WIN!";
int currentLengthOfSequence = 0;
Random randomNumber;
int[] correctColorSequence;
int[] playerColorSequence;
int correctColorSequenceIndex = 0;
int playerColorSequenceIndex = 0;
Boolean isPlayerTurn = true;
Boolean isSequenceCorrect = false;
Boolean isGameStarted = false;
Boolean isDoingAnimation = false;
long timeStart, timeEnd, timeDifference;
#endregion
// Constructor
public MainPage()
{
this.InitializeComponent();
randomNumber = new Random();
correctColorSequence = new int[max_seq_count];
playerColorSequence = new int[max_seq_count];
initializeColorSequence();
textBlockRoundNumber.Opacity = 0;
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private void startGame()
{
currentLengthOfSequence = 0;
//textBlockCenter.Text = "Round " + roundNumber;
textBlockRoundNumber.Text = currentLengthOfSequence.ToString();
textBlockRoundNumber.Foreground = new SolidColorBrush(Colors.White);
textBlockRoundNumber.Opacity = 100;
textBlockStartGame.Opacity = 0;
isGameStarted = true;
playerColorSequenceIndex = 0;
initializeColorSequence();
isPlayerTurn = false;
continueGame();
}
private void continueGame()
{
isSequenceCorrect = true;
for (int i = 0; i < playerColorSequenceIndex; i++)
{
if (correctColorSequence[i] == playerColorSequence[i])
{
// do nothing
}
else
{
isSequenceCorrect = false;
break;
}
}
}
private void initializeColorSequence()
{
for (int i = 0; i < max_seq_count; i++)
{
correctColorSequence[i] = randomNumber.Next(1, colours_amount);
playerColorSequence[i] = 0;
}
}
#region Grip Tapping
private void Rect1_Tap(object sender, GestureEventArgs e)
{
if (isPlayerTurn)
{
//storyboardRectangle0Player.Begin();
//audioPiano12.Volume = 0.5;
//audioPiano12.Play();
if (isGameStarted)
{
playerColorSequence[playerColorSequenceIndex++] = colour1;
isPlayerTurn = false;
continueGame();
}
}
}
private void Rect2_Tap(object sender, GestureEventArgs e)
{
if (isPlayerTurn)
{
//storyboardRectangle1Player.Begin();
//audioPiano12.Volume = 0.5;
//audioPiano12.Play();
if (isGameStarted)
{
playerColorSequence[playerColorSequenceIndex++] = colour2;
isPlayerTurn = false;
continueGame();
}
}
}
private void Rect3_Tap(object sender, GestureEventArgs e)
{
if (isPlayerTurn)
{
//storyboardRectangle2Player.Begin();
//audioPiano12.Volume = 0.5;
//audioPiano12.Play();
if (isGameStarted)
{
playerColorSequence[playerColorSequenceIndex++] = colour3;
isPlayerTurn = false;
continueGame();
}
}
}
private void Rect4_Tap(object sender, GestureEventArgs e)
{
if (isPlayerTurn)
{
//storyboardRectangle3Player.Begin();
//audioPiano12.Volume = 0.5;
//audioPiano12.Play();
if (isGameStarted)
{
playerColorSequence[playerColorSequenceIndex++] = colour4;
isPlayerTurn = false;
continueGame();
}
}
}
private void StartGame_Tap(object sender, GestureEventArgs e)
{
if (textBlockStartGame.Text.Equals(startgame_click))
{
if (textBlockStartGame.Opacity != 0)
{
startGame();
}
}
else if (textBlockStartGame.Text.Equals(win))
{
endGame(startgame_click);
}
else
{
// Do nothing
}
}
#endregion
private void continueGame()
{
isSequenceCorrect = true;
for (int i = 0; i < playerColorSequenceIndex; i++)
{
if (correctColorSequence[i] == playerColorSequence[i])
{
// do nothing
}
else
{
isSequenceCorrect = false;
break;
}
}
if (isSequenceCorrect)
{
if (playerColorSequenceIndex >= currentLengthOfSequence)
{
currentLengthOfSequence++;
if (currentLengthOfSequence < max_seq_count)
{
//audioShinyDing.Volume = 0.5;
//audioShinyDing.Play();
textBlockRoundNumber.Text = currentLengthOfSequence.ToString();
}
else // roundNumber == MAX_SEQUENCE_COUNT
{
// audioApplause.Volume = 0.5;
//audioApplause.Play();
endGame(win);
}
}
else // playerColorSequenceIndex < roundNumber
{
//playerColorSequenceIndex++;
isPlayerTurn = true;
}
}
else // isSquenceCorrect == false
{
endGame(startGame);
}
}
private void endGame(String endGameMessage)
{
isGameStarted = false;
textBlockStartGame.Text = endGameMessage;
textBlockStartGame.Opacity = 100;
textBlockRoundNumber.Foreground = new SolidColorBrush(Colors.Gray);
textBlockRoundNumber.Opacity = 40;
isPlayerTurn = true;
}
#region Helper Functions
private void initializeColorSequence()
{
for (int i = 0; i < max_seq_count; i++)
{
correctColorSequence[i] = randomNumber.Next(1, colours_amount);
playerColorSequence[i] = 0;
}
}
private void waitMilliseconds(int waitTime) // Not used
{
timeStart = DateTime.Now.Ticks;
long totalWaitTimeInTicks = waitTime * 10000;
do
{
timeEnd = DateTime.Now.Ticks;
timeDifference = timeEnd - timeStart;
}
while (timeDifference < totalWaitTimeInTicks);
}
#endregion
}
}
}
You seem to have two functions called "continueGame" and also two "initializeColorSequence", hence why it says a member is already defined.
You appear to have defined both of those methods twice in the code you've provided.