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;
...
}
}
Related
CefSharp Version: 86.0.241.0
.Net Framework 4.5.2
I am new to C# and my English is not good. Sorry....
Try a variety of methods to implement:
private void button18_Click(object sender, EventArgs e)
{
//1
DevToolsClient devTool = chromiumWebBrowser1.GetBrowser().GetDevToolsClient();
devTool.ExecuteDevToolsMethodAsync("Browser.getVersion").Wait();// stuck
//2
DevToolsClient dev = DevToolsExtensions.GetDevToolsClient(chromiumWebBrowser1);
dev.ExecuteDevToolsMethodAsync("Browser.getVersion").Wait();// stuck
}
// load complete after:
chromiumWebBrowser1.FrameLoadEnd += new EventHandler<FrameLoadEndEventArgs>(new Action<object, FrameLoadEndEventArgs>((s, ea) => {
IBrowser browser = chromiumWebBrowser1.GetBrowser();
DevToolsClient devTool = chromiumWebBrowser1.GetBrowser().GetDevToolsClient();
//devTool.Browser.GetVersionAsync().Wait(); //execute nomal
devTool.DOM.GetDocumentAsync().Wait(); // stuck
}));
//
private void button1_Click(object sender, EventArgs e)
{
DevToolsClient devTool = chromiumWebBrowser1.GetBrowser().GetDevToolsClient();
//devTool.Page.ReloadAsync(); //nomal page reload
devTool.Page.ReloadAsync().Wait(); // stuck
}
In addition to being successful Browser.GetVersionAsync() in FrameLoadEnd event .
A solution has been found! use async/await solve.
private async void button1_Click(object sender, EventArgs e)
{
DevToolsClient devTool = chromiumWebBrowser1.GetBrowser().GetDevToolsClient();
DevToolsMethodResponse resp = await devTool.ExecuteDevToolsMethodAsync("DOM.getDocument");
Console.WriteLine(resp.ResponseAsJsonString);
}
The final solution:
//global variable
DevToolsClient devTool = null;
//Should be obtained at initialization time DevToolsClient,And only get it once
//Each call to GetDevToolsClient() messageId resets
chromiumWebBrowser1.IsBrowserInitializedChanged += new EventHandler(delegate {
devTool = chromiumWebBrowser1.GetBrowser().GetDevToolsClient();
});
//Common execution method method: CDP method name ,param: method param
public async Task<string> ExecuteDevToolsMethods(string method, IDictionary<string, object> param = null)
{
DevToolsMethodResponse resp = await devTool.ExecuteDevToolsMethodAsync(method, param);
return resp.ResponseAsJsonString;
}
//call
private void button3_Click(object sender, EventArgs e)
{
ExecuteDevToolsMethods("DOM.getDocument").ContinueWith(new Action<Task<string>>((result) => {
Console.WriteLine(result.Result);
}));
}
if Please point out if I have misunderstood,very thank!
I am trying to validate a winform web browser control url when a button is clicked. I would like to see if the web browser's current url matches a certain url. When I try to run this code the program freezes
private void button_Click(object sender, EventArgs e)
{
// Check to see if web browser is at URL
if (webBrowser1.Url.ToString != "www.google.com" || webBrowser1.Url.ToString == null)
{
// Goto webpage
webBrowser1.Url = new Uri("www.google.ca");
}
else {
webBrowser1.Document.GetElementById("first").InnerText = "blah";
webBrowser1.Document.GetElementById("second").InnerText = "blah";
}
}
Here you go.
private void button1_Click(object sender, EventArgs e)
{
webBrowser1.Url = new Uri("https://www.google.ca");
// Check to see if web browser is at URL
if (webBrowser1.Url != null)
{
if (webBrowser1.Url.ToString() != "https://www.google.com" || webBrowser1.Url.ToString() == null)
{
// Goto webpage
webBrowser1.Url = new Uri("www.google.ca");
}
else
{
webBrowser1.Document.GetElementById("first").InnerText = "blah";
webBrowser1.Document.GetElementById("second").InnerText = "blah";
}
}
}
1) Please use the schema with the URL.
2) Use ToString() as a function.
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
This foreach loop checks a webpage and sees if there are any images then downloads them. How do i stop it? When i press the button it continues the loop forever.
private void button1_Click(object sender, EventArgs e)
{
WebBrowser browser = new WebBrowser();
browser.DocumentCompleted +=browser_DocumentCompleted;
browser.Navigate(textBox1.Text);
}
void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser browser = sender as WebBrowser;
HtmlElementCollection imgCollection = browser.Document.GetElementsByTagName("img");
WebClient webClient = new WebClient();
int count = 0; //if available
int maximumCount = imgCollection.Count;
try
{
foreach (HtmlElement img in imgCollection)
{
string url = img.GetAttribute("src");
webClient.DownloadFile(url, url.Substring(url.LastIndexOf('/')));
count++;
if(count >= maximumCount)
break;
}
}
catch { MessageBox.Show("errr"); }
}
use the break; keyword to break out of a loop
You do not have an infinite loop, you have an exception that is being thrown based on how you are writing the file to disk
private void button1_Click(object sender, EventArgs e)
{
WebBrowser browser = new WebBrowser();
browser.DocumentCompleted += browser_DocumentCompleted;
browser.Navigate("www.google.ca");
}
void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser browser = sender as WebBrowser;
HtmlElementCollection imgCollection = browser.Document.GetElementsByTagName("img");
WebClient webClient = new WebClient();
foreach (HtmlElement img in imgCollection)
{
string url = img.GetAttribute("src");
string name = System.IO.Path.GetFileName(url);
string path = System.IO.Path.Combine(Environment.CurrentDirectory, name);
webClient.DownloadFile(url, path);
}
}
That code works fine on my environment. The issue you seemed to be having was when you were setting the DownloadFile filepath, you were setting it to a value like `\myimage.png', and the webclient could not find the path so it threw and exception.
The above code drops it into the current directory with the extension name.
Maybe the Event browser.DocumentCompleted cause the error, if the page refreshes the event gets fired again. You could try to deregister the event.
void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser browser = sender as WebBrowser;
browser.DocumentCompleted -= browser_DocumentCompleted;
HtmlElementCollection imgCollection = browser.Document.GetElementsByTagName("img");
WebClient webClient = new WebClient();
foreach (HtmlElement img in imgCollection)
{
string url = img.GetAttribute("src");
string name = System.IO.Path.GetFileName(url);
string path = System.IO.Path.Combine(Environment.CurrentDirectory, name);
webClient.DownloadFile(url, path);
}
}
I want to get some data from a website but my code can't get url. Because if state is always false and my textbox called "weather1" always display "ece".
When I make the value of textbox as e.Result instead of "ece", it displays "DownloadStringCompletedEventArgs ".
And there is no error or warning.
What should I do? What's wrong with the code?
public void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (!e.Cancelled && e.Error == null)
{
string res = Convert.ToString(e.Result);
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(res);
var table = doc.DocumentNode.SelectSingleNode("//table[#class='tbl_sond']");
var degree = table.SelectSingleNode("//td[#class='renkMax']");
var date = table.SelectSingleNode("//td[#class='sond_zaman']");
}
else weather1.Text = "ece";
}
public void getWeatherInfo() {
string url = "http://www.mgm.gov.tr/tahmin/il-ve-ilceler.aspx?m=ISTANBUL";
WebClient webclient = new WebClient();
webclient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
Uri uri = new Uri(url);
webclient.DownloadStringAsync(uri);
}