Search Results

Search found 294 results on 12 pages for 'webclient'.

Page 5/12 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Windows Phone - failing to get a string from a website with login information

    - by jumantyn
    I am new to accessing web services with Windows Phone 7/8. I'm using a WebClient to get a string from a php-website. The site returns a JSON string but at the moment I'm just trying to put it into a TextBox as a normal string just to test if the connection works. The php-page requires an authentication and I think that's where my code is failing. Here's my code: WebClient client = new WebClient(); client.Credentials = new NetworkCredential("myUsername", "myPassword"); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); client.DownloadStringAsync(new Uri("https://www.mywebsite.com/ba/php/jsonstuff.php")); void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { try { string data = e.Result; this.jsonText.Text = data; } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); } } This returns first a WebException and then a TargetInvocationException. If I replace the Uri with for example "http://www.google.com/index.html" the jsonText TextBox gets filled with html text from Google (oddly enough, this also works even when the WebClient credentials are still set). So is the problem in the setting of the credentials? I couldn't find any good results when searching for guides on how to access php-pages with credentials, only without them. Then I found a short mention somewhere to use the WebClient.Credentials property. But should it work some other way? Update: here's what I can get out of the WebException (sorry for the bad formatting): System.Net.WebException: The remote server returned an error: NotFound. ---System.Net.WebException: The remote server returned an error: NotFound. at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) at System.Net.Browser.ClientHttpWebRequest.<c_DisplayClasse.b_d(Object sendState) at System.Net.Browser.AsyncHelper.<c_DisplayClass1.b_0(Object sendState) --- End of inner exception stack trace --- at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result) at System.Net.WebClient.DownloadBitsResponseCallback(IAsyncResult result)

    Read the article

  • c# reflection: How can I invoke a method with an out parameter ?

    - by ldp615
    I want expose WebClient.DownloadDataInternal method like below: [ComVisible(true)] public class MyWebClient : WebClient { private MethodInfo _DownloadDataInternal; public MyWebClient() { _DownloadDataInternal = typeof(WebClient).GetMethod("DownloadDataInternal", BindingFlags.NonPublic | BindingFlags.Instance); } public byte[] DownloadDataInternal(Uri address, out WebRequest request) { _DownloadDataInternal.Invoke(this, new object[] { address, out request }); } } WebClient.DownloadDataInternal has a out parameter, I don't know how to invoke it. Help!

    Read the article

  • C# 5 Async, Part 1: Simplifying Asynchrony – That for which we await

    - by Reed
    Today’s announcement at PDC of the future directions C# is taking excite me greatly.  The new Visual Studio Async CTP is amazing.  Asynchronous code – code which frustrates and demoralizes even the most advanced of developers, is taking a huge leap forward in terms of usability.  This is handled by building on the Task functionality in .NET 4, as well as the addition of two new keywords being added to the C# language: async and await. This core of the new asynchronous functionality is built upon three key features.  First is the Task functionality in .NET 4, and based on Task and Task<TResult>.  While Task was intended to be the primary means of asynchronous programming with .NET 4, the .NET Framework was still based mainly on the Asynchronous Pattern and the Event-based Asynchronous Pattern. The .NET Framework added functionality and guidance for wrapping existing APIs into a Task based API, but the framework itself didn’t really adopt Task or Task<TResult> in any meaningful way.  The CTP shows that, going forward, this is changing. One of the three key new features coming in C# is actually a .NET Framework feature.  Nearly every asynchronous API in the .NET Framework has been wrapped into a new, Task-based method calls.  In the CTP, this is done via as external assembly (AsyncCtpLibrary.dll) which uses Extension Methods to wrap the existing APIs.  However, going forward, this will be handled directly within the Framework.  This will have a unifying effect throughout the .NET Framework.  This is the first building block of the new features for asynchronous programming: Going forward, all asynchronous operations will work via a method that returns Task or Task<TResult> The second key feature is the new async contextual keyword being added to the language.  The async keyword is used to declare an asynchronous function, which is a method that either returns void, a Task, or a Task<T>. Inside the asynchronous function, there must be at least one await expression.  This is a new C# keyword (await) that is used to automatically take a series of statements and break it up to potentially use discontinuous evaluation.  This is done by using await on any expression that evaluates to a Task or Task<T>. For example, suppose we want to download a webpage as a string.  There is a new method added to WebClient: Task<string> WebClient.DownloadStringTaskAsync(Uri).  Since this returns a Task<string> we can use it within an asynchronous function.  Suppose, for example, that we wanted to do something similar to my asynchronous Task example – download a web page asynchronously and check to see if it supports XHTML 1.0, then report this into a TextBox.  This could be done like so: private async void button1_Click(object sender, RoutedEventArgs e) { string url = "http://reedcopsey.com"; string content = await new WebClient().DownloadStringTaskAsync(url); this.textBox1.Text = string.Format("Page {0} supports XHTML 1.0: {1}", url, content.Contains("XHTML 1.0")); } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; } Let’s walk through what’s happening here, step by step.  By adding the async contextual keyword to the method definition, we are able to use the await keyword on our WebClient.DownloadStringTaskAsync method call. When the user clicks this button, the new method (Task<string> WebClient.DownloadStringTaskAsync(string)) is called, which returns a Task<string>.  By adding the await keyword, the runtime will call this method that returns Task<string>, and execution will return to the caller at this point.  This means that our UI is not blocked while the webpage is downloaded.  Instead, the UI thread will “await” at this point, and let the WebClient do it’s thing asynchronously. When the WebClient finishes downloading the string, the user interface’s synchronization context will automatically be used to “pick up” where it left off, and the Task<string> returned from DownloadStringTaskAsync is automatically unwrapped and set into the content variable.  At this point, we can use that and set our text box content. There are a couple of key points here: Asynchronous functions are declared with the async keyword, and contain one or more await expressions In addition to the obvious benefits of shorter, simpler code – there are some subtle but tremendous benefits in this approach.  When the execution of this asynchronous function continues after the first await statement, the initial synchronization context is used to continue the execution of this function.  That means that we don’t have to explicitly marshal the call that sets textbox1.Text back to the UI thread – it’s handled automatically by the language and framework!  Exception handling around asynchronous method calls also just works. I’d recommend every C# developer take a look at the documentation on the new Asynchronous Programming for C# and Visual Basic page, download the Visual Studio Async CTP, and try it out.

    Read the article

  • unable to download a file from rtmp server

    - by user309815
    Hi Team I want to download an audio file from red5 server using rtmp server. string strUri; strUri = "rtmp://XXX/oflaDemo/" + Session["streamName"].ToString(); string strUploadto; strUploadto = Server.MapPath("") + "\Audio\" + "myaudio.flv"; WebClient webClient = new WebClient(); //webClient.DownloadFile("rtmp://begoniaprojects.com/oflaDemo/" + Session["streamName"].ToString(), Page.MapPath("") + "\Audio\" +"myaudio.flv"); webClient.DownloadFile(strUri, strUploadto); but i am getting uri prefix is not recognized message while downloading. please suggest me.

    Read the article

  • Error in simple Java application

    - by mrblah
    Just playing around with java trying to learn it etc. Here is my code so far, using HtmlUnit. package hsspider; import com.gargoylesoftware.htmlunit.WebClient; /** * @author */ public class Main { /** * @param args the command line arguments */ public static void main(String[] args) { System.out.println("starting "); Spider spider = new Spider(); spider.Test(); } } package hsspider; import com.gargoylesoftware.htmlunit.WebClient; import com.gargoylesoftware.htmlunit.html.HtmlPage; /** * @author */ public class Spider { public void Test() throws Exception { final WebClient webClient = new WebClient(); final HtmlPage page = webClient.getPage("http://www.google.com"); System.out.println(page.getTitleText()); } } I am using Netbeans. I can't seem to figure out what the problem is, why doesn't it compile? The error: C:\Users\mrblah\.netbeans\6.8\var\cache\executor-snippets\run.xml:45: Cancelled by user. BUILD FAILED (total time: 0 seconds) The row in the xml is: <translate-classpath classpath="${classpath}" targetProperty="classpath-translated" />

    Read the article

  • Definitive list of protocols supported by the WebClient and WebRequest classes.

    - by the-locster
    The docs state: From WebRequest.Create Method The .NET Framework includes support for the http://, https://, and file:// URI schemes. Custom WebRequest descendants to handle other requests are registered with the RegisterPrefix method. However I've also been using this class to get files via ftp (not listed in the docs). Is there a definitive list of supported protocols documented anywhere? UPDATE: To clarify. Yes additional protocols can be plugged-in, but what is the standard/baseline set of protocols supported in the class framework assuming I haven't registered any others. e.g. sftp, tftp?

    Read the article

  • Is it possible in .NET to set the local endpoint (IP address) when using webclient to consume a web

    - by Tom
    I'm wondering if it is possible using .NET to call a remote web service and in effect specify which IP the call is made on. I'm consuming a service that limits the number of calls I can make based on IP. The service costs in the 20k range after the free limit is used up. I'm very close to enough calls but not quite there using the free service. My server has 3 IP so I could in effect triple the number of calls I could make to the remote service by changing the IP.

    Read the article

  • C# Image Download

    - by Nouman Zakir
    A C# class that makes it easier to download images from the web. Use the following code in your program to download image files such as JPG, GIF, PNG, etc from the internet using WebClient class. using System;using System.Drawing;using System.Drawing.Imaging;using System.IO;using System.Net;public class DownloadImage { private string imageUrl; private Bitmap bitmap; public DownloadImage(string imageUrl) { this.imageUrl = imageUrl; } public void Download() { try { WebClient client = new WebClient(); Stream stream = client.OpenRead(imageUrl); bitmap = new Bitmap(stream); stream.Flush(); stream.Close(); } catch (Exception e) { Console.WriteLine(e.Message); } } public Bitmap GetImage() { return bitmap; } public void SaveImage(string filename, ImageFormat format) { if (bitmap != null) { bitmap.Save(filename, format); } }}

    Read the article

  • submit html form programmatically in android

    - by Maneesh
    I want to submit form programatically in android. I don't want any user interaction with web browser. User will provide inputs in EditField and then inputs will be submitted thru httppost method via HTTPwebmethod. But I didn't get any success in the same. Please advise. I have used HTMLUnit in java but its not working android. final WebClient webClient = new WebClient(); final HtmlPage page1 = webClient.getPage("http://www.mail.example.com"); final HtmlForm form = page1.getHtmlElementById("loginform"); final HtmlSubmitInput button = form.getInputByName("btrn"); final HtmlTextInput textField1 = form.getElementById("user"); final HtmlPasswordInput textField2 = form.getElementById("password");textField1.setValueAttribute("user.name"); textField2.setValueAttribute("pass.word"); final HtmlPage page2 = button.click();

    Read the article

  • POST variables to web server?

    - by OverTheRainbow
    Hello I've been trying several things from Google to POST data to a web server, but none of them work: I'm still stuck at how to convert the variables into the request, considering that the second variable is an SQL query so it has spaces. Does someone know the correct way to use a WebClient to POST data? I'd rather use WebClient because it requires less code than HttpWebRequest/HttpWebResponse. Here's what I tried so far: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim wc = New WebClient() 'convert data wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim postData = String.Format("db={0}&query={1}", _ HttpUtility.UrlEncode("books.sqlite"), _ HttpUtility.UrlEncode("SELECT id,title FROM boooks")) 'Dim bytArguments As Byte() = Encoding.ASCII.GetBytes("db=books.sqlite|query=SELECT * FROM books") 'POST query Dim bytRetData As Byte() = wc.UploadData("http://localhost:9999/get", "POST", postData) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub Dim client = New WebClient() Dim nv As New Collection nv.Add("db", "books.sqlite") nv.Add("query", "SELECT id,title FROM books") Dim address As New Uri("http://localhost:9999/get") 'Dim bytRetData As Byte() = client.UploadValues(address, "POST", nv) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub 'Dim wc As New WebClient() 'convert data wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim bytArguments As Byte() = Encoding.ASCII.GetBytes("db=books.sqlite|query=SELECT * FROM books") 'POST query 'Dim bytRetData As Byte() = wc.UploadData("http://localhost:9999/get", "POST", bytArguments) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub End Sub Thank you.

    Read the article

  • C# Thread issues

    - by Mike
    What I have going on is a listview being dynamically created from a previous button click. Then ti starts a background worker in which should clear out the listview and populate the iistview with new information every 30 seconds. I continously get: Cross-thread operation not valid: Control 'listView2' accessed from a thread other than the thread it was created on. private void watcherprocess1Updatelist() { listView2.Items.Clear(); string betaFilePath1 = @"C:\Alpha\watch1\watch1config.txt"; using (FileStream fs = new FileStream(betaFilePath1, FileMode.Open)) using (StreamReader rdr = new StreamReader((fs))) { while (!rdr.EndOfStream) { string[] betaFileLine = rdr.ReadLine().Split(','); using (WebClient webClient = new WebClient()) { string urlstatelevel = betaFileLine[0]; string html = webClient.DownloadString(urlstatelevel); File.AppendAllText(@"C:\Alpha\watch1\specificconfig.txt", html); } } }

    Read the article

  • P0ST variables to web server?

    - by OverTheRainbow
    Hello I've been trying several things from Google to POST data to a web server, but none of them work: I'm still stuck at how to convert the variables into the request, considering that the second variable is an SQL query so it has spaces. Does someone know the correct way to use a WebClient to POST data? I'd rather use WebClient because it requires less code than HttpWebRequest/HttpWebResponse. Here's what I tried so far: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim wc = New WebClient() 'convert data wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim postData = String.Format("db={0}&query={1}", _ HttpUtility.UrlEncode("books.sqlite"), _ HttpUtility.UrlEncode("SELECT id,title FROM boooks")) 'Dim bytArguments As Byte() = Encoding.ASCII.GetBytes("db=books.sqlite|query=SELECT * FROM books") 'POST query Dim bytRetData As Byte() = wc.UploadData("http://localhost:9999/get", "POST", postData) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub Dim client = New WebClient() Dim nv As New Collection nv.Add("db", "books.sqlite") nv.Add("query", "SELECT id,title FROM books") Dim address As New Uri("http://localhost:9999/get") 'Dim bytRetData As Byte() = client.UploadValues(address, "POST", nv) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub 'Dim wc As New WebClient() 'convert data wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded") Dim bytArguments As Byte() = Encoding.ASCII.GetBytes("db=books.sqlite|query=SELECT * FROM books") 'POST query 'Dim bytRetData As Byte() = wc.UploadData("http://localhost:9999/get", "POST", bytArguments) RichTextBox1.Text = Encoding.ASCII.GetString(bytRetData) Exit Sub End Sub Thank you.

    Read the article

  • Change function into dependencyproperty

    - by Jaya Willianto
    Hi everyone.. I am new to XAML and WPF and I am learning about DependencyProperty and Path. For example, I have a function like this public byte[] DownloadPicture() { WebClient webClient = new WebClient(); byte[] data; data = webClient.DownloadData("https://graph.facebook.com/4/picture&type=large"); return data; } and I have dependencyproperty like this public static DependencyProperty DownloadPicProperty = DependencyProperty.Register("DownloadPic", typeof(byte), typeof(ImageControl), new PropertyMetadata(false)); How can I connect the DependencyProperty with the DownloadPicture function I wrote? Any suggestions? What should I write in the CLR wrapper?

    Read the article

  • Is there a better way to consume an ASP.NET Web API call in an MVC controller?

    - by davidisawesome
    In a new project I am creating for my work I am creating a fairly large ASP.NET Web API. The api will be in a separate visual studio solution that also contains all of my business logic and database interactions, Model classes as well. In the test application I am creating (which is asp.net mvc4), I want to be able to hit an api url I defined from the control and cast the return JSON to a Model class. The reason behind this is that I want to take advantage of strongly typing my views to a Model. This is all still in a proof of concept stage, so I have not done any performance testing on it, but I am curious if what I am doing is a good practice, or if I am crazy for even going down this route. Here is the code on the client controller: public class HomeController : Controller { protected string dashboardUrlBase = "http://localhost/webapi/api/StudentDashboard/"; public ActionResult Index() //This view is strongly typed against User { //testing against Joe Bob string adSAMName = "jBob"; WebClient client = new WebClient(); string url = dashboardUrlBase + "GetUserRecord?userName=" + adSAMName; //'User' is a Model class that I have defined. User result = JsonConvert.DeserializeObject<User>(client.DownloadString(url)); return View(result); } . . . } If I choose to go this route another thing to note is I am loading several partial views in this page (as I will also do in subsequent pages). The partial views are loaded via an $.ajax call that hits this controller and does basically the same thing as the code above: Instantiate a new WebClient Define the Url to hit Deserialize the result and cast it to a Model Class. So it is possible (and likely) I could be performing the same actions 4-5 times for a single page. Is there a better method to do this that will: Let me keep strongly typed views. Do my work on the server rather than on the client (this is just a preference since I can write C# faster than I can write javascript).

    Read the article

  • C# Finalize/Dispose pattern

    - by robUK
    Hello, C# 2008 I have been working on this for a while now. And I am still confused about some issues. My questions below 1) I know that you only need a finalizer if you are disposing of unmanaged resources. However, if you are using managed resources that make calls to unmanaged resources. Would you still need to implement a finalizer? 2) However, if you develop a class that doesn't use any unmanged resources directly or indirectly and you implement the IDisposable so that clients of your class can use the 'using statement'. Would it be acceptable to implement the IDisposable just so that clients of your class can use the using statement? using(myClass objClass = new myClass()) { // Do stuff here } 3) I have developed this simple code below to demostrate the Finalize/dispose pattern: public class NoGateway : IDisposable { private WebClient wc = null; public NoGateway() { wc = new WebClient(); wc.DownloadStringCompleted += wc_DownloadStringCompleted; } // Start the Async call to find if NoGateway is true or false public void NoGatewayStatus() { // Start the Async's download // Do other work here wc.DownloadStringAsync(new Uri(www.xxxx.xxx)); } private void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { // Do work here } // Dispose of the NoGateway object public void Dispose() { wc.DownloadStringCompleted -= wc_DownloadStringCompleted; wc.Dispose(); GC.SuppressFinalize(this); } } Question about the source code: 1) Here I have not added the finalizer. And normally the finalizer will be called by the GC, and the finalizer will call the Dispose. As I don't have the finalizer, when do I call the Dispose method? Is it the client of the class that has to call it? So my class in the example is called NoGateway and the client could use and dispose of the class like this: Would the Dispose method be automatically called when execution reaches the end of the using block? using(NoGateway objNoGateway = new NoGateway()) { // Do stuff here } Or does the client have to manually call the dispose method i.e.? NoGateway objNoGateway = new NoGateway(); // Do stuff with object objNoGateway.Dispose(); // finished with it Many thanks for helping with all these questions, 2) I am using the webclient class in my 'NoGateway' class. Because the webclient implements the IDisposable interface. Does this mean that the webclient indirectly uses unmanaged resources? Is there any hard and fast rule to follow about this. How do I know that a class uses unmanaged resources?

    Read the article

  • Loading xap file on demand

    - by synergetic
    I have Silverlight application called MyApp. During startup MyApp loads MyApp.Main.xap module using the following code: WebClient wc = new WebClient(); wc.OpenReadCompleted += new OpenReadCompletedEventHandler(onMainModuleLoaded); Uri uri = new Uri("MyApp.Main.xap", UriKind.Relative); wc.OpenReadAsync(uri); It works. Within MyApp.Main I would like to load another xap file MyApp.Billing.xap, so I wrote like the same as above WebClient wc = new WebClient(); wc.OpenReadCompleted += new OpenReadCompletedEventHandler(onBillingModuleLoaded); Uri uri = new Uri("MyApp.Billing.xap", UriKind.Relative); wc.OpenReadAsync(uri); but it throws an error saying the file not found. MyApp.Billing.xap file is inside ClientBin folder and I can download it directly via absolute path in a browser. If I try to download MyApp.Billing.xap not from inside MyApp.Main, but from inside MyApp (instead of MyAPp.Main.xap) it also works fine. What might be the problem?

    Read the article

  • Getting web page after calling DownloadStringAsync()?

    - by OverTheRainbow
    Hello I don't know enough about VB.Net yet to use the richer HttpWebRequest class, so I figured I'd use the simpler WebClient class to download web pages asynchronously (to avoid freezing the UI). However, how can the asynchronous event handler actually return the web page to the calling routine? Imports System.Net Public Class Form1 Private Shared Sub DownloadStringCallback2(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs) If e.Cancelled = False AndAlso e.Error Is Nothing Then Dim textString As String = CStr(e.Result) 'HERE : How to return textString to the calling routine? End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim client As WebClient = New WebClient() AddHandler client.DownloadStringCompleted, AddressOf DownloadStringCallback2 Dim uri As Uri = New Uri("http://www.google.com") client.DownloadStringAsync(uri) 'HERE : how to get web page back from callback function? End Sub End Class Thank you. Edit: I added a global, shared variable and a While/DoEvents/EndWhile, but there's got to be a cleaner way to do this :-/ Public Class Form1 Shared page As String Public Shared Sub AlertStringDownloaded(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs) ' If the string request went as planned and wasn't cancelled: If e.Cancelled = False AndAlso e.Error Is Nothing Then page = CStr(e.Result) End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim wc As New WebClient AddHandler wc.DownloadStringCompleted, AddressOf AlertStringDownloaded page = Nothing wc.DownloadStringAsync(New Uri("http://www.google.com")) 'Better way to wait until page has been filled? While page Is Nothing Application.DoEvents() End While RichTextBox1.Text = page End Sub End Class

    Read the article

  • How can a silverlight app download and play an mp3 file from a URL?

    - by Edward Tanguay
    I have a small Silverlight app which downloads all of the images and text it needs from a URL, like this: if (dataItem.Kind == DataItemKind.BitmapImage) { WebClient webClientBitmapImageLoader = new WebClient(); webClientBitmapImageLoader.OpenReadCompleted += new OpenReadCompletedEventHandler(webClientBitmapImageLoader_OpenReadCompleted); webClientBitmapImageLoader.OpenReadAsync(new Uri(dataItem.SourceUri, UriKind.Absolute), dataItem); } else if (dataItem.Kind == DataItemKind.TextFile) { WebClient webClientTextFileLoader = new WebClient(); webClientTextFileLoader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClientTextFileLoader_DownloadStringCompleted); webClientTextFileLoader.DownloadStringAsync(new Uri(dataItem.SourceUri, UriKind.Absolute), dataItem); } and: void webClientBitmapImageLoader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { BitmapImage bitmapImage = new BitmapImage(); bitmapImage.SetSource(e.Result); DataItem dataItem = e.UserState as DataItem; CompleteItemLoadedProcess(dataItem, bitmapImage); } void webClientTextFileLoader_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { DataItem dataItem = e.UserState as DataItem; string textFileContent = e.Result.ForceWindowLineBreaks(); CompleteItemLoadedProcess(dataItem, textFileContent); } Each of the images and text files are then put in a dictionary so that the application has access to them at any time. This works well. Now I want to do the same with mp3 files, but all information I find on the web about playing mp3 files in Silverlight shows how to embed them in the .xap file, which I don't want to do since I wouldn't be able to download them dynamically as I do above. How can I download and play mp3 files in Silverlight like I download and show images and text?

    Read the article

  • Is this correct for disposing an object using IDisposable

    - by robUK
    I have a class that implements the IDisposable interface. I am using a webclient to download some data using the AsyncDownloadString. I am wondering have I correctly declared my event handlers in the constructor and within the using statement of the web client? And is this correct way to remove the event handlers in the Dispose method? Overrule is this the correct way to use the IDisposable interface? public class Balance : IDisposable { //Constructor WebClient wc; public Balance() { using (wc = new WebClient()) { //Create event handler for the progress changed and download completed events wc.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged); wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); } } ~Balance() { this.Dispose(false); } //Get the current balance for the user that is logged in. //If the balance returned from the server is NULL display error to the user. //Null could occur if the DB has been stopped or the server is down. public void GetBalance(string sipUsername) { //Remove the underscore ( _ ) from the username, as this is not needed to get the balance. sipUsername = sipUsername.Remove(0, 1); string strURL = string.Format("https://www.xxxxxxx.com", sipUsername); //Download only when the webclient is not busy. if (!wc.IsBusy) { // Download the current balance. wc.DownloadStringAsync(new Uri(strURL)); } else { Console.Write("Busy please try again"); } } //return and display the balance after the download has fully completed void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { //Pass the result to the event handler } //Dispose of the balance object public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } //Remove the event handlers private bool isDisposed = false; private void Dispose(bool disposing) { if (!this.isDisposed) { if (disposing) { wc.DownloadProgressChanged -= new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged); wc.DownloadStringCompleted -= new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); wc.Dispose(); } isDisposed = true; } } }

    Read the article

  • get html content of a page with Silverlight

    - by Yustme
    Hi, I'm trying to get the html content of a page using silverlight. Webresponse and request classes don't work in silverlight. I did some googling and I found something. This is what i tried: public partial class MainPage : UserControl { string result; WebClient client; public MainPage() { InitializeComponent(); this.result = string.Empty; this.client = new WebClient(); this.client.DownloadStringCompleted += ClientDownloadStringCompleted; } private void btn1_Click(object sender, RoutedEventArgs e) { string url = "http://www.nu.nl/feeds/rss/algemeen.rss"; this.client.DownloadStringAsync(new Uri(url, UriKind.Absolute)); if (this.result != string.Empty && this.result != null) { this.txbSummery.Text = this.result; } } private void ClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { this.result = e.Result; //handle the response. } } It gives me a runtime error after pressing the button: Microsoft JScript runtime error: Unhandled Error in Silverlight Application An exception occurred during the operation, making the result invalid. Check InnerException for exception details. at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary() at System.Net.DownloadStringCompletedEventArgs.get_Result() at JWTG.MainPage.ClientDownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e) at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e) at System.Net.WebClient.DownloadStringOperationCompleted(Object arg) I've tried numerous things but all failed. What am i missing? Or does anyone know how i could achieve this in a different way? Thanks in advance!

    Read the article

  • How to use a loop to download HTML with paging?

    - by Nai
    I want to loop through this URL and download the HTML. https://www.googleapis.com/customsearch/v1?key=AIzaSyAAoPQprb6aAV-AfuVjoCdErKTiJHn-4uI&cx=017576662512468239146:omuauf_lfve&q=" + searchTermFormat + "&num=10" +"&start=" + i start and num controls the paging of the URL. So if &start=2, and &num=10, it will scrape 10 results from page 2. Given that Google has a max limit of num = 10, how can I write a loop that loops through the HTML and scrape the results for the first 10 pages? This is what I have so far which just scrapes the first page. //input search term Console.WriteLine("What is your search query?:"); string searchTerm = Console.ReadLine(); //concantenate the strings using + symbol to make it URL friendly for google string searchTermFormat = searchTerm.Replace(" ", "+"); //create a new instance of Webclient and use DownloadString method from the Webclient class to extract download html WebClient client = new WebClient(); int i = 1; string Json = client.DownloadString("https://www.googleapis.com/customsearch/v1?key=AIzaSyAAoPQprb6aAV-AfuVjoCdErKTiJHn-4uI&cx=017576662512468239146:omuauf_lfve&q=" + searchTermFormat + "&num=10" + "&start=" + i); //create a new instance of JavaScriptSerializer and deserialise the desired content JavaScriptSerializer js = new JavaScriptSerializer(); GoogleSearchResults results = js.Deserialize<GoogleSearchResults>(Json); //output results to console Console.WriteLine(js.Serialize(results)); Console.ReadLine();

    Read the article

  • XPath _relative_ to given element in HTMLUnit/Groovy?

    - by Misha Koshelev
    Dear All: I would like to evaluate an XPath expression relative to a given element. I have been reading here: http://www.w3schools.com/xpath/default.asp And it seems like one of the syntaxes below should work (esp no leading slash or descendant:) However, none seem to work in HTMLUnit. Any help much appreciated (oh this is a groovy script btw). Thank you! http://htmlunit.sourceforge.net/ http://groovy.codehaus.org/ Misha #!/usr/bin/env groovy import com.gargoylesoftware.htmlunit.WebClient def html=""" <html><head><title>Test</title></head> <body> <div class='levelone'> <div class='leveltwo'> <div class='levelthree' /> </div> <div class='leveltwo'> <div class='levelthree' /> <div class='levelthree' /> </div> </div> </body> </html> """ def f=new File('/tmp/test.html') if (f.exists()) { f.delete() } def fos=new FileOutputStream(f) fos<<html def webClient=new WebClient() def page=webClient.getPage('file:///tmp/test.html') def element=page.getByXPath("//div[@class='levelone']") assert element.size()==1 element=page.getByXPath("div[@class='levelone']") assert element.size()==0 element=page.getByXPath("/div[@class='levelone']") assert element.size()==0 element=page.getByXPath("descendant:div[@class='levelone']") // this gives namespace error assert element.size()==0 Thank you!!!

    Read the article

  • Strange HtmlUnit behavior (bug?)

    - by roddik
    Hello. Take a look at this: WebClient client = new WebClient(); WebRequestSettings wrs = new WebRequestSettings(new URL("http://stackoverflow.com/ping/?what-the-duck?"), HttpMethod.HEAD); client.getPage(wrs); Running this code results in throwing FileNotFoundException, because HTTP Status code on the page is 404 and getting the same page again with the GET method, with User-Agent set to Java-.... Why does it GET the page (it doesn't happen with "normal" status codes)? Is this a bug? Thanks Here is the entire server response: HTTP/1.1 404 Not Found Cache-Control: private Content-Length: 7502 Content-Type: text/html; charset=utf-8 Server: Microsoft-IIS/7.5 Date: Thu, 11 Feb 2010 14:12:11 GMT Where does it tell client to GET something? And how can I force WebClient to ignore it? Here's a screenshot of HTTPDebugger: The problem here is I don't understand why the second request is being sent and why is it sent with different useragent.

    Read the article

  • The underlying connection was closed: An unexpected error occurred on a receive

    - by Dave
    Using a console app which runs as a scheduled task on Azure, to all a long(ish) running webpage on Azure. Problem after a few minutes: The underlying connection was closed: An unexpected error occurred on a receive //// used as WebClient doesn't support timeout public class ExtendedWebClient : WebClient { public int Timeout { get; set; } protected override WebRequest GetWebRequest(Uri address) { HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(address); if (request != null) request.Timeout = Timeout; request.KeepAlive = false; request.ProtocolVersion = HttpVersion.Version10; return request; } public ExtendedWebClient() { Timeout = 1000000; // in ms.. the standard is 100,000 } } class Program { static void Main(string[] args) { var taskUrl = "http://www.secret.com/secret.aspx"; // create a webclient and issue an HTTP get to our url using (ExtendedWebClient httpRequest = new ExtendedWebClient()) { var output = httpRequest.DownloadString(taskUrl); } } }

    Read the article

  • Security Exception while running sites using subdomain?

    - by lmenaria
    I have 3 sites : media.lmenaria.com - Hosting Images webservice.lmenaria.com - Sending images url from database. www.lmenaria.com - Host Silverlight application and display images. When I run page "http://www.lmenaria.com/silverlight.aspx". I am getting below exception. So what shpould I do ? System.Security.SecurityException: Security error. at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) at System.Net.Browser.BrowserHttpWebRequest.<c_DisplayClass5.b_4(Object sendState) at System.Net.Browser.AsyncHelper.<c_DisplayClass2.b_0(Object sendState) at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.Net.WebClient.GetWebResponse(WebRequest request, IAsyncResult result) at System.Net.WebClient.OpenReadAsyncCallback(IAsyncResult result) I think, my all sites runing at same domain, so I don't need crossdomain xmls. Please let me know how Can I fix it. I have tried to put corssdoamin xml media.lmenaria.com,webservice.lmenaria.com both, and working fine, but only at www.lmenaria.com not working. We are downloading images using WebClient. Thanks in advance, Laxmilal Menaria

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >