The code below compiles but it does not display the text or photos of the website. I just want to run a program that involves HTTP communication with Silverlight. Any idea why I am not getting the website to display? I just get "error occurred" in the textBlock to display instead
namespace SilverlightApplication4
{
public partial class MainPage : UserControl
{
string baseUri = "http://yahoo.com";
WebClient client = new WebClient();
public MainPage()
{
InitializeComponent();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
}
private void Button1_Click(object sender, RoutedEventArgs e)
{
client.DownloadStringAsync(new Uri(baseUri));
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
textBox.Text = "Using WebClient: "+ e.Result;
else
{
textBox.Text = e.Error.Message;
textBlock.Text = "error occurred";
}
}
}
}
It is a crossdomain issue where the xml is not present in the server as a result you are getting the exception
Heres a link where I found the issue you can go through it
Security Exception
Related
Currently I create a Test Application to test my SOAP services, and everything works fine, and right now I want to return error message if user input ID which doesnt exist in DB or if miss to enter ID in textbox.
The error messaga should appear in txtRezultat or pop up message, doesnt matter.
private void button1_Click(object sender, EventArgs e)
{
AkontoService.AkontasSoapClient client = new AkontoService.AkontasSoapClient();
var respons = client.GetAkontasById(txtAkonto.Text);
txtRezultat.Text = respons;
}
You could check the content of the response before setting the content.
private void button1_Click(object sender, EventArgs e)
{
AkontoService.AkontasSoapClient client = new AkontoService.AkontasSoapClient();
var respons = client.GetAkontasById(txtAkonto.Text);
if (string.IsNullOrEmpty(respons))
{
txtRezultat.Text = "Error: Client not found!";
}
else
{
txtRezultat.Text = respons;
}
}
I'm having an issue getting a progressbar to show download progress. The files are downloading without issue, but something is causing my progressbar to not update and I can't figure out why.
I've tried setting the progressBar value manually in the download and wc_DownloadProgressChanged method, but the only place it actually changes is the Form1_Load method.
using System;
using System.Windows.Forms;
using System.Threading;
namespace Launch
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Downloader downloader = new Downloader();
ThreadStart job = new ThreadStart(downloader.download);
Thread thread = new Thread(job);
thread.Start();
}
private void ProgressBar_Click(object sender, EventArgs e)
{
}
public void SetProgress(int val)
{
progressBar.Value = val;
}
public void SetVisible(bool val)
{
progressBar.Visible = val;
}
}
}
using System;
using System.Data;
using System.Net;
using Newtonsoft.Json;
namespace Launch
{
class Downloader
{
public void download()
{
WebClient client = new WebClient();
string url = "https://someurl.com/manifest.json";
string json = client.DownloadString(url);
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);
DataTable dataTable = dataSet.Tables["Required"];
foreach (DataRow row in dataTable.Rows)
{
string remoteUri = row["url"].ToString();
string fileName = row["name"].ToString();
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadFile(remoteUri, fileName);
Console.WriteLine("Did something with " + remoteUri);
}
}
private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
var form = new Form1();
form.SetProgress(e.ProgressPercentage);
}
}
}
Would anyone be able to shed some light on what I'm doing wrong here?
EDIT:
I was able to get this working for the most part using DownloadFileAsync, but the progress bar was bouncing back and forth, I'm assuming because it's trying to calculate the progress for each individual file as bytes are received, so I'd like to get this working with DownloadFile.
The issue I'm now having with DownloadFile is that I have it running as a task but it's skipping all of the files (not downloading any of them, just prints them all out to console super fast).
Here's the code I'm using currently:
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
string url = "https://someurl.com/manifest.json";
string json = client.DownloadString(url);
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(json);
DataTable dataTable = dataSet.Tables["Required"];
foreach (DataRow row in dataTable.Rows)
{
string remoteUri = row["url"].ToString();
string fileName = row["name"].ToString();
Task.Run(() => {
client.DownloadFile(remoteUri, fileName);
});
Console.WriteLine("Did something with " + remoteUri);
}
}
private void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
this.BeginInvoke((MethodInvoker)delegate {
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
label1.Text = "Downloaded ";
label2.Text = e.BytesReceived.ToString();
label3.Text = e.TotalBytesToReceive.ToString();
progressBar.Value = int.Parse(Math.Truncate(percentage).ToString());
});
}
Any ideas?
Use this code below :
private void Form1_Load(object sender, EventArgs e)
{
WebClient client = new WebClient();
client.DownloadProgressChanged += client_DownloadProgressChanged;
client.DownloadStringCompleted += client_DownloadStringCompleted;
Uri url = new Uri("url");
client.DownloadStringAsync(url);
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
SetVisible(false);
}
void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
SetProgress(e.ProgressPercentage);
}
public void SetProgress(int val)
{
progressBar.Value = val;
}
public void SetVisible(bool val)
{
progressBar.Visible = val;
}
This likely should belong to https://codereview.stackexchange.com/
First of all, do not add a handler in a loop
client.DownloadProgressChanged += client_DownloadProgressChanged;
First time it will be fine, on 2nd item it will be called 2x times, on 3rd time it will be called 3 times, etc. You want to set handler once. Move it just after line:
WebClient client = new WebClient();
Second of all, each time a progress update is fired you are creating a new instance of the form. Create a private variable or property once.
private Form1 form = new Form1();
edit:
In case of UI, usually you can modify it only in the dispatcher thread that created it or use marshaling. I would just remove it as our already downloading the string async.
Also, I would not use e.ProgressPercentage, but something like:
Math.Truncate(e.BytesReceived / (double)e.TotalBytesToReceive * 100)
My app for Windows Phone has a string downloaded from server. I'm trying displaying a textBlock while the download is in execution. However, my code doesn't works.
The textBlock is not displayed. Why? Is there another way for this?
WebClient webClient1 = new WebClient();
webClient1.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
webClient1.DownloadStringCompleted += webClient_DownloadStringCompleted1;
webClient1.DownloadStringAsync(new Uri(string.Format(url + insCodComanda.Text + "&random=" + ran.Next().ToString(), UriKind.RelativeOrAbsolute)));
public void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
testete.Visibility = Visibility.Visible;
}
void webClient_DownloadStringCompleted1(object sender, DownloadStringCompletedEventArgs e)
{
testete.Visibility = Visibility.Collapsed;
}
If you want to manipulate UI element like that you need to use Dispatcher
this.Dispatcher.BeginInvoke(new Action(() => testete.Visibility = Visibility.Visible));
Using WebClient in WPF app, the following code works fine, when an image is downloaded an event fire correctly.
I need to pass some parameters to ImageDownloadCompleted in order to specifically know which image has been just downloaded.
Using webClient.DownloadDataAsync(new Uri(url), url); I cannot get the result wanted.
What am I doing wrong here?
PS: Basically I would use this parameters to order in an array the images resulted. If very is another way to achieve this, please let me know.
private void DownloadAndPrintImagesAsync(IEnumerable<string> urls)
{
foreach (var url in urls)
{
var webClient = new WebClient();
webClient.DownloadDataCompleted += ImageDownloadCompleted;
webClient.DownloadDataAsync(new Uri(url), url); // I want to pass url
}
}
private void ImageDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
if (!e.Cancelled && e.Error == null)
{
// I need to get url here
}
}
It's in the UserState property of the DownloadDataCompletedEventArgs argument:
private void ImageDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
{
if (!e.Cancelled && e.Error == null)
{
var url = (string)e.UserState;
...
}
}
I know there have been a lot of questions here but I have went through a ton of them and have had little luck. I'm new to events and background workers and I just don't know the best way to implement this.
I have a a basic Windows form in C#. It contains a progress bar. I am calling a class that is to download a file. I want the progress bar to update based on that download. I have it working fine if everything is all in the same class, but I can't get it to work in this situation. What is the best way to handle this and how might I go about it? Currently I'm doing this:
WebClient downloader = new WebClient();
downloader.DownloadFileCompleted += new AsyncCompletedEventHandler(Completed);
downloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(ProgressChanged);
And then for progress changed I do this:
public void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
pbDownload.Value = e.ProgressPercentage;
}
But when I put all of this except for the progress bar in a separate class, it gets all messed up. Ideas? Thanks!
I have this witch is about the same as what you are trying to do and works fine
FStatus ... form reference
FrmStatus FStatus = null;
public void ProgressInit(String caption, string opis, int Max)
{
FStatus = new SZOKZZ.FrmStatus();
FStatus.InitProc(Max);
FStatus.SetCaption(caption, opis);
FStatus.Show();
}
public void DLProgress(string curl, string cdl)
{
WebClient webClient = new WebClient();
webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(DLDone);
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DLSetProc);
webClient.DownloadFileAsync(new Uri(curl), cdl);
}
private void DLSetProc(object sender, DownloadProgressChangedEventArgs e)
{
this._FileProcentDownloaded = e.ProgressPercentage;
FStatus.SetProcDL(this._FileProcentDownloaded);
}
private void DLDone(object sender, AsyncCompletedEventArgs e)
{
_DlError = e.Error;
FStatus.Dispose();
FStatus = null;
}
You should call Application.DoEvents(); to force your form to update controls based on their new values :
public void ProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
pbDownload.Value = e.ProgressPercentage;
Application.DoEvents();
}
Regards