exception,download,webclient,connect , showing error massage for dont connect the internet in webclient in c#

showing error massage for dont connect the internet in webclient in c#


Tag: exception,download,webclient,connect

my code for download-file is:

private void Completed(object sender, AsyncCompletedEventArgs e)
        MessageBox.Show("Download completed!");
    //----------- Download complete
    Stopwatch sw = new Stopwatch();
    private void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    {// Calculate download speed and output it to labelSpeed.
        lblspeed.Text = string.Format("{0} kb/s", (e.BytesReceived / 1024d / sw.Elapsed.TotalSeconds).ToString("0.00"));
        // Update the progressbar percentage only when the value is not the same.
        progressBar.Value = e.ProgressPercentage;// Show the percentage on our label.
        lblper.Text = e.ProgressPercentage.ToString() + "%";// Update the label with how much data have been downloaded so far and the total size of the file we are currently downloading
        lblsize.Text = string.Format("{0} MB’s / {1} MB’s",
        (e.BytesReceived / 1024d / 1024d).ToString("0.00"),
        (e.TotalBytesToReceive / 1024d / 1024d).ToString("0.00"));
    public void DownloadFile(string urlAddress, string location)
        using (WebClient client = new WebClient())
            client.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
            client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);// The variable that will be holding the url address (making sure it starts with http://)
            Uri URL = urlAddress.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ? new Uri(urlAddress) : new Uri("http://" + urlAddress);// Start the stopwatch which we will be using to calculate the download speed
                // Start downloading the file
                client.DownloadFileAsync(URL, location);
            catch (Exception ex)

when i'm don't connect to internet and Call DownloadFile method , app message: Download Completed!!!

Whats problem?


You need to check if an error has occurred during downloading. Something like this:

private void Completed(object sender, AsyncCompletedEventArgs e)
  if(!e.Cancelled && e.Error == null)
    MessageBox.Show("Download completed!");


Exception when attempting to modify Dictionary

I was creating a Dictionary to manage Threads and I ran into this exception when I attempt to clear dead threads after adding some Threads into the dictionary. using System; using System.Collections.Generic; using System.Threading; namespace SysCat { public class ThreadManager { public static readonly ThreadManager GlobalThreadManager = new ThreadManager( );...

How can I update Android SDK without internet using updated SDK of other computer?

Websites, Blog or Videos with working files like Lynda Tutorials I don't have enough cash to enrol

What happens with duplicates when inserting multiple rows?

I am running a python script that inserts a large amount of data into a Postgres database, I use a single query to perform multiple row inserts: INSERT INTO table (col1,col2) VALUES ('v1','v2'),('v3','v4') ... etc I was wondering what would happen if it hits a duplicate key for the insert....

Fatal Exception Main Android Null Pointer Exception

I am having an issue with this weather app that I am making with TreeHouse I have asked a question on their forums, but no avail. Here are my two files in question... MainActivity package com.megliosolutions.stormy; import android.content.Context; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log;...

ASP WebForms file download works only sometimes

I developed code to add/remove/download files to orders and it works good. Downloading code: Response.Clear(); Response.ClearHeaders(); Response.ContentType = GetContentType(fileExtension); Response.AppendHeader("Content-Disposition", String.Format("attachment; filename=\"{0}\"", fileName)); Response.WriteFile(filePath); Response.Flush(); Response.Close(); Everything works good when code is in OnItemCommand method in DataList. protected void dlAttachemnts_OnItemCommand(object sender, DataListCommandEventArgs e) { if (e.CommandName ==...

FileNotFoundException EACCES (Permission Denied)

I'm getting an exception that file open permission is denied when I'm trying to open a FileInputStream. File myFile = new File(Environment.getExternalStorageDirectory() .getAbsolutePath() + "/test/test.txt"); try { FileInputStream inStream = new FileInputStream(myFile); // crash Here's the stacktrace: System.err﹕ java.io.FileNotFoundException: /storage/emulated/0/test/test.txt: open failed: EACCES (Permission denied) System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:456) System.err﹕ at...

How to get raw Exception Message without HTML in Laravel?

I make ajax requests to Laravel backend. In backend I check request data and throw some exceptions. Laravel, by default, generate html pages with exception messages. I want to respond just raw exception message not any html. ->getMessage() doesn't work. Laravel, as always, generate html. What shoud I do?...

std::ostream to QString?

Is there a way to convert an std::ostream to a QString? Allow me to expand in case it is useful: I am writing a program in C++/Qt and I used to (not) deal with / debug exceptions by just using std::cout, as in for example: std::cout << "Error in void...

exception catching for int divided by 0

Recently i was trying a simple exception program in C++ which goes like this:- #include <iostream> #include <exception> #include <stdexcept> using namespace std; int main() { int x=5, y=0; try { int z=x/y; cout<<"z="<<z; } catch (exception& e) { cout<<"exception caught: "<<e.what(); } return 0; } Why is no exception...

Throwable constructors

The 4 types of Throwable constructors are :- Throwable() : Constructs a new throwable with null as its detail message. Throwable(String message) : Constructs a new throwable with the specified detail message. Throwable(String message, Throwable cause) : Constructs a new throwable with the specified detail message and cause. Throwable(Throwable cause)...

How can I extract ALL the information of the JavaScript native exception?

Well, as JavaScript is executed in the client-side, I can't control a bunch of environment variables and, at some point, my app will probably throw an exception. What I want to do is to get this exception and make my app fail gracefully and show the maximum information as possible...

DownloadFileAsync Error

I keep get this error while trying to download a file using WebClient.DownloadFileAsync System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. ---> System.IO.IOException: Unable to read data from the transport connection: An established connection was aborted by the software in your host machine. ---> System.Net.Sockets.SocketException:...

SimpleMembershipProvider WebSecurity.InitializeDatabaseConnection The login from an untrusted domain

I export the database to the server and i've problem. When I start application i see this error An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code Login failed. The login is from an untrusted domain and cannot be used with Windows authentication. WebSecurity.InitializeDatabaseConnection("DefaultConnection",...

App Not Downloading Newest Version Of File [Java]

Okay, I've been trying to figure this out for a few hours and it's starting to kill me. I wrote a primitive version checker for an app I work on every once and awhile. It's just a simple for fun project. The version checker has been a pain though. It...

Exception in async task gets intercepted in Visual Studio

I want to run several tasks, some of which would complete async'ly, and then wait for all of them to complete. As the tasks may throw exceptions, I want to catch and log them. sample code for that: static async Task doit(int x) { try { Console.WriteLine("{0} {1} start", x,...

Java Ignoring an Exception and Continuing Loop

I have a program where it checks if a given URL is real multiple times, each with different URLs. I have a for loop set up: for (int i=0;i<100;i++) { URL url=findWebsite(); System.out.println(readURL(url)); } But when it encounters a URL that does not exist, it just throws a Runtime error...

Any way to catch an exception occurring on a thread I don't own?

I'm using a crappy third party library because unfortunately I have no choice. This library creates a bunch of threads internally when I call it, and occasionally throws a NullReferenceException on one of these threads. Is there any way for me to catch these exceptions even though I don't own...

Changing text of a TextView throws NullPointer Exception

I'm just following the basic tutorial on the Android website. However, I'm trying to change a few things just for fun. For instance, instead of creating a runtime TextView (as in the tutorial) within the method onCreate(...) of the DisplayMessageActivty class, I've defined a static TextView in the XML layout...

Class with long name

Name of Exception class in Java must have Exception suffix also describe its throwing situation. Now I have two exception classes in about primary external storage in Android: /** * Thrown when Application tries to access primary external storage and it is not * available for write.This only depends on...

RoundingMode.UNNECESSARY throws exception

I wrote this to test BigDecimal in action but found that RoundingMode.UNNECESSARY threw an exception. Can anyone explain why? public class TestRounding2 { public static void main(String args[]) { Locale swedish = new Locale("sv", "SE"); BigDecimal pp; //declare variable pp=pounds pence NumberFormat swedishFormat = NumberFormat.getCurrencyInstance(swedish); Scanner scan = new Scanner(System.in);...

How do I read nothing else but a String using exceptions?

would you be so kind and help me please? Im doing a simple quiz game, during the game the user is asked to enter his answer. Its either A,B or C. i would like to have this covered with try/catch exceptions... What I want this code to do, is to...

C++ Have lone executable log exceptions?

I'm currently in a beta testing phase of my C++ Server. I'm sending it out to users to stress test it to see if an exceptions show up. However, since the .exe is a standalone, how do I make it so it automatically creates a dump or a log of...

Destructor throwing an exception

I'm reading Scott Meyerses C++ and now I'm at the destructor throwing exceptions section. Here is what is he said: When the vector v is destroyed, it is responsible for destroying all the Widgets it contains. Suppose v has ten Widgets in it, and during destruction of the first one,...

Java 5 Multi threading, catch thread exceptions

I've got a class that generates threads (file i/o). I need to catch exceptions in the thread - I don't want to do anything fancy, I want to kill the main thread, rather, stop processing altogether so it can start over. If I catch the exceptions in the thread, that's...

zip and download from nodejs

I am trying to zip the file and download from server using easy-zip module. But now I can write into a server using following code but how can i make it downloadable??? var app = require('express')(); var easyzip = require('easy-zip'); app.get('/api/downloadFile',function(req,res){ console.log("inside req"); var data = "<html><body><h1>Inside new Html</h1></body></html>"; var...

Retry on database exception using php

I have been working on exceptions thrown by php - mysqli & created this snippet below that tries to check a few times to see if a temp glitch has caused the database to fail. if so, it tries to recover. If it cannot then it quits/ ends. Now while...

throws x extends Exception method signature

Reading the JavaDoc of Optional, I bumped in a weird method signature; I never saw in my life: public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X extends Throwable At first glance, I wondered how the generic exception <X extends Throwable> is even possible, since you can't do...

java.lang.ArrayStoreException with new JPanel

I have a problem: public static JPanel regNewBodyPart(int i, int x, int y){ //System.out.println(i); body[i] = new SnakeBlock(); JPanel bp = body[i]; //bp.setBackground(Color.GREEN); bp.setBounds(x, y, 20, 20); bp.setVisible(true); registeredBodyParts++; return(bp); } Throws an java.lang.ArrayStoreException, when I change body[i] = new SnakeBlock(); to body[i] = new Block(); does not. I dont...

java.util.NoSuchElementException when using Scanner.next()

Java noob working on a project where I'm supposed to display data obtained from a text file onto grids. Project is essentially written, but output displays this exception: run: Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1371) at inputOutput.ReadDataFile.populateData(ReadDataFile.java:50) at boggle.Boggle.main(Boggle.java:27) Java Result: 1 BUILD SUCCESSFUL (total time: 0...

How to check what constraint has been violated?

I'm used to check if the user try to store a valid data with cathcing the ConsratinViolationException, like that: try { //persisitng to a db } catch (ConstraintViolationException e){ //Print message } I'm using PostgreSQL and now I'm under the isssue that the persisitng can violate more than one different...

how exception finds correct catch block

I was wondering how catch block works. I have below code, catch(ArithmeticException e){ System.out.println("task1 is completed"); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("task 2 completed"); } catch(Exception e){ System.out.println("common task completed"); } If divide by zero occurs it will go to Arithmetic Exception and skips rest. How is it internally implemented so that...

Why is eclipse complaining when I try to close BufferedReader in finally block?

Here is my code: public static String readFile() { BufferedReader br = null; String line; String dump=""; try { br = new BufferedReader(new FileReader("dbDumpTest.txt")); } catch (FileNotFoundException fnfex) { System.out.println(fnfex.getMessage()); System.exit(0); } try { while( (line = br.readLine()) != null) { dump += line + "\r\n"; } } catch (IOException...

android - No Activity found to handle intent action.VIEW

I got an exception in my android app: 06-18 17:57:39.816 6333-6333/com.appsrox.instachat E/InputEventReceiver﹕ Exception dispatching input event. 06-18 17:57:39.816 6333-6333/com.appsrox.instachat E/MessageQueue-JNI﹕ Exception in MessageQueue callback: handleReceiveCallback 06-18 17:57:39.816 6333-6333/com.appsrox.instachat E/MessageQueue-JNI﹕ android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=href (has extras) } at...

Python exception for HTTP response codes

I'd like to raise a Python-standard exception when an HTTP response code from querying an API is not 200, but what specific exception should I use? For now I raise an OSError: if response.status_code != 200: raise OSError("Response " + str(response.status_code) + ": " + response.content) I'm aware of the...

Replace backslash in string

I have a String in which I am trying to replace the number enclosed by two backslashes. For example: \10\ , I am trying to replace that with 10. I am currently using this regex to do that: String texter = texthb.replaceAll("\\.+\\", "\\"+String.valueOf(pertotal + initper)+"\\"); This line is giving the...

Ubuntu down load a package and all of its dependencies without installing them

I need to download a package and all of its dependencies without installing any of them. I'm looking for a command like apt-get -R --download-only install package-name Or any solution that would produce the same result. Based on my research I could not find a solution that produces this and...

BufferedWriter closed throws exception

I have made a method to write a log in an external storage of Android. public int writeLog(String clase, String metodo, Object object){ try{ File folder = new File(Environment.getExternalStorageDirectory(), Constants.ROUTE_FILES_TEXT); if (!folder.exists()) { folder.mkdir(); } FileWriter fw = new FileWriter(folder.toString() + "/log.txt", true); BufferedWriter out = new BufferedWriter(fw); out.write("Hora: "...

How to generate text files and download a zip file in Javascript?

I would like to know the best way in Javascript (maybe in JQuery) to do the following things without server coding if able : Generate around 20 text files from sets of objects. Zip these files into a ZIP file. Download this ZIP file. 1. Generate around 20 text files...

Laravel MethodNotAllowedHttpException

I am currently creating a website that, once the user arrives, they are greeted by a form with which they input their unique id and DoB. Upon entering the information and clicking submit, they are sent to the main form which has only a little information on it and the...

Global Exception Handling in play framework java 2.3.7

I am trying to implement global exception handling in Play framework(RESTful) using Java. While searching I found out that extending GlobalSettings and overriding the onError method should handle all errors and give the appropriate response/view. But in the console where I execute "activator run", I still get the ugly stack...

Exception handler in Node.js

I have a very simple question; I have a wrong endpoint and when I try the following code, it throws an exception client.post("http://WrongEndPoint", [], function (data, response) { console.log("data:", data, "response:", response.statusCode); }) ERROR: events.js:72 throw er; // Unhandled 'error' event ^ Error: connect ETIMEDOUT at errnoException (net.js:905:11) at Object.afterConnect...

String returned positive booleans, despite not fulfilling any [closed]

import java.util.Scanner; public class Driver { public static void main(String[] args) { String userName; boolean good = false; boolean good1 = false; boolean good2 = false; boolean good3 = false; do{ Scanner scan = new Scanner(System.in); System.out.print("Please enter username: "); userName=scan.next(); try { checkForUpper(userName); good = true; } catch (MustHaveUpperCaseException...

Add user to LDAP using JAVA. Naming.InvalidNameException: Invalid Name

I am practicing in Java, adding a user to LDAP(v3, running on my Virtual machine). Userdetails and attributes are obtained from postgres database running locally. This is my code (may not be a good approach): public class LDAPConnector { static final String DOMAIN_URL = "ldaps://"; static final String ADMIN_NAME =...

Express can't set headers after they're sent while downloading from mobile

I have fairly simple route defined: router.get('/download', function(req, res){ var file = __dirname + 'file.ext'; res.download(file); }); It works fine when I'm making requests from my comp, but once I do it from smartphone, server crashes and I get following error: throw new Error('Can\'t set headers after they are sent.');...

Exception error using C++ Thread Pool Library (CTPL)

I am trying to use the C++ Thread Pool Library (CTPL), which pleasantly consists in a single header file. For this, I created a very simple test program. Here is the code : #include <iostream> #include "ctpl_stl.h" void myFunction(int threadID_0) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } int main() { ctpl::thread_pool p(2); // We...

Try-Except block in python

Here is the code that I'm running, basically it just ask the user to type in numbers and then after I type in "done", calculate the average of them: average = 0 total = 0.0 count = 0 while True: num = raw_input() if num == "done": break try: int(num)...

Does throwing an Exception have side effects beyond just constructing the exception?

I've got it in my head that throwing an exception has side effects (like collecting stack information), but I'm realizing it might not. Is there a difference between the following two versions of GetException? public Exception GetException() { try { throw new Exception("Bummer"); } catch (Exception e) { return e;...

How to catch an exception and continue without stopping

I have the following code import msgpack def deserialize(data) return msgpack.loads(data) for data in stream: print deserialize(data) Now, the issue is that some data is (maybe) corrupted.. and I am seeing this error: UnicodeDecodeError: 'utf8' codec can't decode byte 0xcc in position 0: invalid continuation byte Why am I getting...

Java: unhandled exception

I would like to handle an exception but the Eclipse editor is giving me tips which I'm not understanding. This is the method's code: public Collection<String> listOfFriends(String codePerson) throws NoSuchCodeException { Collection<String> s = new LinkedList<>(); try { people.get(codePerson).getFriendsCodes().forEach( code -> s.add(getPerson(code))); } catch (Exception e) { e.printStackTrace(); } return...

errors not being thrown after promise

i have a weird situation i would like to know how to solve. in my app errors that happen after functions with promises do net get thrown and the app just stalls. here an example: getTenant = (req) -> deferred = Q.defer() deferred.resolve('foo') if req.info.referrer deferred.resolve('bar') if !req.info.referrer deferred.promise Routes...