I am not sure which parameters i am meant to pass when calling the function in this If/Else statement.
The If/Else statement is calling 1 of 2 functions, Online_Version or Offline Version.
Code is as follows:
public void Form1_Load(object sender, EventArgs e)
{
if (MessageBox.Show("Would you like to run the Event Register?", "Registration Selection", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
label5.Text = "Event Registration";
textBox1.Select();
this.TopMost = true;
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
var fileSave = new FileStream(fullFileName, FileMode.Create);
fileSave.Close();
OfflineRegister();
}
else
{
label5.Text = "ICAS Register";
textBox1.Select();
this.TopMost = true;
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
var fileSave = new FileStream(fullFileName, FileMode.Create);
fileSave.Close();
OnlineRegister();
}
}
public void Online_Register(object sender, KeyPressEventArgs e)
{
OnlineRegister();
}
public void Offline_Register(object sender, KeyPressEventArgs e)
{
OfflineRegister();
}
public void OnlineRegister()
{
SqlConnection DBConnection = new SqlConnection("Data Source=DATABASE;Initial Catalog=imis;Integrated Security=True");
SqlCommand cmd = new SqlCommand();
Object returnValue;
string txtend = textBox1.Text;
string lastTwoChars = txtend.Substring(txtend.Length - 1);
if (textBox1.Text.Length != 6 && e.KeyChar != '*') return;
//cmd.CommandText = ("SELECT last_name +', '+ first_name +'\t ('+major_key+')\t' from name where id =#Name");
cmd.CommandText = ("SELECT last_name +', '+ first_name from name where id =#Name");
cmd.Parameters.Add(new SqlParameter("Name", textBox1.Text.Replace(#"L", "")));
cmd.CommandType = CommandType.Text;
cmd.Connection = DBConnection;
//Time = DateTime.Now.ToString("HH:mm");
//TimeIn = "Time In: ";
//TimeOut = "Time Out: ";
returnValue = cmd.ExecuteScalar() + "\t (" + textBox1.Text.Replace(#"L", "") + ")";
DBConnection.Close();
if (listBox1.Items.Contains(returnValue))
{
for (int n = listBox1.Items.Count - 1; n >= 0; --n)
{
string removelistitem = returnValue.ToString();
if (listBox1.Items[n].ToString().Contains(removelistitem))
{
listBox1.Items.RemoveAt(n);
//listBox1.Items.Add(removelistitem + " " + 'TimeOut' + 'Time');
}
}
}
else
listBox1.Items.Add(returnValue);
textBox1.Clear();
System.IO.StreamWriter sw = new System.IO.StreamWriter(fullFileName);
foreach (object item in listBox1.Items)
sw.WriteLine(item.ToString());
sw.Flush();
sw.Close();
if (listBox1.Items.Count != 0) { DisableCloseButton(); }
else
{
EnableCloseButton();
}
label6.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance.";
e.Handled = true;
}
public void OfflineRegister()
{
Object returnValue;
string txtend = textBox1.Text;
returnValue = textBox1.Text.Replace(#"*", "");
if (e.KeyChar != '*') return;
{
if (listBox1.Items.Contains(returnValue))
{
for (int n = listBox1.Items.Count - 1; n >= 0; --n)
{
string removelistitem = returnValue.ToString();
if (listBox1.Items[n].ToString().Contains(removelistitem))
{
//listBox1.Items.RemoveAt(n);
}
}
}
else
{
listBox1.Items.Add(returnValue);
textBox1.Clear();
System.IO.StreamWriter sw = new System.IO.StreamWriter(fullFileName);
foreach (object item in listBox1.Items)
sw.WriteLine(item.ToString());
sw.Flush();
sw.Close();
if (listBox1.Items.Count != 0) { DisableCloseButton(); }
else
{
EnableCloseButton();
}
label6.Text = "Currently " + listBox1.Items.Count.ToString() + " in attendance.";
e.Handled = true;
}
}
}
Any help is appreciated!
What you should do is take the code ouf of the Online_Register/Offline_Register event handlers and put it in a different methods called: OnlineRegister and OfflineRegister for example, that way you can do this:
public void Form1_Load(object sender, EventArgs e)
{
if (MessageBox.Show("Would you like to run the Event Register?","Registration Selection", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
label5.Text = "Event Registration";
textBox1.Select();
this.TopMost = true;
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
var fileSave = new FileStream(fullFileName, FileMode.Create);
fileSave.Close();
OfflineRegister();
}
else
{
label5.Text = "ICAS Register";
textBox1.Select();
this.TopMost = true;
this.FormBorderStyle = FormBorderStyle.None;
this.WindowState = FormWindowState.Maximized;
var fileSave = new FileStream(fullFileName, FileMode.Create);
fileSave.Close();
OnlineRegister();
}
}
public void Online_Register(object sender, KeyPressEventArgs e)
{
OnlineRegister();
}
public void Offline_Register(object sender, KeyPressEventArgs e)
{
OfflineRegister();
}
public void OnlineRegister()
{
// Do Stuff
}
public void OfflineRegister()
{
// Do Stuff
}
This is of course assuming that you actually need the KeyPress event handlers.
Explanation
The bottom of the code above shows two methods which I just created. These can be called from within your event handlers and on the Form1_Load event. This is useful as you won't have to repeatedly paste the same code over and over again.
Improvements
You could improve your current scenario by taking the Register code and putting it inside a different class, maybe called, RegisterHelper or something, which serves the purpose of providing logic for Registering users.
Furthermore, you could give your Form a name that's a little more appropriate, instead of Form1.
Check the FullFileName variable value, methods looks perfect. Always segregate the UI and functional events.
Related
I am making an application that has some options in drop-down menus that get populated from the App.Config file. I was testing a reset function when the program stopped doing the reset. My code for Form1 is below:
public Form1()
{
InitializeComponent();
InitializeDropDownMenu();
}
private void InitializeDropDownMenu()
{
//Populate all the menus from app.config
foreach (string s in Properties.Settings.Default.Box1Contents)
{
comboBox1.Items.Add(s);
}
foreach (string s in Properties.Settings.Default.Box2Contents)
{
comboBox2.Items.Add(s);
}
foreach (string s in Properties.Settings.Default.Box3Contents)
{
comboBox3.Items.Add(s);
}
//Controls for drop down menus
this.Controls.Add(comboBox1);
comboBox1.SelectedIndexChanged +=
new System.EventHandler(comboBox1_SelectedIndexChanged);
this.Controls.Add(comboBox2);
comboBox2.SelectedIndexChanged +=
new System.EventHandler(comboBox2_SelectedIndexChanged);
this.Controls.Add(comboBox3);
comboBox3.SelectedIndexChanged +=
new System.EventHandler(comboBox3_SelectedIndexChanged);
//Begin Program with all dDMenus enabled.
comboBox1.Enabled = true;
comboBox2.Enabled = true;
comboBox3.Enabled = true;
}
private void comboBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
DialogResult result = MessageBox.Show(
"Change Viewer to: \r\n" + comboBox1.Text + "\r\n\r\n" + "Confirm?",
"Menu",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
label3.Text = comboBox1.SelectedText;
}
else if( result == DialogResult.No)
{
comboBox1.ResetText();
}
}
private void comboBox2_SelectedIndexChanged(object sender, System.EventArgs e)
{
DialogResult result = MessageBox.Show(
"Change Viewer to: \r\n" + comboBox2.Text + "\r\n\r\n" + "Confirm?",
"Menu",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
label3.Text = comboBox2.SelectedText;
}
else if (result == DialogResult.No)
{
comboBox2.ResetText();
}
}
private void comboBox3_SelectedIndexChanged(object sender, System.EventArgs e)
{
DialogResult result = MessageBox.Show(
"Change Viewer to: \r\n" + comboBox3.Text + "\r\n\r\n" + "Confirm?",
"Menu",
MessageBoxButtons.YesNo,
MessageBoxIcon.Information);
if (result == DialogResult.Yes)
{
label3.Text = comboBox3.SelectedText;
}
else if (result == DialogResult.No)
{
comboBox3.ResetText();
}
}
private void ResetApp()
{
comboBox1.ResetText();
comboBox2.ResetText();
comboBox3.ResetText();
}
private void button1_Click(object sender, EventArgs e)
{
ResetApp();
label3.Text = "ResetApp Ran";
}
Any ideas as to why label3 is always set to null, and why when reset is clicked the ComboBoxes aren't being reset to blanks anymore?
Thank you for your help,
-Arthur
EDIT* I will use Items.Clear(); and then just call InitializeDropDownMenu() in the reset function. Should work for my intended use. Thank you all.
I think the problem is in use of SelectedText. The SelectedTextproperty "Gets or sets the text that is selected in the editable portion of a System.Windows.Forms.ComboBox".
Instead try to use the SelectedItem property.
label1.Text = comboBox1.SelectedItem.ToString();
I'm doing two methods when searching. First retrieving files and then searching in the files.
But in some cases i change only the searching text i search for and i want to repeat the searching in the same directories and files. So how can i make that it will remember the last retrieved files ?
This is the button click event to start the backgorundworker and the searching methods:
private void startButton_Click(object sender, EventArgs e)
{
ListViewCostumControl.lvnf.Items.Clear();
numberoffiles = 0;
numberofrestrictedFiles = 0;
numberofdirs = 0;
label24.Text = "0";
label1.Text = "0";
label15.Text = "0";
Logger.Write("Operation started");
label21.Text = "Phase 1: Retrieving files";
label21.Visible = true;
startButton.Enabled = false;
stopButton.Enabled = true;
pauseresumeButton.Enabled = true;
label1.Select();
timer1.Start();
if (!backgroundWorker1.IsBusy)
{
SetWorkerMode(true);
backgroundWorker1.RunWorkerAsync();
}
}
This is the backgroundworker events in the completed i'm writing to a text file some information but not the whole retrieved files.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
_stopwatch.Restart();
string[] values = textBox1.Text.Split(new string[] { ",," }, StringSplitOptions.None);
DirSearch(textBox3.Text, textBox2.Text, values, worker, e);
_stopwatch.Stop();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
MyProgress mypro = (MyProgress)e.UserState;
ListViewCostumControl.lvnf.Items.Add(mypro.Report1);
label15.Text = mypro.Report2;
label15.Visible = true;
if (ListViewCostumControl.lvnf.Items.Count > 9)
textBox4.Enabled = true;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled == true)
{
label1.Select();
_stopwatch.Stop();
label24.Text = "0";
label5.Text = "00:00:00";
label1.Text = "0";
label11.Text = "0";
label15.Text = "0";
label24.Text = "0";
pauseresumeButton.Enabled = false;
stopButton.Enabled = false;
startButton.Enabled = true;
timer1.Stop();
ListViewCostumControl.lvnf.Items.Clear();
Logger.Write("Operation cancelled");
button4.Enabled = true;
}
if (e.Error != null)
{
}
else
{
label1.Select();
_stopwatch.Stop();
timer1.Stop();
stopButton.Enabled = false;
pauseresumeButton.Enabled = false;
startButton.Enabled = true;
label21.Text = "Last operation ended at: " + DateTime.Now;
Logger.Write("Number of retrieved files: " + numberoffiles);
Logger.Write("Number of restricted files: " + numberofrestrictedFiles);
Logger.Write("Number of searched files: " + numberofdirs);
Logger.Write("Number of results: " + label15.Text);
Logger.Write("Searched root directory: " + textBox3.Text);
Logger.Write("Operation time: " + _stopwatch.Elapsed);
Logger.Write("Operation ended");
Logger.Write(" ");
button4.Enabled = true;
mCompleted = true;
if (mClosePending) this.Close();
}
}
This is the searching methods:
int numberofdirs = 0;
void DirSearch(string rootDirectory, string filesExtension, string[] textToSearch, BackgroundWorker worker, DoWorkEventArgs e)
{
List<string> resultsoftextfound = new List<string>();
List<string> resultsoftextfound1 = new List<string>();
List<string> filePathList = new List<string>();
int numberoffiles = 0;
try
{
filePathList = SearchAccessibleFilesNoDistinct(rootDirectory, null,worker,e).ToList();
}
catch (Exception err)
{
string ad = err.ToString();
}
label21.Invoke((MethodInvoker)delegate
{
label21.Text = "Phase 2: Searching in files";
});
MyProgress myp = new MyProgress();
myp.Report4 = filePathList.Count.ToString();
foreach (string file in filePathList)
{
try
{
_busy.WaitOne();
if (worker.CancellationPending == true)
{
e.Cancel = true;
return;
}
bool reportedFile = false;
for (int i = 0; i < textToSearch.Length; i++)
{
if (File.ReadAllText(file).IndexOf(textToSearch[i], StringComparison.InvariantCultureIgnoreCase) >= 0)
{
resultsoftextfound.Add(file + " " + textToSearch[i]);
if (!reportedFile)
{
numberoffiles++;
myp.Report1 = file;
myp.Report2 = numberoffiles.ToString();
myp.Report3 = textToSearch[i];
backgroundWorker1.ReportProgress(0, myp);
reportedFile = true;
}
}
}
numberofdirs++;
label1.Invoke((MethodInvoker)delegate
{
label1.Text = string.Format("{0}/{1}", numberofdirs, myp.Report4);
label1.Visible = true;
});
}
catch (Exception)
{
}
}
}
And SearchAccessibleFilesNoDistinct method:
string restrictedFile = "";
List<string> restrictedFiles = new List<string>();
int numberofrestrictedFiles = 0;
int numberoffiles = 0;
IEnumerable<string> SearchAccessibleFilesNoDistinct(string root, List<string> files,BackgroundWorker worker, DoWorkEventArgs e)
{
_busy.WaitOne();
if (files == null)
files = new List<string>();
if (Directory.Exists(root))
{
foreach (var file in Directory.EnumerateFiles(root))
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
return files;
}
restrictedFile = file;
string ext = Path.GetExtension(file);
if (!files.Contains(file) && ext == textBox2.Text)
{
files.Add(file);
}
numberoffiles++;
label24.Invoke((MethodInvoker)delegate
{
label24.Text = numberoffiles.ToString();
label24.Visible = true;
});
}
foreach (var subDir in Directory.EnumerateDirectories(root))
{
if (worker.CancellationPending == true)
{
e.Cancel = true;
return files;
}
try
{
SearchAccessibleFilesNoDistinct(subDir, files,worker, e);
}
catch (UnauthorizedAccessException)
{
restrictedFiles.Add(restrictedFile);
numberofrestrictedFiles++;
label11.Invoke((MethodInvoker)delegate
{
label11.Text = numberofrestrictedFiles.ToString();
label11.Visible = true;
});
continue;
}
}
}
return files;
}
The idea is to give the user and option to choose if to save or not somehow the last retrieved files so when he repeat the searching it will not retrieve the whole files over again only will search in them. In other words if i repeat the last searching just make the second method.
I call it Phase 1 and Phase 2.
The problem might be that if i save the last retrieved files to a text files or something like that it might be a large file on the hard disk ?
Another problem is when i type the text to search for in textBox1 if i type two words with a space it's not the same without a space for example: Form1 is not the same as Form 1 How can i make that it will search for both results Form1 and Form 1 ?
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text != "" && textBox3.Text != "" && Directory.Exists(textBox3.Text))
{
startButton.Enabled = true;
Properties.Settings.Default["Setting2"] = textBox1.Text;
Properties.Settings.Default.Save();
}
else
{
startButton.Enabled = false;
}
}
I did that if the user type in the textBox1 ,,
It will consider the text after it as another search text.
void lvnf_SelectedIndexChanged(object sender, EventArgs e)
{
if (ListViewCostumControl.lvnf.SelectedItems.Count > 0)
{
results = new List<int>();
richTextBox1.Text = File.ReadAllText(ListViewCostumControl.lvnf.Items[ListViewCostumControl.lvnf.SelectedIndices[0]].Text);
FileInfo fi = new FileInfo(ListViewCostumControl.lvnf.Items[ListViewCostumControl.lvnf.SelectedIndices[0]].Text);
label17.Text = ExtensionMethods.ToFileSize(fi.Length);
label17.Visible = true;
filePath = Path.GetDirectoryName(fi.FullName);
string word = textBox1.Text;
string[] test = word.Split(new string[] { ",," }, StringSplitOptions.None);
foreach (string myword in test)
{
HighlightPhrase(richTextBox1, myword, Color.Yellow);
label16.Text = results.Count.ToString();
label16.Visible = true;
if (results.Count > 0)
{
numericUpDown1.Maximum = results.Count;
numericUpDown1.Enabled = true;
richTextBox1.SelectionStart = results[(int)numericUpDown1.Value - 1];
richTextBox1.ScrollToCaret();
}
}
}
}
For example if i type to search for Form1,,Form 1
Then it will search for all the results of Form1 and of Form 1
Or if i type Form1,,Help
Then the results will be also for Form1 and for Help.
The question not sure if a problem is more logic. When i type only Form1 should i consider it somehow also as Form 1 or i should leave it as it is now Form1,,Form 1 ?
Before i searched for SwitchCameras and it found results but before that i searched for Switch Cameras and it didn't find any results and i didn't put ,, between the Switch Cameras.
So i think by logic Switch Cameras should also find SwitchCameras.
So how can i change this searching rule so if there is no ,, but there is a space between the words search also for one word ?
Switch Cameras will also find SwitchCameras but Switch,,Cameras might find more results.
So basically I used two speech recognition engines(speechrecog & speechrecog1) and one speech synthesizer. When the speechrecog is asked a question like how are you
it then replies I am fine (if the computer picks 2 from the two numbers 1,2). Then it initializes the second speech recognition engine. When it does its stuff. It then turns the second one off and the first one on again. But the problem is when using the second speech recognition engine it repeats( speech synthesizer) the number of times I have tried the second speech recognition engine out.
Here's my code for that form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Speech.Recognition;
using System.Speech.Synthesis;
using System.Threading;
namespace Project_Juliet
{
public partial class Form11 : Form
{
public Form11()
{
InitializeComponent();
}
class FullScreen
{
public void EnterFullScreenMode(Form targetForm)
{
targetForm.WindowState = FormWindowState.Normal;
targetForm.FormBorderStyle = FormBorderStyle.None;
targetForm.WindowState = FormWindowState.Maximized;
}
public void LeaveFullScreenMode(Form targetForm)
{
targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
targetForm.WindowState = FormWindowState.Normal;
}
}
// System.Globalization.CultureInfo cl2 = new System.Globalization.CultureInfo("en-US");
SpeechRecognitionEngine speechrecog = new SpeechRecognitionEngine(/*new System.Globalization.CultureInfo("en-IN")*/);
SpeechSynthesizer ss = new SpeechSynthesizer();
PromptBuilder pb = new PromptBuilder();
Choices zlist = new Choices();
Form2 frm = new Form2();
FullScreen fs = new FullScreen();
bool SpeechRecognitionState = true;
Choices dirlist = new Choices();
SpeechRecognitionEngine speechrecog1 = new SpeechRecognitionEngine(/*new System.Globalization.CultureInfo("en-IN")*/);
bool sprs2 = false;
Choices us = new Choices();
string dir234;
string[] gm;
private void Form11_Load(object sender, EventArgs e)
{
listBox1.Visible = false;
string dir = "C:/Users/" + Environment.UserName + "/Documents/Juliet/response";
DirectoryInfo dinfo = new DirectoryInfo(dir);
FileInfo[] Files = dinfo.GetFiles("*.txt");
webBrowser1.ScriptErrorsSuppressed = true;
foreach (FileInfo file2 in Files)
{
string yts = ".txt";
listBox1.Items.Add(file2.Name.Replace(yts + "", ""));
}
/* String[] list = new String();
list = listBox1.Items.OfType<string>().ToList();
*/
fs.EnterFullScreenMode(this);
textBox1.Width = toolStrip1.Width - 10;
// toolStripTextBox1.Width = toolStrip1.Width - 30;
// toolStripTextBox1.Select();
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
ss.SelectVoiceByHints(VoiceGender.Female, VoiceAge.Teen);
zlist.Add(new string[] { "exit"});
Grammar gr = new Grammar(new GrammarBuilder(zlist));
gr.Weight = 0.9f;
dirlist.Add(new string[]{"Mr.Danely"});
foreach (FileInfo file2 in Files)
{
string yts = ".txt";
dirlist.Add(file2.Name.Replace(yts + "", ""));
}
Grammar gr1 = new Grammar(new GrammarBuilder(dirlist));
gr1.Weight = 1f;
Grammar tgi = new DictationGrammar();
tgi.Weight = 0.3f;
try
{
if (SpeechRecognitionState == true)
{
speechrecog.RequestRecognizerUpdate();
speechrecog.LoadGrammar(gr);
speechrecog.LoadGrammar(gr1);
speechrecog.LoadGrammar(tgi);
speechrecog.SpeechRecognized += speechrecog_SpeechRecognized;
speechrecog.SetInputToDefaultAudioDevice();
speechrecog.RecognizeAsync(RecognizeMode.Multiple);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
//us.Add(new string[] { "yes","no","good","bad" });
us.Add(new string[] { "exit" });
Grammar gr12 = new Grammar(new GrammarBuilder(us));
if (sprs2 == true)
{
}
}
void speechrecog1_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
if(File.Exists(#"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1//"+e.Result.Text.ToString()+".txt"))
{
string hjjk = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1//" + e.Result.Text.ToString() + ".txt";
StreamReader file = new StreamReader(hjjk);
string readText = file.ReadLine();
file.Close();
ss.Speak(readText);
timer2.Interval = 10;
timer2.Start();
}
}
void speechrecog_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
string igput = e.Result.Text.ToString();
dir234 = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//" + igput + ".txt";
if (igput == "exit")
{
speechrecog.RecognizeAsyncStop();
this.Hide();
frm.Closed += (s, args) => this.Close();
frm.Show();
}
else
{
if (File.Exists(dir234))
{
StreamReader file = new StreamReader(dir234);
string readText = file.ReadLine();
file.Close();
if (readText.Contains("%"))
{
string[] words = readText.Split('%');
Random r = new Random();
int selection = r.Next(1, 3);
if (selection == 1)
{
ss.SpeakAsync(words[0]);
}
if (selection == 2)
{
if (readText.Contains('#'))
{
SpeechRecognitionState = false;
us.Add(new string[] { "exit" });
gm = words[1].Split('#');
string speak = words[0] + gm[0];
ss.SpeakAsync(speak);
List<string> lk = gm.ToList();
lk.RemoveAt(0);
string[] hkl = lk.ToArray<string>();
foreach(string g3 in hkl)
{
if (g3.Contains(".txt"))
{
string fj = g3.Replace(".txt" + "", "");
us.Add(fj);
}
else
{
string fj = g3;
us.Add(fj);
}
}
string dir333 = #"C://Users//" + Environment.UserName + "//Documents//Juliet//response//r1";
Grammar gr12 = new Grammar(new GrammarBuilder(us));
try
{
speechrecog1.RequestRecognizerUpdate();
speechrecog1.LoadGrammar(gr12);
speechrecog1.SpeechRecognized += speechrecog1_SpeechRecognized;
speechrecog1.SetInputToDefaultAudioDevice();
speechrecog1.RecognizeAsync(RecognizeMode.Single);
//speechrecog1.RecognizeAsyncStop();
//speechrecog.RecognizeAsync(RecognizeMode.Multiple);
//_completed.WaitOne(); // wait until speech recognition is completed
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
// timer2.Interval = 7000;
//timer2.Start();
// timer2.Interval = 5000;
//timer2.Start();
}
else
{
string speak = words[0] + words[1];
ss.SpeakAsync(speak);
}
}
}
else
{
ss.Speak(readText);
}
}
else
{
try
{
tabControl1.SelectedIndex = 1;
webBrowser1.Navigate("https://www.google.com/search?q=" + e.Result.Text.ToString());
}
catch (Exception ex)
{
string ggh = "Error"+ex;
}
}
}
/* SpeechRecognitionState = false;
timer1.Interval = 3000;
timer1.Start();
* */
textBox1.Text = "You: "+e.Result.Text.ToString();
}
private void timer1_Tick(object sender, EventArgs e)
{
SpeechRecognitionState = true;
timer1.Stop();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void timer2_Tick(object sender, EventArgs e)
{
//loading the grammar again somehow make the recognition better
speechrecog.UnloadAllGrammars();
Grammar gr1 = new Grammar(new GrammarBuilder(dirlist));
gr1.Weight = 1f;
Grammar tgi = new DictationGrammar();
tgi.Weight = 0.3f;
Grammar gr = new Grammar(new GrammarBuilder(zlist));
gr.Weight = 0.9f;
speechrecog.LoadGrammar(gr);
speechrecog.LoadGrammar(gr1);
speechrecog.LoadGrammar(tgi);
SpeechRecognitionState = true;
speechrecog1.RecognizeAsyncStop();
speechrecog1.UnloadAllGrammars();
timer2.Stop();
}
}
}
For example:
the text file how are you.txt contains:
i am fine. thank you.% how are you#good#bad
and the computer asks if im good and I reply with good. In the good.txt file:
Oh thats cool
the first time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(1 time)
the 2nd time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(repeats it 2 times)
the 3rd time I ask her: How are you?
Reply:I am fine thankyou. How are you
User: good
reply: Oh thats cool(repeats it 3 times)
How do i fix the repetition problem.
Thanks to #Nikolay Shmyrev I found the solution. As he said my event handler was firing twice. So inside it I put a:
try
{
//My code
}
finally
{
speechrecog1.SpeechRecognized -= speechrecog1_SpeechRecognized;
}
(http://s14.directupload.net/images/140127/fooispgt.jpg) Link for image
Please view image for more clarification of the problem bcz i know i'm not able to make it more clear to you.
I want to update data for only those columns which are checked by user via checkboxes and those which are left unchecked don't get updated by NULL value....
what i'm thinking is use 511 if....else conditions each for different update query but it's not possible to implement this.
till now the code for update is this:
else if(update_rdbtn.Checked)
{
FileStream fstream = new FileStream(this.imglocation_lbl.Text, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imgbtarray = br.ReadBytes((int)fstream.Length);
SqlConnection con = new SqlConnection("Data Source=JackSparrow-PC\\sqlexpress;Initial Catalog=HCE_DB;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand("Update StudentInfo SET Rollno='" + this.rollno_txtbox.Text + "',Student_Name='" + this.studname_txtbox.Text + "',F_name='" + this.fname_txtbox.Text + "',D_O_B='" + this.dob_txtbox.Text + "',Address='" + this.address_txtbox.Text + "',Phone='" + this.phone_txtbox.Text + "',Valid_upto='" + this.validupto_txtbox.Text + "',Image=#IMG,Branch='" + this.branch_txtbox.Text + "' WHERE Rollno='" + this.rollno_txtbox.Text + "';", con);
SqlDataReader myReader;
try
{
con.Open();
cmd.Parameters.Add(new SqlParameter("#IMG", imgbtarray));
myReader = cmd.ExecuteReader();
MessageBox.Show("Data has been updated");
myReader.Close();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Code for radio btn on checked changed:
private void update_rdbtn_CheckedChanged(object sender, EventArgs e)
{
update_grpbox.Enabled = true;
studname_txtbox.Enabled = false;
fname_txtbox.Enabled = false;
dob_txtbox.Enabled = false;
branch_txtbox.Enabled = false;
address_txtbox.Enabled = false;
phone_txtbox.Enabled = false;
validupto_txtbox.Enabled = false;
Browse_btn.Enabled = false;
studname_chkbox.Checked = false;
fname_chkbox.Checked = false;
dob_chkbox.Checked = false;
branch_chkbox.Checked = false;
Address_chkbox.Checked = false;
phone_chkbox.Checked = false;
validupto_chkbox.Checked = false;
Uploadimg_chkbox.Checked = false;
}
Code for check boxes:
private void studname_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!studname_chkbox.Checked)
{
studname_txtbox.Enabled = false;
}
else
{
studname_txtbox.Enabled = true;
}
}
private void fname_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!fname_chkbox.Checked)
{
fname_txtbox.Enabled = false;
}
else
{
fname_txtbox.Enabled = true;
}
}
private void dob_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!dob_chkbox.Checked)
{
dob_txtbox.Enabled = false;
}
else
{
dob_txtbox.Enabled = true;
}
}
private void branch_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!branch_chkbox.Checked)
{
branch_txtbox.Enabled = false;
}
else
{
branch_txtbox.Enabled = true;
}
}
private void Address_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!Address_chkbox.Checked)
{
address_txtbox.Enabled = false;
}
else
{
address_txtbox.Enabled = true;
}
}
private void phone_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!phone_chkbox.Checked)
{
phone_txtbox.Enabled = false;
}
else
{
phone_txtbox.Enabled = true;
}
}
private void validupto_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!validupto_chkbox.Checked)
{
validupto_txtbox.Enabled = false;
}
else
{
validupto_txtbox.Enabled = true;
}
}
private void Uploadimg_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!Uploadimg_chkbox.Checked)
{
Browse_btn.Enabled = false;
}
else
{
Browse_btn.Enabled = true;
}
}
I have a windows ATM app and I'm stuck on this part:
I have pin and firstName as private strings and balance as private double.
However, when I try to display the balance in the text area, it just prints 0. Is it because retrieveAccountInformation() has void as the return? How can I change my code so that I can use pin, firstName, and balance in my other methods?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SQLDll;
namespace WindowsFormsApplication14
{
public partial class Form1 : Form
{
private Connection myConnection;
private Statement myStatement;
private ResultSet myResultSet;
String databaseURL = "http://www.boehnecamp.com/phpMyAdmin/razorsql_mysql_bridge.php";
public string pin, firstName, userAccountNumber;
public double balance;
public double withdraw = 0;
public double deposit = 0;
bool buttonClicked;
bool buttonClicked2;
public Form1()
{
InitializeComponent();
try
{
//connect to database
SQL sql = new SQL();
myConnection = sql.getConnection(databaseURL);
//create Statement for executing SQL
myStatement = myConnection.createStatement(databaseURL);
loadAccountNumbers();
updateBalance();
}
catch (Exception)
{
Console.WriteLine("Cannot connect to database server");
}
//close statement and database connection
myStatement.close();
myConnection.close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void setText(string text)
{
}
//load account numbers to ComboBox
private void loadAccountNumbers()
{
//get all account numbers from database
try
{
myResultSet = myStatement.executeQuery("SELECT accountNumber FROM accountInformation");
// add account numbers to ComboBox
while (myResultSet.next())
{
accountNumberComboBox.Items.Add(myResultSet.getString("accountNumber"));
}
myResultSet.close(); // close myResultSet
}//end try
catch (Exception)
{
Console.WriteLine("Error in loadAccountNumbers");
}
}//end method to loadAccountNumbers
private void retrieveAccountInformation()
{
//get account info
try
{
myResultSet = myStatement.executeQuery("SELECT pin, " +
"firstName, balanceAmount FROM accountInformation " +
"WHERE accountNumber = '" + userAccountNumber + "'");
//get next result
if (myResultSet.next())
{
pin = myResultSet.getString("pin");
firstName = myResultSet.getString("firstName");
balance = myResultSet.getDouble("balanceAmount");
}
myResultSet.close(); //close myResultSet
}//end try
catch (Exception)
{
Console.WriteLine("Error in retrieveAccountInformation");
}
}// end method retrieveAccountInformation
//update database after withdrawing
private void updateBalance()
{
//update balance in database
try
{
myStatement.executeUpdate("UPDATE accountInformation" +
" SET balanceAmount = " + balance + " WHERE " +
"accountNumber = '" + userAccountNumber + "'");
}
catch (Exception)
{
Console.WriteLine("Error in updateBalace");
}
}//end method updateBalance
private void accountNumberComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
accountNumberComboBox.Enabled = false;
numberTextField.Text = " ";
messageTextArea.Text = "Enter your PIN #.";
button0.Enabled = true;
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
button9.Enabled = true;
buttonDone.Enabled = true;
retrieveAccountInformation();
}
private void button1_Click(object sender, EventArgs e)
{
setText("1");
numberTextField.Text += "1";
buttonEnter.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
setText("2");
numberTextField.Text += "2";
buttonEnter.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
setText("3");
numberTextField.Text += "3";
buttonEnter.Enabled = true;
}
private void button4_Click(object sender, EventArgs e)
{
setText("4");
numberTextField.Text += "4";
buttonEnter.Enabled = true;
}
private void button5_Click(object sender, EventArgs e)
{
setText("5");
numberTextField.Text += "5";
buttonEnter.Enabled = true;
}
private void button6_Click(object sender, EventArgs e)
{
setText("6");
numberTextField.Text += "6";
buttonEnter.Enabled = true;
}
private void button7_Click(object sender, EventArgs e)
{
setText("7");
numberTextField.Text += "7";
buttonEnter.Enabled = true;
}
private void button8_Click(object sender, EventArgs e)
{
setText("8");
numberTextField.Text += "8";
buttonEnter.Enabled = true;
}
private void button9_Click(object sender, EventArgs e)
{
setText("9");
numberTextField.Text += "9";
buttonEnter.Enabled = true;
}
private void button0_Click(object sender, EventArgs e)
{
setText("0");
numberTextField.Text += "0";
buttonEnter.Enabled = true;
}
private void buttonEnter_Click(object sender, EventArgs e)
{
numberTextField.Text = " ";
buttonEnter.Enabled = false;
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
button5.Enabled = false;
button6.Enabled = false;
button7.Enabled = false;
button8.Enabled = false;
button9.Enabled = false;
button0.Enabled = false;
buttonBalance.Enabled = true;
buttonWithdraw.Enabled = true;
buttonDeposit.Enabled = true;
messageTextArea.Text = "Welcome," + firstName;
updateBalance();
if (buttonClicked == true)
{
withdraw = Double.Parse(numberTextField.Text);
balance = balance - withdraw;
updateBalance();
}
}
private void buttonBalance_Click(object sender, EventArgs e)
{
retrieveAccountInformation();
updateBalance();
messageTextArea.Text=(balance.ToString());
//display balance to messageTextArea
}
private void buttonWithdraw_Click(object sender, EventArgs e)
{
buttonBalance.Enabled = false;
buttonWithdraw.Enabled = false;
button0.Enabled = true;
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
button9.Enabled = true;
messageTextArea.Text = "Enter withdrawal amount:";
buttonClicked = true;
}
private void buttonDone_Click(object sender, EventArgs e)
{
button1.Enabled = false;
button2.Enabled = false;
button3.Enabled = false;
button4.Enabled = false;
button5.Enabled = false;
button6.Enabled = false;
button7.Enabled = false;
button8.Enabled = false;
button9.Enabled = false;
button0.Enabled = false;
buttonEnter.Enabled = false;
buttonBalance.Enabled = false;
buttonWithdraw.Enabled = false;
buttonDone.Enabled = false;
buttonDeposit.Enabled = false;
accountNumberComboBox.Enabled = true;
messageTextArea.Text = "Please select your account number.";
}
private void buttonDeposit_Click(object sender, EventArgs e)
{
buttonBalance.Enabled = false;
buttonWithdraw.Enabled = false;
button0.Enabled = true;
button1.Enabled = true;
button2.Enabled = true;
button3.Enabled = true;
button4.Enabled = true;
button5.Enabled = true;
button6.Enabled = true;
button7.Enabled = true;
button8.Enabled = true;
button9.Enabled = true;
messageTextArea.Text = "Enter deposit amount:";
buttonClicked2 = true;
}
}
}
Because you are using myResultSet.next().
If you have two SQL Statements, eg
SELECT * FROM Users
Go
SELECT * FROM Accounts
Go
if (myResultSet.next()) -> this will read the data returned from the second SQL Statement.
I think this maybe what you are wanting:
string connString = AppConfigurationManager.GetAppSetting("ConnectionString",IsQA);
using (var conn = new SqlConnection(connString))
{
conn.Open();
using (SqlCommand sqlCommand = new SqlCommand("SELECT pin, " +
"firstName, balanceAmount FROM accountInformation " +
"WHERE accountNumber = '" + userAccountNumber + "'", conn))
{
sqlCommand.CommandType = CommandType.Text;
SqlDataReader dr = null;
try
{
dr = sqlCommand.ExecuteReader();
while (dr.Read())
{
pin = dr.getString("pin");
firstName = dr.getString("firstName");
balance = dr.getDouble("balanceAmount");
}
}
catch (SqlException ex)
{
}
catch (Exception ex)
{
}
finally
{
//clean up resources that access Data
if (dr != null)
{
dr.Close();
}
}
}
you can using "out" or "ref" in my opinion
private void retrieveAccountInformation(out string pin, out string firstname, out double balance)
{
//get account info
try
{
myResultSet = myStatement.executeQuery("SELECT pin, " +
"firstName, balanceAmount FROM accountInformation " +
"WHERE accountNumber = '" + userAccountNumber + "'");
//get next result
if (myResultSet.next())
{
pin = myResultSet.getString("pin");
firstName = myResultSet.getString("firstName");
balance = myResultSet.getDouble("balanceAmount");
}
myResultSet.close(); //close myResultSet
}//end try
catch (Exception)
{
Console.WriteLine("Error in retrieveAccountInformation");
}
}// end method retrieveAccountInformation
private void buttonBalance_Click(object sender, EventArgs e)
{
string pin = "";
string firstname = "";
double balance = 0;
retrieveAccountInformation(out string pin, out string firstname, out double balance);
updateBalance();
messageTextArea.Text=(balance.ToString());
//display balance to messageTextArea
}
Because pin, firstName, balance is Local Variable and this method is private void so if you want to get value from a void method. Use in,out variable. This make a method can return multiple value
Morever, what updateBalance() do ? It declared varial and call retrieveAccountInformation method ????
Example :
private void retrieveAccountInformation(out string pin,out string firstname,out double balance)
{
//get account info
try
{
myResultSet = myStatement.executeQuery("SELECT pin, " +
"firstName, balanceAmount FROM accountInformation " +
"WHERE accountNumber = '" + userAccountNumber + "'");
//get next result
if (myResultSet.next())
{
pin = myResultSet.getString("pin");
firstName = myResultSet.getString("firstName");
balance = myResultSet.getDouble("balanceAmount");
}
myResultSet.close(); //close myResultSet
}//end try
catch (Exception)
{
Console.WriteLine("Error in retrieveAccountInformation");
}
}// end method retrieveAccountInformation
private void buttonBalance_Click(object sender, EventArgs e)
{
string pin, firstname;
double balance;
retrieveAccountInformation(pin, firstname, balance);
messageTextArea.Text=(balance.ToString());
//display balance to messageTextArea
}