I've created a simple tool that can find Sign up option in websites (200 website list is in arraylist).
I was using webbrowser but it has a problem of cache and cookie so i switched to webclient. It works fine when i put breakpoints and debug but when i run it normally, it also include those websites which doesn't have signup option.
Here is my code
private void btnSearch_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Start();
}
Timer1 code
string st;
private void timer1_Tick(object sender, EventArgs e)
{
st = "";
Application.DoEvents();
try
{
st = lst[dataindex2].ToString();
using (WebClient asyncWebRequest = new WebClient())
{
asyncWebRequest.DownloadDataCompleted += asyncWebRequest_DownloadDataCompleted;
Uri urlToRequest = new Uri(st);
asyncWebRequest.DownloadDataAsync(urlToRequest);
asyncWebRequest.Dispose();
}
dataindex2++;
if (dataindex2 == lst.Count)
{
timer1.Stop();
lblStatus.Text = "Stopped";
lblStatus.ForeColor = Color.DarkRed;
MessageBox.Show("Search Completed");
}
}
catch (Exception ex)
{
timer1.Stop();
lblStatus.Text = "Stopped";
lblStatus.ForeColor = Color.DarkRed;
timer1.Dispose();
MessageBox.Show(ex.Message);
return;
}
asyncWebRequest_DownloadDataCompleted code:
private void asyncWebRequest_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
if (e.Error != null)
{
timer1.Stop();
ena();
lblStatus.Text = "Stopped";
lblStatus.ForeColor = Color.DarkRed;
timer1.Dispose();
MessageBox.Show(e.Error.Message);
}
if (e.Result != null && e.Result.Length > 0)
{
string browsetext = "";
int = iSuccess = 0;
browsetext = Encoding.Default.GetString(e.Result);
iSuccess = browsetext.IndexOf("Sign up") + 1;
if (iSuccess == 0)
{
}
else
{
listBox1.Items.Add(st);
domaincount++;
lblDomainCount.ForeColor = Color.DarkGreen;
lblDomainCount.Text = domaincount.ToString();
}
}
else
{
}
}
}
else
{
MessageBox.Show("No data found.");
}
}
Please help and if there is any alternate of webclient that doesn't hang gui then please suggest. ty.
You dispose WebClient as soon as you start the download.
asyncWebRequest.DownloadDataAsync(urlToRequest);
asyncWebRequest.Dispose();
Please help and if there is any alternate of webclient that doesn't hang gui
see my other answer which creates a wrapper for WebClient to be able to use async/await. HttpClient can be an alternative too.
Related
Before you flag this as a duplicate, yes there are questions just like this, i've looked at all of them and still couldn't get this working. I'm trying to code in a feature that downloads and runs a .exe file but it doesn't download, run or do anything. I even removed the try catches to find an error or error codes but I have non, so I have no idea where i'm going wrong, here is my code for it
public test_Configuration()
{
InitializeComponent();
}
Uri uri = new Uri("http://example.com/files/example.exe");
string filename = #"C:\Users\**\AppData\Local\Temp\example.exe";
private void button1_Click(object sender, EventArgs e)
{
try
{
if(File.Exists(filename))
{
File.Delete(filename);
}
else
{
WebClient wc = new WebClient();
wc.DownloadDataAsync(uri, filename);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
if (progressBar1.Value == progressBar1.Maximum)
{
progressBar1.Value = 0;
}
}
private void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if(e.Error == null)
{
MessageBox.Show("Download complete!, running exe", "Completed!");
Process.Start(filename);
}
else
{
MessageBox.Show("Unable to download exe, please check your connection", "Download failed!");
}
Change DownloadDataAsync to DownloadFileAsync.
wc.DownloadFileAsync(uri, filename);
This code helped me out quite a bit with updating a file, so I thought I would show my twist in the hopes that someone else out there has a similar requirement as me.
I needed this code to do the following when a button was clicked:
Grab a file from a sever and store it locally in AppData\Temp.
Keep my user up-to-date of install progress (an installer is downloaded).
If successfully downloaded (note the removal of the else after deleting old file check), launch "daInstaller.exe", whilst terminating the current running program.
And if said file already exist (i.e. the old "daIstaller.exe"), delete prior to copying new file to AppData\Temp.
Don't forget to keep the file names the same, else you'll be leaving more trash in that AppData\Temp folder.
private void button1_Click(object sender, EventArgs e)
{
Uri uri = new Uri("http://example.com/files/example.exe");
filename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Temp/example.exe");
try
{
if (File.Exists(filename))
{
File.Delete(filename);
}
WebClient wc = new WebClient();
wc.DownloadFileAsync(uri, filename);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
if (progressBar1.Value == progressBar1.Maximum)
{
progressBar1.Value = 0;
}
}
private void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error == null)
{
Process.Start(filename);
Close();
Application.Exit();
}
else
{
MessageBox.Show("Unable to download exe, please check your connection", "Download failed!");
}
}
I was developing my first app called Minecraft Wiglet. It pings important minecraft sites and it can start in starup. When I am testing my app it succesfully pinged sites while
I was online but when I was offline the app crashed at the fourth line it said "unhandled pingExpection" I am new in coding so go easy on me :)
private void button1_Click(object sender, EventArgs e)
{
Ping ping = new Ping();
PingReply pingresult = ping.Send("minecraftturk.com"); //Crashed here
if (pingresult.Status.ToString() == "Success")
{
label5.Text = "Online";
}
else if (pingresult.Status.ToString() == "Failure")
{
label5.Text = "Offline";
}
Ping ping1 = new Ping();
PingReply pingresult1 = ping.Send("minecraft.net");
if (pingresult.Status.ToString() == "Success")
{
label3.Text = "Online";
}
else if (pingresult.Status.ToString() == "Failure")
{
label3.Text = "Offline";
}
Ping ping2 = new Ping();
PingReply pingresult2 = ping.Send("www.planetminecraft.com");
if (pingresult.Status.ToString() == "Success")
{
label10.Text = "Online";
}
else if (pingresult.Status.ToString() == "Failure")
{
label10.Text = "Offline";
}
MessageBox.Show("Durum başarıyla güncellendi.");
}
You need to catch and handle your exceptions. I'd recommend wrapping your pinging into another method like this:
private bool CanPing(string url)
{
try
{
return new Ping().Send(url).Status == IPStatus.Success;
}
catch (PingException)
{
return false;
}
}
Then you can call CanPing for each site and it will return true or false while handling the case where the user is offline in just one line, like so:
private void button1_Click(object sender, EventArgs e)
{
label10.Text = CanPing("www.planetminecraft.com") ? "Online" : "Offline";
// ...
}
You could further encapsulate the above into another method, but that might be overkill.
I have tried to add a bool function so it will not download the second file before the first is finished. But when I do that my program locks! What can I do?
This is my code:
private void btnDownload_Click(object sender, EventArgs e)
{
try
{
int total = listLink.Items.Count;
total--;
int current = -1;
while (current < total)
{
if (completed == true)
{
completed = false;
listLink.SelectedIndex = current + 1;
listSave.SelectedIndex = current + 1;
string download = listLink.SelectedItem.ToString();
string save = listSave.SelectedItem.ToString();
message = true;
wc.DownloadFileAsync(new Uri(download), save);
wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
if (wc.IsBusy)
{
if (message == true)
{
//wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
message = false;
}
}
current++;
}
if (current == total)
{
MessageBox.Show("Download Successful!", "Download Completed");
//completed = true;
wc.DownloadFileCompleted += new AsyncCompletedEventHandler(wc_DownloadFileCompleted);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
private void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressDownload.Value = e.ProgressPercentage;
this.Text = e.ProgressPercentage + "% Advanced Download Manager";
}
private void wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
/*if (shouldsay == true)
{
if (completed == true)
{
MessageBox.Show("Download Successful!", "Download Completed");
shouldsay = false;
}
else if (completed == false)
{
}
}*/
completed = true;
}
On my windows phone 7 Mango app I use the Microsoft.Live and Microsoft.Live.Controls references to download and upload on Skydrive. Logging in and uploading files works fine but whenever I call the "client.GetAsync("/me/skydrive/files");" on the LiveConnectClient the Callback result is empty just containing the error: "An error occurred while retrieving the resource. Try again later."
I try to retrieve the list of files with this method.
This error suddenly occured without any change on the source code of the app (I think..) which worked perfectly fine for quite a while until recently. At least I didn't change the code section for up- or downloading.
I tried out the "two-step verification" of Skydrive, still the same: can log in but not download.
Also updating the Live refercences to 5.5 didn't change anything.
Here is the code I use. The error occurs in the "getDir_Callback" in the "e" variable.
Scopes (wl.skydrive wl.skydrive_update) and clientId are specified in the SignInButton which triggers "btnSignin_SessionChanged".
private void btnSignin_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
connected = true;
processing = true;
client = new LiveConnectClient(e.Session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(UploadCompleted);
client.DownloadCompleted += new EventHandler<LiveDownloadCompletedEventArgs>(OnDownloadCompleted);
client.DownloadProgressChanged += new EventHandler<LiveDownloadProgressChangedEventArgs>(client_DownloadProgressChanged);
infoTextBlock.Text = "Signed in. Retrieving file IDs...";
client.GetAsync("me");
}
else
{
connected = false;
infoTextBlock.Text = "Not signed into Skydrive.";
client = null;
}
}
private void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
if (e.Error == null)
{
client.GetCompleted -= new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetCompleted += getDir_Callback;
client.GetAsync("/me/skydrive/files");
client_id = (string)e.Result["id"];
if (e.Result.ContainsKey("first_name") && e.Result.ContainsKey("last_name"))
{
if (e.Result["first_name"] != null && e.Result["last_name"] != null)
{
infoTextBlock.Text = "Hello, " +
e.Result["first_name"].ToString() + " " +
e.Result["last_name"].ToString() + "!";
}
}
else
{
infoTextBlock.Text = "Hello, signed-in user!";
}
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
processing = false;
}
public void getDir_Callback(object s, LiveOperationCompletedEventArgs e)
{
client.GetCompleted -= getDir_Callback;
//filling Dictionary with IDs of every file on SkyDrive
if (e.Result != null)
ParseDir(e);
if (!String.IsNullOrEmpty(e.Error.Message))
infoTextBlock.Text = e.Error.Message;
else
infoTextBlock.Text = "File-IDs loaded";
}
Yo shall use client.GetAsync("me/SkyDrive/files", null) in place of client.GetAsync("me");
This is my code and it works fine.
private void btnSignIn_SessionChanged(object sender, Microsoft.Live.Controls.LiveConnectSessionChangedEventArgs e)
{
try
{
if (e.Session != null && e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
client.GetCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_GetCompleted);
client.UploadCompleted += new EventHandler<LiveOperationCompletedEventArgs>(client_UploadCompleted);
client.GetAsync("me/SkyDrive/files", null);
client.DownloadAsync("me/SkyDrive", null);
canUpload = true;
ls = e.Session;
}
else
{
if (client != null)
{
MessageBox.Show("Signed out successfully!");
client.GetCompleted -= client_GetCompleted;
client.UploadCompleted -= client_UploadCompleted;
canUpload = false;
}
else
{
canUpload = false;
}
client = null;
canUpload = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void client_GetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
try
{
List<System.Object> listItems = new List<object>();
if (e.Result != null)
{
listItems = e.Result["data"] as List<object>;
for (int x = 0; x < listItems.Count(); x++)
{
Dictionary<string, object> file1 = listItems[x] as Dictionary<string, object>;
string fileName = file1["name"].ToString();
if (fileName == lstmeasu[0].Title)
{
folderID = file1["id"].ToString();
folderAlredyPresent = true;
}
}
}
}
catch (Exception)
{
MessageBox.Show("An error occured in getting skydrive folders, please try again later.");
}
}
It miraculously works again without me changing any code. It seems to be resolved on the other end. I have no clue what was wrong.
I've got a problem. How can I cancel a download ?
client.CancelAsync();
Doesn't work for me, because if I cancel a download and start a new one the code still tries to access the old download file. You've to know in my code is a part when a download is done it should unzip the file which has been downloaded. Example.zip like this :)
So, when I cancel my download and start a new one you know my script tries to unzip my old Example.zip, but it should kick this ....
For Unzipping, I'm using Iconic.Zip.dll (http://dotnetzip.codeplex.com/)
How to get it work?
UPDATE:
This is my Downloader Form
private void button3_Click_1(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("This will cancel your current download ! Continue ?", "Warning !", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
cancelDownload = true;
URageMainWindow.isDownloading = false;
this.Close();
}
else if (dialogResult == DialogResult.No)
{
}
}
This is my Main form this happens when you start downloading something
private void checkInstall(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string input = storeBrowser.Url.ToString();
// Test these endings
string[] arr = new string[]
{"_install.html"};
// Loop through and test each string
foreach (string s in arr)
{
if (input.EndsWith(s) && isDownloading == false)
{
// MessageBox.Show("U.Rage is downloading your game");
Assembly asm = Assembly.GetCallingAssembly();
installID = storeBrowser.Document.GetElementById("installid").GetAttribute("value");
// MessageBox.Show("Name: " + installname + " ID " + installID);
installname = storeBrowser.Document.GetElementById("name").GetAttribute("value");
installurl = storeBrowser.Document.GetElementById("link").GetAttribute("value");
isDownloading = true;
string install_ID = installID;
string Install_Name = installname;
// MessageBox.Show("New Update available ! " + " - Latest version: " + updateversion + " - Your version: " + gameVersion);
string url = installurl;
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_InstallProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_InstallFileCompleted);
client.DownloadFileAsync(new Uri(url), #"C:\U.Rage\Downloads\" + installID + "Install.zip");
if (Downloader.cancelDownload == true)
{
//MessageBox.Show("Downloader has been cancelled");
client.CancelAsync();
Downloader.cancelDownload = false;
}
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(2, "Downloading !", "U.Rage is downloading " + installname, ToolTipIcon.Info);
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"c:/U.Rage/Sounds/notify.wav");
player.Play();
storeBrowser.GoBack();
igm = new Downloader();
igm.labelDWGame.Text = installname;
// this.Hide();
igm.Show();
return;
}
if (input.EndsWith(s) && isDownloading == true)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"c:/U.Rage/Sounds/notify.wav");
player.Play();
MessageBox.Show("Please wait until your download has been finished", "Warning");
storeBrowser.GoBack();
}
}
}
This happens when the download has been finished
void client_InstallFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if(Downloader.cancelDownload == false)
{
using (ZipFile zip = ZipFile.Read(#"C:\U.Rage\Downloads\" + installID + "Install.zip"))
{
//zip.Password = "iliketrains123";
zip.ExtractAll("C:/U.Rage/Games/", ExtractExistingFileAction.OverwriteSilently);
}
System.IO.File.Delete(#"C:/U.Rage/Downloads/" + installID + "Install.zip");
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(2, "Download Completed !", "Installing was succesful !", ToolTipIcon.Info);
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"c:/U.Rage/Sounds/notify.wav");
player.Play();
this.Show();
igm.Close();
isDownloading = false;
listView.Items.Clear();
var files = Directory.GetFiles(#"C:\U.Rage\Games\", "*.ugi").Select(f => new ListViewItem(f)).ToArray();
foreach (ListViewItem f in files)
{
this.LoadDataFromXml(f);
}
}
}
Here is the method for async data download that supports cancellation:
private static async Task<byte[]> downloadDataAsync(Uri uri, CancellationToken cancellationToken)
{
if (String.IsNullOrWhiteSpace(uri.ToString()))
throw new ArgumentNullException(nameof(uri), "Uri can not be null or empty.");
if (!Uri.IsWellFormedUriString(uri.ToString(), UriKind.Absolute))
return null;
byte[] dataArr = null;
try
{
using (var webClient = new WebClient())
using (var registration = cancellationToken.Register(() => webClient.CancelAsync()))
{
dataArr = await webClient.DownloadDataTaskAsync(uri);
}
}
catch (WebException ex) when (ex.Status == WebExceptionStatus.RequestCanceled)
{
// ignore this exception
}
return dataArr;
}
When you call CancelAsync, the AsyncCompletedEventArgs object passed to the completed callback will have the Cancelled property set to true. So you could write:
void client_InstallFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if(e.Cancelled)
{
// delete the partially-downloaded file
return;
}
// unzip and do whatever...
using (ZipFile zip = ZipFile.Read(#"C:\U.Rage\Downloads\" + installID + "Install.zip"))
See the documentation for more info.
The selected answer didn't work properly for me. Here's what I did:
When they click the cancel button I call the
Client.CancelAsync();
And then in the Web.Client DownloadFileCompleted:
Client.DownloadFileCompleted += (s, e) =>
{
if (e.Cancelled)
{
//cleanup delete partial file
Client.Dispose();
return;
}
}
And then when you try to re-download just instantiate a new client:
Client = WebClient();
This way the old async parameters won't be maintained.