How to restore data that was backed up in C#? - c#

How to restore data that was backed up in C#? I am trying to figure out how to restore data that was already saved. I think I figured out how to save the data, but when my application was running, I had trouble restoring the data, and I really need help with that?
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;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
namespace Lab09_E00988190
{
public partial class Form1 : Form
{
List<Student> listOfStudents;
int intCurrentStudent = 0;
string fileName;
StreamWriter outputFile;
StreamWriter inputFile;
BinaryFormatter studentFormatter = new BinaryFormatter();
public Form1()
{
InitializeComponent();
listOfStudents = new List<Student>();
txtGPA.Enabled = false;
txtID.Enabled = false;
txtName.Enabled = false;
btnPrevious.Enabled = false;
btnNext.Enabled = false;
btnRegisterStudent.Enabled = false;
}
private void btnNewStudent_Click(object sender, EventArgs e)
{
txtName.Text = "";
txtGPA.Text = "";
txtID.Text = "";
txtName.Enabled = true;
txtGPA.Enabled = true;
txtID.Enabled = true;
txtName.Focus();
btnRegisterStudent.Enabled = true;
btnNewStudent.Enabled = true;
}
private void btnNext_Click(object sender, EventArgs e)
{
intCurrentStudent++;
displayCurrent();
if (intCurrentStudent == listOfStudents.Count - 1)
{
btnNext.Enabled = false;
}
btnPrevious.Enabled = true;
}
private void displayCurrent()
{
txtGPA.Text = listOfStudents[intCurrentStudent].GPA.ToString();
txtName.Text = listOfStudents[intCurrentStudent].Name;
txtID.Text = listOfStudents[intCurrentStudent].ID.ToString();
lblNumberofStudents.Text = listOfStudents[intCurrentStudent].Students.ToString();
}
private void btnPrevious_Click(object sender, EventArgs e)
{
intCurrentStudent--;
displayCurrent();
if (intCurrentStudent == 0)
{
btnPrevious.Enabled = false;
}
btnNext.Enabled = true;
}
private void btnRegisterStudent_Click(object sender, EventArgs e)
{
try
{
if (txtName.Text != "")
{
if (Decimal.Parse(txtGPA.Text) >= 0 && Decimal.Parse(txtGPA.Text) <= 4)
{
listOfStudents.Add(new Student(txtName.Text, txtID.Text, Int32.Parse(lblNumberofStudents.Text), Decimal.Parse(txtGPA.Text)));
txtGPA.Enabled = false;
txtID.Enabled = false;
txtName.Enabled = false;
if (listOfStudents.Count == 0)
{
btnPrevious.Enabled = false;
btnNext.Enabled = false;
}
if (listOfStudents.Count == 1)
{
btnPrevious.Enabled = false;
btnNext.Enabled = false;
}
if (listOfStudents.Count > 1)
{
btnPrevious.Enabled = true;
btnNext.Enabled = true;
}
if (listOfStudents.Count >= 5)
{
btnRegisterStudent.Enabled = false;
btnNewStudent.Enabled = false;
}
}
else
{
MessageBox.Show("GPA can't be less than 0 or greater than 4");
}
}
else
{
MessageBox.Show("GPA must be in numbers!");
}
}
catch
{
MessageBox.Show("Make sure you have all the right information entered there");
}
displaySummary();
}
private void displaySummary()
{
int numberOfStudents = 0;
foreach (Student aStudent in listOfStudents)
{
numberOfStudents += aStudent.Students;
}
lblNumberofStudents.Text = listOfStudents.Count.ToString();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void openFileDialogToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
fileName = openFileDialog1.FileName;
if (!File.Exists(fileName))
{
fileName += ".txt";
}
}
{
try
{
using (Stream inputFile = File.OpenRead(fileName))
{
listOfStudents = (List<Student>)studentFormatter.Deserialize(inputFile);
}
if (listOfStudents.Count == 0)
{
btnPrevious.Enabled = false;
btnNext.Enabled = false;
}
if (listOfStudents.Count == 1)
{
btnPrevious.Enabled = false;
btnNext.Enabled = false;
}
if (listOfStudents.Count > 1)
{
btnPrevious.Enabled = true;
btnNext.Enabled = true;
}
if (listOfStudents.Count >= 5)
{
btnRegisterStudent.Enabled = false;
btnNewStudent.Enabled = false;
}
displaySummary();
displayCurrent();
MessageBox.Show("File backup complete!");
}
catch (ArgumentNullException)
{
MessageBox.Show("You need to select file first!");
}
catch (IOException exception)
{
MessageBox.Show(exception.ToString(), "An IO exception has occured!");
}
}
}
private void saveFileDialogToolStripMenuItem_Click(object sender, EventArgs e)
{
DialogResult result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
fileName = saveFileDialog1.FileName;
if (!File.Exists(fileName))
{
fileName += ".txt";
}
}
try
{
using (Stream outputFile = File.Create(fileName))
{
studentFormatter.Serialize(outputFile, listOfStudents);
}
MessageBox.Show("File restoration complete!");
}
catch (IOException exception)
{
MessageBox.Show(exception.ToString(), "An IO exception has occured!");
}
}
}
}

Related

Multiple errors while trying to download with C#

Introduction:
Hello, I tried doing a program with a WinForms Application that downloads specific .zip files, but I get these errors:
UI look like
Errors what I get
Code:
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;
using System.IO;
using System.Collections;
using System.Net;
using System.Threading;
namespace Universal_Installer
{
public partial class Form1 : Form
{
WebClient wc;
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog def = new FolderBrowserDialog();
def.RootFolder = Environment.SpecialFolder.Desktop;
def.Description = "Select installation location...";
def.ShowNewFolderButton = true;
if (def.ShowDialog() == DialogResult.OK)
{
textBox1.Text = def.SelectedPath;
}
}
private void Button2_Click(object sender, EventArgs e)
{
if (!Directory.Exists(textBox1.Text))
{
MessageBox.Show("The selected path does not exist!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (Directory.Exists(textBox1.Text))
{
string inst_size = "n/a";
string name = "n/a";
bool able = false;
string downloadlink = "n/a";
string PeoplePlaygroundSize = "0.161";
string PrisonArchitectSize = "0.586";
string AnotherBrickInTheMallSize = "0.164";
if (PP.Checked == true)
{
inst_size = PeoplePlaygroundSize;
downloadlink = "(A download link)";
name = "People Playground.zip";
able = true;
}
else if (PA.Checked == true)
{
inst_size = PrisonArchitectSize;
downloadlink = "(A download link)";
name = "Prison Architect.zip";
able = true;
}
else if (ABITM.Checked == true)
{
inst_size = AnotherBrickInTheMallSize;
downloadlink = "(A download link)";
name = "Another Brick In The Mall.zip";
able = true;
}
if (able == false)
{
MessageBox.Show("No checkboxes are checked!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else if (MessageBox.Show("Are you sure you want to install a " + inst_size + " GB game?", "Are you sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
status.Text = "Status: DOWNLOADING (" + inst_size + " GB)";
//////
ABITM.Enabled = false;
PP.Enabled = false;
PA.Enabled = false;
textBox1.Enabled = false;
button1.Enabled = false;
button2.Enabled = false;
//////
Thread thread = new Thread(() =>
{
Uri uri = new Uri(downloadlink);
string filename = System.IO.Path.GetFileName(uri.AbsolutePath);
wc.DownloadFileAsync(uri, textBox1.Text + "/" + filename);
});
thread.Start();
}
}
}
private void FileDownloadComplete(object sender,AsyncCompletedEventArgs e)
{
status.Text = "Status: IDLE";
PBAR.Value = 0;
MessageBox.Show("Download Completed (PATH: "+textBox1.Text+")", "Finished", MessageBoxButtons.OK, MessageBoxIcon.Information);
ABITM.Enabled = true;
PP.Enabled = true;
PA.Enabled = true;
textBox1.Enabled = true;
button1.Enabled = true;
button2.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
wc = new WebClient();
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileCompleted += FileDownloadComplete;
}
private void wc_DownloadProgressChanged(object sender, AsyncCompletedEventArgs e)
{
Invoke(new MethodInvoker(delegate ()
{
PBAR.Minimum = 0;
double recive = double.Parse(e.BytesReceived.ToString());
double total = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = recive / total * 100;
PBAR.Value = int.Parse(Math.Truncate(percentage).ToString());
}));
}
}
}
Help:
Any help? By the way, if you see any text ending with .Text or .Value etc... these mean they are objects.
I really need your help by the way...
According the Official Documentation, the second argument for the DownloadProgressChanged must be DownloadProgressChangedEventArgs instead of AsyncCompletedEventArgs.
private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
Invoke(new MethodInvoker(delegate ()
{
PBAR.Minimum = 0;
double recive = double.Parse(e.BytesReceived.ToString());
double total = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = recive / total * 100;
PBAR.Value = int.Parse(Math.Truncate(percentage).ToString());
}));
}

Dis connect websocket in c# after many minutes

I made a desktop program with c# an use
web socket ((use : https://www.nuget.org/packages/WebSocketSharp/1.0.3-rc11)) into
and server side script is PHP web socket ((use : http://socketo.me/))
but I encountered some errors.
1-When I call the Send method, the readyState switches to 'close' and I have to call Connect method before Send .
2-When The program stays idle for a while connection is close
Please help me 2 errors.
Thank you very much
my code c#:
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using System.Threading.Tasks;
using System.Threading;
using Newtonsoft.Json;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using WebSocketSharp;
using System.Globalization;
namespace MyApp
{
public partial class Form1 : Form
{
public WebSocket ws = new WebSocket("ws://example.com:4563");
private static readonly HttpClient client = new HttpClient();
public int request_id;
public bool online;
public async Task<String> login(String id, String password)
{
var values = new Dictionary<string, string>
{
{ "id",id },
{ "password",password }
};
var content = new FormUrlEncodedContent(values);
var response = await client.PostAsync("https://example.com/Login", content);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
}
public void websocket()
{
button1.Enabled = button4.Enabled = button5.Enabled = false;
ws.OnOpen += (sende, E) =>
{
//conncect app
};
ws.OnClose += (sende, E) =>
{
};
ws.OnMessage += (sende, E) =>
{
dynamic response = JsonConvert.DeserializeObject(E.Data);
switch ((String)response.type)
{
case "push_for_app":
{
label10.Text = (String)response.response;
turn_count = (String)response.response;
if ((String)response.response == "0")
{
button1.Enabled = button4.Enabled = button5.Enabled = false;
}
else if (online) button1.Enabled = true;
}
break;
case "request":
{
switch ((String)response.method)
{
case "logout":
{
if ((String)response.response == "true")
{
groupBox1.Visible = false;
groupBox4.Visible = false;
groupBox1.Visible = false;
groupBox4.Visible = false;
groupBox2.Visible = true;
}
}
break;
case "get_turn_count":
{
label10.Text = (String)response.response;
turn_count = (String)response.response;
if ((String)response.response == "0")
{
button1.Enabled = button4.Enabled = button5.Enabled = false;
}
else if (online) button1.Enabled = true;
}
break;
case "set_online":
{
if ((String)response.response == "is_online")
{
button2.Visible = true;
online = true;
{
var template = new
{
type = "request",
method = "get_turn_count"
};
String output = JsonConvert.SerializeObject(template);
ws.Connect();
ws.Send(output);
}
}
}
break;
case "set_offline":
{
if ((String)response.response == "is_offline")
{
button8.Visible = true;
button1.Enabled = false;
online = false;
}
}
break;
default: break;
}
}
break;
default: break;
}
};
var List = new List<KeyValuePair<String, String>> {
new KeyValuePair<String, String>("api-key", "jshTRHNSDB54n7y4e5nhty"),
new KeyValuePair<String, String>("secret-key", secret_key),
new KeyValuePair<String, String>("type", "app")
};
ws.CustomHeaders = List;
ws.Connect();
}
//login
private void button7_Click(object sender, EventArgs e)
{
Task<String> task = Task.Run(async () => await login(textBox1.Text, textBox3.Text));
task.Wait();
dynamic res = JsonConvert.DeserializeObject(task.Result);
if (res.state == "true")
{
secret_key = res.message;
set_secret(secret_key);
groupBox1.Visible = true;
groupBox4.Visible = true;
groupBox2.Visible = false;
button8.Visible = true;
//connect socket
websocket();
}
else { label11.Text = res.message; }
}
//start app
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
this.ShowInTaskbar = false;
this.StartPosition = FormStartPosition.Manual;
this.Location = new Point(SystemInformation.VirtualScreen.Width - this.Width, SystemInformation.VirtualScreen.Height - this.Height);
this.BringToFront();
this.TopMost = true;
this.Focus();
}
//set offline
private void button2_Click(object sender, EventArgs e)
{
var template = new
{
type = "request_from_pharmacy",
method = "set_offline"
};
String output = JsonConvert.SerializeObject(template);
ws.Connect();
ws.Send(output);
button2.Visible = false;
button8.Visible = true;
}
//set online
private void button8_Click(object sender, EventArgs e)
{
var template = new
{
type = "request",
method = "set_online"
};
String output = JsonConvert.SerializeObject(template);
ws.Connect();
ws.Send(output);
button8.Visible = false;
button2.Visible = true;
}
}
}

Why when trying to download the files again when clicking the start button I'm getting exception on the progressBar? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
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;
using System.IO;
using System.Net;
using System.Xml.Linq;
using System.Diagnostics;
using System.Management;
using System.Runtime.InteropServices;
namespace DownloadFiles
{
public partial class Form1 : Form
{
Stopwatch sw = new Stopwatch();
Stopwatch stopwatch = new Stopwatch();
string filesdirectory = "Downloaded_Files";
string mainurl = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/";
List<string> parsedlinks = new List<string>();
string path_exe = Path.GetDirectoryName(Application.LocalUserAppDataPath);
List<string> results = new List<string>();
List<string> urls = new List<string>();
string radarImageWebAddressP1;
string radarImageWebAddressP2;
public Form1()
{
InitializeComponent();
label3.Text = "";
label4.Text = "";
label5.Text = "";
label7.Text = "";
button2.Enabled = false;
button3.Enabled = false;
filesdirectory = Path.Combine(path_exe, filesdirectory);
if (!Directory.Exists(filesdirectory))
{
Directory.CreateDirectory(filesdirectory);
}
else
{
if (IsDirectoryEmpty(filesdirectory) == false)
{
button3.Enabled = true;
}
}
radarImageWebAddressP1 = "http://www.ims.gov.il/Ims/Pages/RadarImage.aspx?Row=";
radarImageWebAddressP2 = "&TotalImages=10&LangID=1&Location=";
for (int i = 0; i < 9; i++)
{
urls.Add(radarImageWebAddressP1 + i + radarImageWebAddressP2);
}
}
public bool IsDirectoryEmpty(string path)
{
return !Directory.EnumerateFileSystemEntries(path).Any();
}
private string downloadhtml(string url)
{
backgroundWorker1.ReportProgress(0, "Downloading Main Url");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Proxy = null;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
string html = sr.ReadToEnd();
sr.Close();
response.Close();
StreamWriter w = new StreamWriter(path_exe + "\\page.html");
w.Write(html);
w.Close();
return html;
}
int Counter = 0;
int percentage = 0;
int total = 0;
int countfiletodownload = 0;
bool processStatus = false;
private void Parseanddownloadfiles()
{
//downloadhtml(mainurl);
if (bgw.CancellationPending == false)
{
/*backgroundWorker1.ReportProgress(0, "Parsing Links");
HtmlAgilityPack.HtmlWeb hw = new HtmlAgilityPack.HtmlWeb();
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc = hw.Load(path_exe + "\\page.html");
foreach (HtmlAgilityPack.HtmlNode link in doc.DocumentNode.SelectNodes("//a[#href]"))
{
string hrefValue = link.GetAttributeValue("href", string.Empty);
if (hrefValue.Contains("US"))
{
string url = "http://www.usgodae.org/ftp/outgoing/fnmoc/models/navgem_0.5/latest_data/" + hrefValue;
parsedlinks.Add(url);
if (bgw.CancellationPending == true)
return;
}
}*/
parsedlinks = urls;
countfiletodownload = parsedlinks.Count;
total = parsedlinks.Count;
backgroundWorker1.ReportProgress(0, "Downloading Files");
processStatus = true;
for (int i = 0; i < parsedlinks.Count && bgw.CancellationPending == false; i++)
{
try
{
using (WebClient client = new WebClient())
{
sw.Start();
Uri uri = new Uri(parsedlinks[i]);
string filename = "RadarImage" + i.ToString() + ".gif";//parsedlinks[i].Substring(71);
client.DownloadFileAsync(uri, filesdirectory + "\\" + filename);
Counter += 1;
percentage = Counter * 100 / total;
string filenametoreport = filename.Substring(1);
countfiletodownload--;
backgroundWorker1.ReportProgress(percentage, filenametoreport);//countfiletodownload, filenametoreport);
}
}
catch (Exception err)
{
string error = err.ToString();
}
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
BackgroundWorker bgw;
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
bgw = (BackgroundWorker)sender;
if (bgw.CancellationPending == true)
{
return;
}
else
{
Parseanddownloadfiles();
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState.ToString() == "Downloading Main Url")
{
label3.Text = e.UserState.ToString();
}
if (e.UserState.ToString() == "Parsing Links")
{
label3.Text = e.UserState.ToString();
}
if (e.UserState.ToString() == "Downloading Files")
{
label7.Text = countfiletodownload.ToString();//parsedlinks.Count.ToString();
label3.Text = e.UserState.ToString();
}
if (processStatus == true)
{
if (e.UserState.ToString() != "Downloading Files")
{
label4.Text = e.UserState.ToString();
label7.Text = countfiletodownload.ToString();
progressBar1.Value = e.ProgressPercentage;
/*using (var bitmap = new Bitmap(this.Width, this.Height))
{
this.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
bitmap.Save(#"e:\screens\ss.gif" + countscreenshots, System.Drawing.Imaging.ImageFormat.Gif);
countscreenshots += 1;
}*/
}
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
}
else
{
label3.Text = "Download Completed";
stopwatch.Reset();
stopwatch.Stop();
timer1.Stop();
}
if(e.Cancelled)
label3.Text = "Operation Cancelled";
button1.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
label3.Text = "Cancelling Operation";
backgroundWorker1.CancelAsync();
button2.Enabled = false;
timer1.Stop();
stopwatch.Stop();
stopwatch.Reset();
}
private void button1_Click(object sender, EventArgs e)
{
label3.Text = "";
label4.Text = "";
label7.Text = "";
backgroundWorker1.RunWorkerAsync();
timer1.Start();
stopwatch.Start();
button1.Enabled = false;
button2.Enabled = true;
}
private void button3_Click(object sender, EventArgs e)
{
Process.Start(filesdirectory);
}
private void timer1_Tick(object sender, EventArgs e)
{
label5.Text = string.Format("{0:hh\\:mm\\:ss}", stopwatch.Elapsed);
}
}
}
First time it's downloading fine but next time when clicking again the start button(button1) it's showing exception: System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'
I tried to reset the progressBar value to 0 in the start button(button1) click event but it didn't solve the problem.
ArgumentOutOfRangeException: Value of '111' is not valid for 'Value'. 'Value' should be between 'minimum' and 'maximum'.
Parameter name: Value
The ArgumentOutOfRange exception is because you never reset Counter:
You define Counter as class level variable and initialize to 0:
int Counter = 0;
Then in your loop you call:
Counter += 1;
percentage = Counter * 100 / total;
When you click the button to restart the download, Counter still holds the final value of the previous run.
In button1_Click, prior to calling RunWorkerAsync
You need to reset it:
Counter = 0;

I want to update only those columns in my database whose textboxes are enabled and keep previous data for those which are disabled?

(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;
}
}

Sending messages back to a client

I have a client-server applications I wrote in c#.
My server monitors the commands sent to it by the client.
I wish to send a "finish" message back to the client when the process finishes, I'm just not sure how to do it...
Here is my code:
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.Net;
using System.Net.Sockets;
using System.IO;
using System.Management;
using Microsoft.Win32;
namespace RM
{
public partial class RMFORM : Form
{
private Socket clientSock;
private string userName = "";
private string testName = "";
private string testNameString = "";
private string targetPath = "";
private bool isConnected = false;
private TestForm testForm;
private List<string> listOfFilesToCopy = new List<string>();
private List<string> listOfPathToCopy = new List<string>();
private RegistryKey registryKey;
public RMFORM ()
{
InitializeComponent();
userName = RemoteUtils.getConnectedUser();
targetPath = RemoteUtils.targetPath + userName;
testForm = new TestForm(RemoteUtils.remoteIpAddress, userName);
}
private void createNewCommand(string executable, string selectedPath, bool isDirectory)
{
string selectedOutDir = "";
testForm.enableFinishedButton();
testForm.setNumOfProcessesTest();
testForm.ShowDialog();
while (!testForm.getIsFinished())
{
if (testForm.getIsFormClosed())
{
testForm.Hide();
return;
}
}
testName = testForm.getTestName();
testNameString = testForm.getSelectedTestType();
selectedOutDir = targetPath + "\\" + testName;
try
{
if (Directory.Exists(selectedOutDir))
{
DialogResult dialogResult = MessageBox.Show("Test named " + testName + " already exists.\nDo You Wish To Continue?", "Warning!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.No)
{
return;
}
}
else
Directory.CreateDirectory(selectedOutDir);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!");
this.Close();
}
if (testNameString.CompareTo("Mek") == 0)
{
addSingleTest(executable, selectedPath, selectedOutDir, "mek", isDirectory);
}
if (testNameString.CompareTo("Mel") == 0)
{
addSingleTest(executable, selectedPath, selectedOutDir, "mel", isDirectory);
}
if (testNameString.CompareTo("Mem") == 0)
{
addSingleTest(executable, selectedPath, selectedOutDir, "mem", isDirectory);
}
}
private void addSingleTest(string executable, string selectedPath, string outputDir, string testType, bool isDirectory)
{
string commandToRun = "";
commandToRun = targetPath + RemoteUtils.batchRunPath + executable + testForm.getTestPerformance() + " " + selectedPath + " " + outputDir;
if (!isDirectory)
{
commandToRun += "\\" + Path.GetFileNameWithoutExtension(selectedPath) + "." + testType + ".pos " + testType;
}
else
{
commandToRun += " " + testType + " " + testForm.getNumOfProcess();
}
removeOne.Enabled = true;
removeAll.Enabled = true;
sendBtn.Enabled = true;
listORequestedCommands.Items.Add(commandToRun);
listORequestedCommands.Refresh();
}
private bool searchForFiles(string parentDirectory)
{
bool found = false;
if (Directory.GetFiles(parentDirectory, "*" + RemoteUtils.sequenceExtenssion).Length > 0)
return true;
try
{
foreach (string subDir in Directory.GetDirectories(parentDirectory))
{
if (Directory.GetFiles(subDir, "*" + RemoteUtils.sequenceExtenssion).Length > 0)
return true;
found = searchForFiles(subDir);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
this.Close();
}
return found;
}
private void connectBtn_Click(object sender, EventArgs e)
{
try
{
if (!isConnected)
{
registryKey = Registry.CurrentUser.CreateSubKey(RemoteUtils.registrySubKey);
clientSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
connectBtn.Text = "Disconnect From Server";
connectBtn.Refresh();
clientSock.Connect(RemoteUtils.remoteIpAddress, RemoteUtils.remotePort);
statusColor.BackColor = Color.Green;
statusColor.Refresh();
isConnected = true;
buttonAddDirectory.Enabled = true;
buttonAddFile.Enabled = true;
var backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork += (sender1, e1) => RemoteUtils.copyDllsToServer(targetPath);
backgroundWorker.RunWorkerAsync();
}
else
{
registryKey.Close();
connectBtn.Text = "Connect To Server";
isConnected = false;
statusColor.BackColor = Color.Red;
buttonAddDirectory.Enabled = false;
buttonAddFile.Enabled = false;
clientSock.Close();
clientSock.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
this.Close();
}
}
private void sendBtn_Click(object sender, EventArgs e)
{
try
{
string [] commandsInRegistry = registryKey.GetValueNames();
for (int i = 0; i < commandsInRegistry.Length; i++)
{
registryKey.DeleteValue(commandsInRegistry[i]);
}
for (int i = 0; i < listORequestedCommands.Items.Count; i++)
{
clientSock.Send(Encoding.Default.GetBytes(listORequestedCommands.Items[i].ToString() + " <eom> "));
registryKey.SetValue("Command " + (i + 1).ToString(), listORequestedCommands.Items[i].ToString());
}
removeAll_Click(sender, e);
sendBtn.Enabled = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error!");
this.Close();
}
}
private void buttonAddDirectory_Click(object sender, EventArgs e)
{
folderBrowserDialog = new FolderBrowserDialog();
folderBrowserDialog.SelectedPath = "C:\\";
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
string selectedPath = folderBrowserDialog.SelectedPath;
if (!searchForFiles(selectedPath))
{
MessageBox.Show("The directory: " + selectedPath + " doesn't contain sequences.", "Error!");
return;
}
testForm.enableNumOfProcesses();
createNewCommand(RemoteUtils.runBatchScript, selectedPath, true);
}
}
private void buttonAddFile_Click(object sender, EventArgs e)
{
openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "C:\\";
openFileDialog.Filter = "PMD files (*" + RemoteUtils.sequenceExtenssion + ")|*" + RemoteUtils.sequenceExtenssion + "|All files (*.*)|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string selectedFile = openFileDialog.FileName;
if (Path.GetExtension(selectedFile).CompareTo(RemoteUtils.sequenceExtenssion) != 0)
{
MessageBox.Show("The file: " + selectedFile + " is not a sequence file.", "Error!");
return;
}
createNewCommand(RemoteUtils.batchRunExe, selectedFile, false);
}
}
private void removeOne_Click(object sender, EventArgs e)
{
int iRemoveIndex = listORequestedCommands.SelectedIndex;
if (iRemoveIndex > -1)
{
listORequestedCommands.Items.RemoveAt(iRemoveIndex);
listORequestedCommands.Refresh();
if (listORequestedCommands.Items.Count == 0)
{
removeOne.Enabled = false;
removeAll.Enabled = false;
sendBtn.Enabled = false;
}
}
}
private void removeAll_Click(object sender, EventArgs e)
{
listORequestedCommands.Items.Clear();
listORequestedCommands.Refresh();
buttonAddDirectory.Enabled = true;
buttonAddFile.Enabled = true;
removeOne.Enabled = false;
removeAll.Enabled = false;
sendBtn.Enabled = false;
}
}
}
Any ideas?
Have you looked at
http://www.thecodeproject.com/csharp/ZaSocks5Proxy.asp
We use code based on this in our s/w so that our "server" monitors input to broadcasts the message to all other users hooked into the "server"
In essence each workstation monitors in incoming string. The first word of the string we use as a "command" and process accordingly. "finish" could be such a command.

Categories