Sending messages back to a client - c#

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.

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

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;

c# updater help ( restart once update is complete )

Hello all i have managed to make a basic program that will do a update for me but one thing i want to try and do when the update form is open to close the main form then restart program when the update is finished but have no idea how to do this
this is the code i have currently
namespace update_test
{
public partial class Form1 : Form
{
// folder calls needed
string updatepath = Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + "updatetest");
public Form1()
{
InitializeComponent();
}
// copying files
private static void DirectoryCopy(
string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name);
// Copy the file.
file.CopyTo(temppath, true);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
public void downloadfile()
{
//client.DownloadFile("http://elfenliedtopfan5.co.uk/update/elfenlied_weapons.zip", updatepath);
WebClient client = new WebClient();
string file = Path.Combine(updatepath, "elfenlied_weapons.zip");
client.DownloadFileAsync(new Uri("http://elfenliedtopfan5.co.uk/update/elfenlied_weapons.zip"), file);
client.DownloadProgressChanged += client_DownloadProgressChanged;
MessageBox.Show(file);
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
int bytesin = int.Parse(e.BytesReceived.ToString());
int totalbytes = int.Parse(e.TotalBytesToReceive.ToString());
int kb1 = bytesin / 1024;
int kb2 = totalbytes / 1024;
label1.Text = kb1.ToString() + "KB out of " + kb2.ToString() + "KB (" +e.ProgressPercentage.ToString() + "%)";
progressBar1.Value = e.ProgressPercentage;
if (e.ProgressPercentage == 100)
{
exactzip();
}
}
public void update()
{
string downloadurl = "";
Version newversion = null;
string xmlurl = "http://elfenliedtopfan5.co.uk/xml/update.xml";
XmlTextReader reader = null;
try
{
reader = new XmlTextReader(xmlurl);
reader.MoveToContent();
string elementname = "";
if ((reader.NodeType == XmlNodeType.Element)&& (reader.Name == "update_test"))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
elementname = reader.Name;
}
else
{
if((reader.NodeType == XmlNodeType.Text)&& (reader.HasValue))
{
switch (elementname)
{
case "version":
newversion = new Version(reader.Value);
break;
case "url":
downloadurl = reader.Value;
break;
}
}
}
}
}
}
catch(Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
if (reader != null)
reader.Close();
}
Version applicationvershion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
if (applicationvershion.CompareTo(newversion) < 0)
{
DialogResult dialogResult = MessageBox.Show("Version " + newversion.Major + "." + newversion.Minor + "." + newversion.Build + " of elfenliedprograms do you want to update now ?", "Update Avalible!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
var myForm = new Form1();
myForm.Show();
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
else
{
MessageBox.Show("program currently upto date :) ");
}
}
}
public void seeiffile()
{
// Set to folder path we must ensure exists.
string updatepathex = updatepath;
try
{
// If the directory doesn't exist, create it.
if (!Directory.Exists(updatepathex))
{
Directory.CreateDirectory(updatepathex);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
// if all above works then follow this
public void exactzip()
{
using (ZipFile zip = ZipFile.Read (Path.Combine(updatepath, "elfenlied_weapons.zip")))
{
foreach (ZipEntry e in zip)
{
e.ExtractExistingFile = ExtractExistingFileAction.OverwriteSilently;
e.Extract(updatepath);
// e.Extract(updatepath);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
seeiffile();
downloadfile();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
ShowHideForm1(true);
}
private void ShowHideForm1(bool show)
{
Form1 f1 = Application.OpenForms.OfType<Form1>().SingleOrDefault();
if (f1 != null)
{
if (show)
{ f1.Show(); }
else
{ f1.Hide(); }
}
}
private void Form2_Shown(object sender, EventArgs e)
{
ShowHideForm1(false);
}
}
}
then i have another form attached to this application called
elfenliedprograms.cs
witch contains this code
namespace update_test
{
public partial class elfenliedprograms : Form
{
public elfenliedprograms()
{
InitializeComponent();
}
private void elfenliedprograms_Load(object sender, EventArgs e)
{
update();
}
public void update()
{
string downloadurl = "";
Version newversion = null;
string xmlurl = "http://elfenliedtopfan5.co.uk/xml/update.xml";
XmlTextReader reader = null;
try
{
reader = new XmlTextReader(xmlurl);
reader.MoveToContent();
string elementname = "";
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "update_test"))
{
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
elementname = reader.Name;
}
else
{
if ((reader.NodeType == XmlNodeType.Text) && (reader.HasValue))
{
switch (elementname)
{
case "version":
newversion = new Version(reader.Value);
break;
case "url":
downloadurl = reader.Value;
break;
}
}
}
}
}
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
finally
{
if (reader != null)
reader.Close();
}
Version applicationvershion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
if (applicationvershion.CompareTo(newversion) < 0)
{
DialogResult dialogResult = MessageBox.Show("Version "+ newversion.Major + "." + newversion.Minor + "." + newversion.Build + " of elfenliedprograms do you want to update now ?", "Update Avalible!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
var myForm = new Form1();
myForm.Show();
}
else if (dialogResult == DialogResult.No)
{
//do something else
}
else
{
MessageBox.Show("program currently upto date :) ");
}
}
}
so basically once the update triggers there is a update it will call elfenliedprograms.cs but it will not shut down the main form if i do that it will shut the whole process down and im not sure how to go about making it download then restart app so all new stuff is updated it has taken me a good 4 months just to get this working the way i want not very good when it comes to updating a aplication so i would need help on this part sorry to be a pain and ask
thank you for

C# code to make mobile phone to connect through visual studio using AT commands?

This the code for making connection with the GSM 900 modem... and the code works perfectly..
but when i try to make my mobile(micromax doodle a111-works perfectly for all AT COMMANDS in HYPERTERMINAL) to act instead of GSM 900 modem.. its says NO PHONE CONNECTED..
What changes i have to make in order to connect my mobile..pls help me soon.. thanx in advance...
public partial class frmConnection : Form
{
public frmConnection()
{
InitializeComponent();
}
// private System.ComponentModel.Container components = null;
private int port;
private int baudRate;
private int timeout;
private void frmConnection_Load(object sender, EventArgs e)
{
cboPort.Items.Add("1");
cboPort.Items.Add("2");
cboPort.Items.Add("3");
cboPort.Items.Add("4");
cboPort.Text = port.ToString();
cboBaudRate.Items.Add("9600");
cboBaudRate.Items.Add("19200");
cboBaudRate.Items.Add("38400");
cboBaudRate.Items.Add("57600");
cboBaudRate.Items.Add("115200");
cboBaudRate.Text = baudRate.ToString();
cboTimeout.Items.Add("150");
cboTimeout.Items.Add("300");
cboTimeout.Items.Add("600");
cboTimeout.Items.Add("900");
cboTimeout.Items.Add("1200");
cboTimeout.Items.Add("1500");
cboTimeout.Items.Add("1800");
cboTimeout.Items.Add("2000");
cboTimeout.Text = timeout.ToString();
}
public void SetData(int port, int baudRate, int timeout)
{
this.port = port;
this.baudRate = baudRate;
this.timeout = timeout;
}
public void GetData(out int port, out int baudRate, out int timeout)
{
port = this.port;
baudRate = this.baudRate;
timeout = this.timeout;
}
private bool EnterNewSettings()
{
int newPort;
int newBaudRate;
int newTimeout;
try
{
newPort = int.Parse(cboPort.Text);
}
catch (Exception)
{
MessageBox.Show(this, "Invalid port number.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
cboPort.Focus();
return false;
}
try
{
newBaudRate = int.Parse(cboBaudRate.Text);
}
catch (Exception)
{
MessageBox.Show(this, "Invalid baud rate.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
cboBaudRate.Focus();
return false;
}
try
{
newTimeout = int.Parse(cboTimeout.Text);
}
catch (Exception)
{
MessageBox.Show(this, "Invalid timeout value.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
cboTimeout.Focus();
return false;
}
SetData(newPort, newBaudRate, newTimeout);
return true;
}
private void btnOK_Click(object sender, EventArgs e)
{
if (!EnterNewSettings())
DialogResult = DialogResult.None;
}
private void btnTest_Click(object sender, EventArgs e)
{
if (!EnterNewSettings())
return;
Cursor.Current = Cursors.WaitCursor;
GsmCommMain comm = new GsmCommMain(port, baudRate, timeout);
try
{
comm.Open();
while (!comm.IsConnected())
{
Cursor.Current = Cursors.Default;
if (MessageBox.Show(this, "No phone connected.", "Connection setup",
MessageBoxButtons.RetryCancel, MessageBoxIcon.Exclamation) == DialogResult.Cancel)
{
comm.Close();
return;
}
Cursor.Current = Cursors.WaitCursor;
}
comm.Close();
}
catch (Exception ex)
{
MessageBox.Show(this, "Connection error: " + ex.Message, "Connection setup", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
MessageBox.Show(this, "Successfully connected to the phone.", "Connection setup", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
and this the code that have to receive the msg after the connection and display it on the screen and to access the content in teh message..
public partial class Mainform : Form
{
SmsSubmitPdu pdu;
private delegate void SetTextCallback(string text);
private CommSetting comm_settings = new CommSetting();
SqlConnection conn = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=localtrain;Integrated Security=True");
string mess="";
private void Mainform_Load(object sender, EventArgs e)
{
Control.CheckForIllegalCrossThreadCalls = false;
// Prompt user for connection settings
int port = GsmCommMain.DefaultPortNumber;
int baudRate = 9600; // We Set 9600 as our Default Baud Rate
int timeout = GsmCommMain.DefaultTimeout;
timer1.Start();
timer1.Interval = 10000;
frmConnection dlg = new frmConnection();
dlg.StartPosition = FormStartPosition.CenterScreen;
dlg.SetData(port, baudRate, timeout);
if (dlg.ShowDialog(this) == DialogResult.OK)
{
dlg.GetData(out port, out baudRate, out timeout);
CommSetting.Comm_Port = port;
CommSetting.Comm_BaudRate = baudRate;
CommSetting.Comm_TimeOut = timeout;
}
else
{
Close();
return;
}
Cursor.Current = Cursors.WaitCursor;
CommSetting.comm = new GsmCommMain(port, baudRate, timeout);
Cursor.Current = Cursors.Default;
CommSetting.comm.PhoneConnected += new EventHandler(comm_PhoneConnected);
CommSetting.comm.MessageReceived += new MessageReceivedEventHandler(comm_MessageReceived);
bool retry;
do
{
retry = false;
try
{
Cursor.Current = Cursors.WaitCursor;
CommSetting.comm.Open();
Cursor.Current = Cursors.Default;
}
catch (Exception)
{
Cursor.Current = Cursors.Default;
if (MessageBox.Show(this, "Unable to open the port.", "Error",
MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning) == DialogResult.Retry)
retry = true;
else
{
Close();
return;
}
}
}
while (retry);
}
private delegate void ConnectedHandler(bool connected);
private void OnPhoneConnectionChange(bool connected)
{
lbl_phone_status.Text = "CONNECTED";
}
private void comm_MessageReceived(object sender, GsmComm.GsmCommunication.MessageReceivedEventArgs e)
{
MessageReceived();
}
private void comm_PhoneConnected(object sender, EventArgs e)
{
this.Invoke(new ConnectedHandler(OnPhoneConnectionChange), new object[] { true });
}
private string GetMessageStorage()
{
string storage = string.Empty;
storage = PhoneStorageType.Sim;
if (storage.Length == 0)
throw new ApplicationException("Unknown message storage.");
else
return storage;
}
private void MessageReceived()
{
Cursor.Current = Cursors.WaitCursor;
string storage = GetMessageStorage();
DecodedShortMessage[] messages = CommSetting.comm.ReadMessages(PhoneMessageStatus.ReceivedUnread, storage);
foreach (DecodedShortMessage message in messages)
{
Output(string.Format("Message status = {0}, Location = {1}/{2}",
StatusToString(message.Status), message.Storage, message.Index));
ShowMessage(message.Data);
Output("");
}
Output(string.Format("{0,9} messages read.", messages.Length.ToString()));
Output("");
}
private string StatusToString(PhoneMessageStatus status)
{
// Map a message status to a string
string ret;
switch (status)
{
case PhoneMessageStatus.All:
ret = "All";
break;
case PhoneMessageStatus.ReceivedRead:
ret = "Read";
break;
case PhoneMessageStatus.ReceivedUnread:
ret = "Unread";
break;
case PhoneMessageStatus.StoredSent:
ret = "Sent";
break;
case PhoneMessageStatus.StoredUnsent:
ret = "Unsent";
break;
default:
ret = "Unknown (" + status.ToString() + ")";
break;
}
return ret;
}
int kl = 0;
long mobilenumber;
string message;
private void Output(string text)
{
label1.Text = "Processing....";
try
{
kl = kl + 1;
if (text != "RECEIVED MESSAGE")
{
if (this.txtOutput.InvokeRequired)
{
SetTextCallback stc = new SetTextCallback(Output);
this.Invoke(stc, new object[] { text });
}
else
{
txtOutput.AppendText(text);
txtOutput.AppendText("\r\n");
label2.Text = (Convert.ToInt32(label2.Text) + 1).ToString();
comboBox1.Items.Add(text);
if (label2.Text == "6")
{
string temps = "ms*tbm*2*";
int count;
string mob;
DateTime dt = new DateTime();
string source, dest, temp, tempdate;
string source1, dest1, temp1, tempdate1;
int tic;
mob = comboBox1.Items[1].ToString();
mob = mob.Substring(mob.LastIndexOf('+') + 3);
mobilenumber = Convert.ToInt64(mob);
tempdate = comboBox1.Items[2].ToString();
temp = comboBox1.Items[3].ToString();
string[] mess1 = temp.Split('*');
source1 = mess1[0].ToString();
source1 = source1.Substring(source1.IndexOf('$') + 1);
dest1 = mess1[1].ToString();
tic =Convert.ToInt32(mess1[2].ToString());
temp = temp.Substring(temp.LastIndexOf('$')+1);
//
//source = temp.Substring(0, temp.IndexOf('*'));
//temp = temp.Substring(temp.IndexOf('*') + 1);
//dest = temp.Substring(0, temp.IndexOf('*') - 1);
//temp = temp.Substring(temp.IndexOf('*') + 1);
//count = Convert.ToInt32(temp);
ticketing(mobilenumber, source1, dest1, tic);
}
}
}
else
{
comboBox1.Items.Clear();
txtOutput.Text = "";
// label2.Text = "";
comboBox1.Items.Add(text);
if (this.txtOutput.InvokeRequired)
{
SetTextCallback stc = new SetTextCallback(Output);
this.Invoke(stc, new object[] { text });
}
else
{
txtOutput.AppendText(text);
txtOutput.AppendText("\r\n");
// label2.Text += "*" + text;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void ShowMessage(SmsPdu pdu)
{
if (pdu is SmsSubmitPdu)
{
// Stored (sent/unsent) message
SmsSubmitPdu data = (SmsSubmitPdu)pdu;
Output("SENT/UNSENT MESSAGE");
Output("Recipient: " + data.DestinationAddress);
Output("Message text: " + data.UserDataText);
Output("-------------------------------------------------------------------");
return;
}
if (pdu is SmsDeliverPdu)
{
// Received message
SmsDeliverPdu data = (SmsDeliverPdu)pdu;
Output("RECEIVED MESSAGE");
Output("Sender: -" + data.OriginatingAddress);
Output("Sent: " + data.SCTimestamp.ToString());
Output("Message text: $" + data.UserDataText);
Output("-------------------------------------------------------------------");
// label2.Text = data.UserDataText;
return;
}
if (pdu is SmsStatusReportPdu)
{
// Status report
SmsStatusReportPdu data = (SmsStatusReportPdu)pdu;
Output("STATUS REPORT");
Output("Recipient: " + data.RecipientAddress);
Output("Status: " + data.Status.ToString());
Output("Timestamp: " + data.DischargeTime.ToString());
Output("Message ref: " + data.MessageReference.ToString());
Output("-------------------------------------------------------------------");
return;
}
Output("Unknown message type: " + pdu.GetType().ToString());
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
// Clean up comm object
if (CommSetting.comm != null)
{
// Unregister events
CommSetting.comm.PhoneConnected -= new EventHandler(comm_PhoneConnected);
CommSetting.comm.MessageReceived -= new MessageReceivedEventHandler(comm_MessageReceived);
// Close connection to phone
if (CommSetting.comm != null && CommSetting.comm.IsOpen())
CommSetting.comm.Close();
CommSetting.comm = null;
this.Close();
}
}
//
I think you should add combobox first and check all available ports automatically using this code :
private void comboBox1_DropDown(object sender, EventArgs e)
{
comboBox1.Items.Clear();
try
{
#region Display all available COM Ports
string[] ports = SerialPort.GetPortNames();
// Add all port names to the combo box:
foreach (string port in ports)
{
this.comboBox1.Items.Add(port);
}
#endregion
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And you'll see where the problem is .
Thank you .

How to restore data that was backed up in 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!");
}
}
}
}

Categories