Getting NotFound trying to access google.com with WebClient - c#

the problem is : the remote server returned an error :NotFound
private WebClient client = new WebClient();
private string siteUrl = "http://www.google.com/";
// Constructor
public MainPage()
{
InitializeComponent();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(siteUrl));
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
if (e.Error == null)
{
webClientResults.Text = e.Result;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Check the network connectivity in your device. Such error occurs mainly when there is no proper internet connectivity is not available.
There is no problem in your code.

Related

I am trying to post image on Facebook using asp.net but I am getting exception as Thread was being aborted

C# Code
I am using ASPSnippets.FaceBookAPI to upload image on Facebook in local machine I get exception as Thread was being aborted and if I try on live domain it says "Can't load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and sub-domains of your app to the App Domains field in your app settings"
protected void Page_Load(object sender, EventArgs e)
{
FaceBookConnect.API_Key = "gfafsa";
FaceBookConnect.API_Secret = "bdhsafvhj";
if (!IsPostBack)
{
try
{
string code = Request.QueryString["code"];
if (!string.IsNullOrEmpty(code))
{
if (Session["File"] != null)
{
FaceBookConnect.PostFile(code, "me/photos", (HttpPostedFile)Session["File"], Session["Message"].ToString());
}
else
{
Dictionary<string, string> data = new Dictionary<string, string>();
data.Add("message", Session["Message"].ToString());
FaceBookConnect.Post(code, "me/feed", data);
}
Session["File"] = null;
Session["Message"] = null;
}
}
catch(Exception ex)
{
}
finally
{
}
}
}
protected void lbtnSubmit_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.HasFile)
Session["File"] = FileUpload1.PostedFile;
Session["Message"] = txtCaption.Text;
FaceBookConnect.Authorize("user_photos,publish_actions", Request.Url.AbsoluteUri.Split('?')[0]);
Response.Redirect("", false);
}
catch(Exception ex)
{
Response.Write(ex);
}
finally
{
}
}

c# webclient not timing out

Im trying to download files using extended WebClient with set timeout and I have a problem with the timeout (or what I think should cause timeout).
When I start the download with WebClient and receive some data, then disconnect wifi - my program hangs on the download without throwing any exception. How can I fix this?
EDIT: It actually throws exception but way later than it should (5 minutes vs 1 second which i set) - that is what Im trying to fix.
If you find anything else wrong with my code, please let me know too. Thank you for help
This is my extended class
class WebClientWithTimeout : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest w = base.GetWebRequest(address);
w.Timeout = 1000;
return w;
}
}
This is the download
using (WebClientWithTimeout wct = new WebClientWithTimeout())
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
try
{
wct.DownloadFile("https://example.com", file);
}
catch (Exception e)
{
Console.WriteLine("Download: {0} failed with exception:{1} {2}", file, Environment.NewLine, e);
}
}
Try this, you can avoid UI blocking by this. Coming the WiFi when device connects to WiFi the download resumes.
//declare globally
DateTime lastDownloaded = DateTime.Now;
Timer t = new Timer();
WebClient wc = new WebClient();
//declarewherever you initiate download my case button click
private void button1_Click(object sender, EventArgs e)
{
wc.DownloadProgressChanged += Wc_DownloadProgressChanged;
wc.DownloadFileCompleted += Wc_DownloadFileCompleted;
lastDownloaded = DateTime.Now;
t.Interval = 1000;
t.Tick += T_Tick;
wc.DownloadFileAsync(new Uri("https://github.com/google/google-api-dotnet-client/archive/master.zip"), #"C:\Users\chkri\AppData\Local\Temp\master.zip");
}
private void T_Tick(object sender, EventArgs e)
{
if ((DateTime.Now - lastDownloaded).TotalMilliseconds > 1000)
{
wc.CancelAsync();
}
}
private void Wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
{
lblProgress.Text = e.Error.Message;
}
}
private void Wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
lastDownloaded = DateTime.Now;
lblProgress.Text = e.BytesReceived + "/" + e.TotalBytesToReceive;
}

Connecting asp.net C# to server with Linux O.S using telnet protocol

i am trying to design a interface local website for Linux cash server , i am using asp.net with c# , at first i just try to make a test connection , i make one bottom with two textboxes
and one label and here's is my code :
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private Socket clientSocket;
private IPAddress hostAddress;
private void telnetSocketAsyncEventArgs_Completed(object sender, SocketAsyncEventArgs e)
{
try
{
if (e.SocketError == SocketError.Success)
{
if (e.LastOperation == SocketAsyncOperation.Connect)
{
errorplace.Text="Service Is Running";
}
}
else
{
errorplace.Text="Service Is not Running";
}
}
catch (SocketException ex )
{
errorplace.Text = ex.Message;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
{
try
{
if (string.IsNullOrEmpty(IPTextBox.Text))
return;
if (string.IsNullOrEmpty(PortTextBox.Text))
return;
int port;
hostAddress = Dns.GetHostEntry(IPTextBox.Text).AddressList[0];
int.TryParse(PortTextBox.Text, out port);
if (hostAddress.AddressFamily == AddressFamily.InterNetwork)
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
else if (hostAddress.AddressFamily == AddressFamily.InterNetworkV6)
clientSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs telnetSocketAsyncEventArgs = new SocketAsyncEventArgs();
telnetSocketAsyncEventArgs.RemoteEndPoint = new IPEndPoint(hostAddress, port);
telnetSocketAsyncEventArgs.Completed += new
EventHandler<SocketAsyncEventArgs>(telnetSocketAsyncEventArgs_Completed);
clientSocket.ConnectAsync(telnetSocketAsyncEventArgs);
}
catch (SocketException )
{
errorplace.Text="Service Is not Running";
}
finally
{
}
}
}
}
i don't have any problem with code debugging but when each time i try to connect its said "Service Is not Running"..
please i need the help in that and i just want to be sure is asp.net with linux server running ok? so i can go ahead with my project?

download file from web in background in wp7

I'm writing an app in c# for wp7: 2 pages [mainpage, secondpage].
The application starts in mainpage, then the user can navigate to secondpage (using NavigationService.Navigate) in secondpage.
In secondpage WebClient downloads a file in the isolatedStorage.
My problem is that the download freezes when the user returns back to mainpage using the back key!
There is a way to do that in background so the user can navigate throw the pages freely?
Here is the code of the secondpage class (there is also a button with webClient.OpenReadAsync(uri) in the click event).
public partial class SecondPage : PhoneApplicationPage
{
WebClient webClient = new WebClient();
IsolatedStorageFile Storage = IsolatedStorageFile.GetUserStoreForApplication();
public SecondPage()
{
InitializeComponent();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
try
{
if (e.Result != null)
{
string fileName = "download.txt";
IsolatedStorageFileStream f = new IsolatedStorageFileStream(fileName, System.IO.FileMode.Create, Storage);
long fileNameLength = (long)e.Result.Length;
byte[] byteImage = new byte[fileNameLength];
e.Result.Read(byteImage, 0, byteImage.Length);
f.Write(byteImage, 0, byteImage.Length);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
void webClient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
try
{
if (ProgressDownload.Value <= ProgressDownload.Maximum)
{
ProgressDownload.Value = (double)e.ProgressPercentage;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Thanks
with the BackgroundWorker class i have this issue: when i call the webClient.OpenReadAsync the bw_doWork function (code is under) ends, because that call is async! so the bw reports the completeEvent.
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
WebClient webClient = new WebClient();
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(new Uri("http://foo.com/asd.txt"));
}
Check out the Background Transfer APIs - sounds like this is exactly what you need to accomplish your requirements.

How to capture any error with Webclient?

Im trying to capture connection problem when using WebClient. Example, unreachable, timeout etc. Code belows doesnt work, as if there is nothing wrong.
WebClient wc = new WebClient();
try
{
wc.UploadFileAsync(new Uri(#"ftp://tabletijam/FileServer/upload.bin"), Directory.GetCurrentDirectory() + #"\crypto.bin");
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
The code you are using, just sends the file ... you need to implement the Async part.
WebClient webClient = new WebClient();
webClient.UploadFileAsync(address, fileName);
webClient.UploadProgressChanged += WebClientUploadProgressChanged;
webClient.UploadFileCompleted += WebClientUploadCompleted;
...
void WebClientUploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
{
Console.WriteLine("Download {0}% complete. ", e.ProgressPercentage);
}
void WebClientUploadCompleted(object sender, UploadFileCompletedEventArgs e)
{
// The upload is finished, clean up
}
try
{
// trying to make any operation on a file
}
catch (IOException error)
{
if(error is FileNotFoundException)
{
// Handle this error
}
}
use this code but with your scenario

Categories

Resources