Dis connect websocket in c# after many minutes - c#

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

Related

c# Windows Form slow rendering objects

I have spent some time designing my first project using C#, it is a Windows form project with 8 buttons on the side. pressing one of the buttons will open another form within the parent form as a window. On clicking the button the new form loads up about 27 objects mostly Labels, Textboxes, Comboboxes and a few DateTimePickers. For some reason it you can see it drawing the boxes and it looks slow. I have an SQL db included with my project which is tiny and contains only 2 rows of data. It is very dishearting to spend all that time working on it only to see it run like a ZX Spectrum. I am using Microsoft Visual Studio 2019 and is fully updated. I have no errors, no warnings thank god but the performance is horrible. One of the comboBoxes when selected will make visible 3 more textBoxes and even making those visible is really slow. Is there something I am doing wrong or is there a way to have it working faster please?
This is the code of my childForm which opens from the main parentForm, sorry is is a bit long but it is all of it.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace AvianManager.Forms
{
public partial class formMyBirds : Form
{
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Dion\Documents\AvianManager.mdf;Integrated Security=True;Connect Timeout=30");
public formMyBirds()
{
InitializeComponent();
}
private void formMyBirds_Load(object sender, EventArgs e)
{
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
var form = Application.OpenForms["formMyBirdsHelper"]; // Lookup form and check if already open
if (form == null)
{
formMyBirdsHelper MyBirdsHelper = new formMyBirdsHelper(); // Instantiate a FormMyBirdsHelp object.
MyBirdsHelper.Show(); // Show FormMyBirdsHelp and
}
}
private void comboBoxLegBandType_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxLegBandType.GetItemText(this.comboBoxLegBandType.SelectedItem);
if (selected != "None" || selected == null)
{
textBoxLegBandID.Visible = true;
labelLegBandId.Visible = true;
textBoxLegBandSize.Visible = true;
labelLegBandSize.Visible = true;
}
else
{
textBoxLegBandID.Visible = false;
labelLegBandId.Visible = false;
textBoxLegBandSize.Visible = false;
labelLegBandSize.Visible = false;
}
}
private void comboBoxPrevOwner_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxPrevOwner.GetItemText(this.comboBoxPrevOwner.SelectedItem);
if (selected != "No")
{
textBoxLastOwnerName.Visible = true;
labelLastOwnerName.Visible = true;
textBoxLastOwnerFone.Visible = true;
labelLastOwnerFone.Visible = true;
textBoxLastOwnerAddr.Visible = true;
labelLastOwnerAddr.Visible = true;
}
else
{
textBoxLastOwnerName.Visible = false;
labelLastOwnerName.Visible = false;
textBoxLastOwnerFone.Visible = false;
labelLastOwnerFone.Visible = false;
textBoxLastOwnerAddr.Visible = false;
labelLastOwnerAddr.Visible = false;
}
}
private void comboBoxVitalStatus_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxVitalStatus.GetItemText(this.comboBoxVitalStatus.SelectedItem);
if (selected != "Alive")
{
dateTimeDateOfDeath.Visible = true;
labelDateOfDeath.Visible = true;
textBoxCauseOfDeath.Visible = true;
labelCauseOfDeath.Visible = true;
}
else
{
dateTimeDateOfDeath.Visible = false;
labelDateOfDeath.Visible = false;
textBoxCauseOfDeath.Visible = false;
labelCauseOfDeath.Visible = false;
}
}
private void comboBoxRetained_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxRetained.GetItemText(this.comboBoxRetained.SelectedItem);
if (selected != "Yes")
{
dateTimeRelinquishedDate.Visible = true;
labelRelinquishedDate.Visible = true;
}
else
{
dateTimeRelinquishedDate.Visible = false;
labelRelinquishedDate.Visible = false;
}
}
private void textBoxUid_TextChanged(object sender, EventArgs e)
{
SqlCommand cmd1 = new SqlCommand("select top 1 * from dbMyBirds where db_Uid = '" + textBoxUid.Text + "'", connection);
cmd1.Parameters.AddWithValue("db_Uid", textBoxUid.Text);
SqlDataReader reader1;
connection.Open();
reader1 = cmd1.ExecuteReader();
if (reader1.Read())
{
labelResult.Text = "Found";
textBoxName.Text = reader1["db_Name"].ToString();
textBoxSpecies.Text = reader1["db_Species"].ToString();
comboBoxLegBandType.Text = reader1["db_LegBandType"].ToString();
textBoxLegBandID.Text = reader1["db_LegBandId"].ToString();
textBoxLegBandSize.Text = reader1["db_LegBandSize"].ToString();
comboBoxPrevOwner.Text = reader1["db_PrevOwner"].ToString();
textBoxLastOwnerName.Text = reader1["db_PrevOwnerName"].ToString();
textBoxLastOwnerFone.Text = reader1["db_PrevOwnerFone"].ToString();
textBoxLastOwnerAddr.Text = reader1["db_PrevOwnerAddr"].ToString();
comboBoxIsHybrid.Text = reader1["db_Hybrid"].ToString();
comboBoxRearedBy.Text = reader1["db_RearedBy"].ToString();
textBoxDisformaties.Text = reader1["db_Disformaties"].ToString();
comboBoxVitalStatus.Text = reader1["db_VitalStatus"].ToString();
dateTimeDateOfDeath.Text = reader1["db_DateDied"].ToString();
textBoxCauseOfDeath.Text = reader1["db_CauseOfDeath"].ToString();
comboBoxRetained.Text = reader1["db_Retained"].ToString();
dateTimeRelinquishedDate.Text = reader1["db_RelinquishedDate"].ToString();
dateTimeHatchDate.Text = reader1["db_HatchDate"].ToString();
dateTimeFledgeDate.Text = reader1["db_FledgeDate"].ToString();
comboBoxMaleParentHybrid.Text = reader1["db_MPisHybrid"].ToString();
textBoxMaleParentId.Text = reader1["db_MPUid"].ToString();
textBoxMaleParentSpecies.Text = reader1["db_MPSpecies"].ToString();
comboBoxHenParentHybrid.Text = reader1["db_FPisHybrid"].ToString();
textBoxHenParentId.Text = reader1["db_FPUid"].ToString();
textBoxHenParentSpecies.Text = reader1["db_FPSpecies"].ToString();
textBoxNotes.Text = reader1["db_Notes"].ToString();
}
else
{
resetInputs();
if (textBoxUid.Text == "")
{
labelResult.Text = "Live Search";
}
else
{
labelResult.Text = "Nothing Found";
}
}
connection.Close();
}
//Reset input fields if no results
private void resetInputs()
{
string dt2;
DateTime date2 = DateTime.Now;
dt2 = date2.ToShortDateString(); // display format: 15/07/2021
textBoxName.Text = "";
textBoxSpecies.Text = "";
comboBoxLegBandType.Text = "Select";
textBoxLegBandID.Text = "";
textBoxLegBandSize.Text = "";
comboBoxPrevOwner.Text = "Select";
textBoxLastOwnerName.Text = "";
textBoxLastOwnerFone.Text = "";
textBoxLastOwnerAddr.Text = "";
comboBoxIsHybrid.Text = "Select";
comboBoxRearedBy.Text = "Select";
textBoxDisformaties.Text = "";
comboBoxVitalStatus.Text = "Select";
dateTimeDateOfDeath.Text = dt2;
textBoxCauseOfDeath.Text = "";
comboBoxRetained.Text = "Select";
dateTimeRelinquishedDate.Text = dt2;
dateTimeHatchDate.Text = dt2;
dateTimeFledgeDate.Text = dt2;
comboBoxMaleParentHybrid.Text = "Select";
textBoxMaleParentId.Text = "";
textBoxMaleParentSpecies.Text = "";
comboBoxHenParentHybrid.Text = "Select";
textBoxHenParentId.Text = "";
textBoxHenParentSpecies.Text = "";
textBoxNotes.Text = "";
}
private void buttonInsert_Click(object sender, EventArgs e)
{
}
}
}

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;

Cannot Implicitly convert type "String" to "Windows.Security.Credentials.PasswordCredential"

Cannot Implicitly convert type "String" to "Windows.Security.Credentials.PasswordCredential"
After about 4 hours of searching I cannot figure out this error. I am using the Windows 10 IOT Core on a RPI 3. My program is pretty basic, however I can not convert the datatype within the code to resolve the error.
using SDKTemplate;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using Windows.Devices.WiFi;
using Windows.Networking.Connectivity;
using Windows.Security.Credentials;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WiFiConnect
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class WiFiConnect_Scenario : Page
{
MainPage rootPage;
private WiFiAdapter firstAdapter;
public ObservableCollection<WiFiNetworkDisplay> ResultCollection
{
get;
private set;
}
public WiFiConnect_Scenario()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
ResultCollection = new ObservableCollection<WiFiNetworkDisplay>();
rootPage = MainPage.Current;
// RequestAccessAsync must have been called at least once by the app before using the API
// Calling it multiple times is fine but not necessary
// RequestAccessAsync must be called from the UI thread
var access = await WiFiAdapter.RequestAccessAsync();
if (access != WiFiAccessStatus.Allowed)
{
rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage);
}
else
{
DataContext = this;
var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDevice Selector());
if (result.Count >= 1)
{
firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
var button = new Button();
button.Content = string.Format("Scan Available Wifi Networks");
button.Click += Button_Click;
Buttons.Children.Add(button);
}
else
{
rootPage.NotifyUser("No WiFi Adapters detected on this machine.", NotifyType.ErrorMessage);
}
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
await firstAdapter.ScanAsync();
ConnectionBar.Visibility = Visibility.Collapsed;
DisplayNetworkReport(firstAdapter.NetworkReport);
}
private void DisplayNetworkReport(WiFiNetworkReport report)
{
rootPage.NotifyUser(string.Format("Network Report Timestamp: {0}", report.Timestamp), NotifyType.StatusMessage);
ResultCollection.Clear();
foreach (var network in report.AvailableNetworks)
{
ResultCollection.Add(new WiFiNetworkDisplay(network, firstAdapter));
}
}
private void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;
if (selectedNetwork == null)
{
return;
}
// Show the connection bar
ConnectionBar.Visibility = Visibility.Visible;
// Only show the password box if needed
if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 &&
selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
{
NetworkKeyInfo.Visibility = Visibility.Collapsed;
}
else
{
NetworkKeyInfo.Visibility = Visibility.Visible;
}
}
private async void ConnectButton_Click(object sender, RoutedEventArgs e)
{
var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;
if (selectedNetwork == null || firstAdapter == null)
{
rootPage.NotifyUser("Network not selcted", NotifyType.ErrorMessage);
return;
}
WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;
if (IsAutomaticReconnection.IsChecked.HasValue && IsAutomaticReconnection.IsChecked == true)
{
reconnectionKind = WiFiReconnectionKind.Automatic;
}
WiFiConnectionResult result;
if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211 &&
selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
{
result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind);
}
else
{
FileStream file = new FileStream("final-wordlist.txt", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(file);
sr.ReadLine();
var textLines = File.ReadAllLines("final-wordlist.txt");
foreach (var line in textLines)
{
string[] dataArray = line.Split(' ');
foreach (var item in dataArray)
{
PasswordCredential credential = line;
//string credential = line.ToString();
result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential);
}
}
// Only the password potion of the credential need to be supplied
}
if (result.ConnectionStatus == WiFiConnectionStatus.Success)
{
rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage);
// refresh the webpage
webViewGrid.Visibility = Visibility.Visible;
toggleBrowserButton.Content = "Hide Browser Control";
refreshBrowserButton.Visibility = Visibility.Visible;
}
else
{
rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage);
}
// Since a connection attempt was made, update the connectivity level displayed for each
foreach (var network in ResultCollection)
{
network.UpdateConnectivityLevel();
}
}
private void Browser_Toggle_Click(object sender, RoutedEventArgs e)
{
if (webViewGrid.Visibility == Visibility.Visible)
{
webViewGrid.Visibility = Visibility.Collapsed;
refreshBrowserButton.Visibility = Visibility.Collapsed;
toggleBrowserButton.Content = "Show Browser Control";
}
else
{
webViewGrid.Visibility = Visibility.Visible;
refreshBrowserButton.Visibility = Visibility.Visible;
toggleBrowserButton.Content = "Hide Browser Control";
}
}
private void Browser_Refresh(object sender, RoutedEventArgs e)
{
webView.Refresh();
}
}
}
This worked for me. The problem was it was it need more than one var to fill it.
var credential = new PasswordCredential("Module", "Username", "Password");
Try this:
PasswordCredential credential = null;
if (!string.IsNullOrEmpty(line))
{
credential = new PasswordCredential()
{
Password = line
};
}

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