Search Results

Search found 121 results on 5 pages for 'webexception'.

Page 1/5 | 1 2 3 4 5  | Next Page >

  • Handling two WebException's properly

    - by baron
    Hi Everyone, I am trying to handle two different WebException's properly. Basically they are handled after calling WebClient.DownloadFile(string address, string fileName) AFAIK, so far there are two I have to handle, both WebException's: The remote name could not be resolved (i.e. No network connectivity to access server to download file) (404) File not nound (i.e. the file doesn't exist on the server) There may be more but this is what I've found most important so far. So how should I handle this properly, as they are both WebException's but I want to handle each case above differently. This is what I have so far: try { using (var client = new WebClient()) { client.DownloadFile("..."); } } catch(InvalidOperationException ioEx) { if (ioEx is WebException) { if (ioEx.Message.Contains("404") { //handle 404 } if (ioEx.Message.Contains("remote name could not") { //handle file doesn't exist } } } As you can see I am checking the message to see what type of WebException it is. I would assume there is a better or a more precise way to do this? Thanks

    Read the article

  • 503 (Server Unavailable) WebException when loading local XHTML file in Visual C# 2008

    - by kcoppock
    Hello! So I'm currently working on an ePub reader application, and I've been reading through a bunch of regular XML files just fine with System.Xml and XmlDocument: XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(Path.Combine(Directory.GetCurrentDirectory(), "META-INF/container.xml")); XmlNodeList xnl = xmldoc.GetElementsByTagName("rootfile"); However, now I'm trying to open the XHTML files that contain the actual book text, and they're XHTML files. Now I don't really know the difference between the two, but I'm getting the following error with this code (in the same document, using the same XmlDocument and XmlNodeList variable) xmldoc.Load(Path.Combine(Directory.GetCurrentDirectory(), "OEBPS/part1.xhtml")); "WebException was unhandled: The remote server returned an error: (503) Server Unavailable" It's a local document, so I'm not understanding why it's giving this error? Any help would be greatly appreciated. :) I've got the full source code here if it helps: http://drop.io/epubtest (I know the ePubConstructor.ParseDocument() method is horribly messy, I'm just trying to get it working at the moment before I split it into classes)

    Read the article

  • 503 (Server Unavailable) WebException when loading local XHTML file

    - by kcoppock
    Hello! So I'm currently working on an ePub reader application, and I've been reading through a bunch of regular XML files just fine with System.Xml and XmlDocument: XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(Path.Combine(Directory.GetCurrentDirectory(), "META-INF/container.xml")); XmlNodeList xnl = xmldoc.GetElementsByTagName("rootfile"); However, now I'm trying to open the XHTML files that contain the actual book text, and they're XHTML files. Now I don't really know the difference between the two, but I'm getting the following error with this code (in the same document, using the same XmlDocument and XmlNodeList variable) xmldoc.Load(Path.Combine(Directory.GetCurrentDirectory(), "OEBPS/part1.xhtml")); "WebException was unhandled: The remote server returned an error: (503) Server Unavailable" It's a local document, so I'm not understanding why it's giving this error? Any help would be greatly appreciated. :) I've got the full source code here if it helps: http://drop.io/epubtest (I know the ePubConstructor.ParseDocument() method is horribly messy, I'm just trying to get it working at the moment before I split it into classes)

    Read the article

  • WinMo > ASMX WebException - how to get details?

    - by eidylon
    Okay, we've got an application which consists of a website hosting several ASMX webservices, and a handheld application running on WinMo 6.1 which calls the webservices. Been developing in the office, everything works perfect. Now we've gone to install it at the client's and we got all the servers set up and the handhelds installed. However the handhelds are now no longer able to connect to the webservice. I added in extra code in my error handler to specifically trap WebException exceptions and handle them differently in the logging to put out extra information (.Status and .Response). I am getting out the status, which is returning a [7], or ProtocolError. However when I try to read out the ResponseStream (using WebException.Response.GetResponseStream), it is returning a stream with CanRead set to False, and I thus am unable to get any further details of what is going wrong. So I guess there are two things I am asking for help with... a) Any help with trying to get more information out of the WebException? b) What could be causing a ProtocolError exception? Things get extra complicated by the fact that the client has a full-blown log-in-enabled proxy setup going on-site. This was stopping all access to the website initially, even from a browser. So we entered in the login details in the network connection for HTTP on the WinMo device. Now it can get to websites fine. In fact, I can even pull up the webservice fine and call the methods from the browser (PocketIE). So I know the device is able to see the webservices okay via HTTP. But when trying to call them from the .NET app, it throws ProtocolError [7]. Here is my code which is logging the exception and failing to read out the Response from the WebException. Public Sub LogEx(ByVal ex As Exception) Try Dim fn As String = Path.Combine(ini.CorePath, "error.log") Dim t = File.AppendText(fn) t.AutoFlush = True t.WriteLine(<s>===== <%= Format(GetDateTime(), "MM/dd/yyyy HH:mm:ss") %> =====<%= vbCrLf %><%= ex.Message %></s>.Value) t.WriteLine() t.WriteLine(ex.ToString) t.WriteLine() If TypeOf ex Is WebException Then With CType(ex, WebException) t.WriteLine("STATUS: " & .Status.ToString & " (" & Val(.Status) & ")") t.WriteLine("RESPONSE:" & vbCrLf & StreamToString(.Response.GetResponseStream())) End With End If t.WriteLine("=".Repeat(50)) t.WriteLine() t.Close() Catch ix As Exception : Alert(ix) : End Try End Sub Private Function StreamToString(ByVal s As IO.Stream) As String If s Is Nothing Then Return "No response found." // THIS IS THE CASE BEING EXECUTED If Not s.CanRead Then Return "Unreadable response found." Dim rv As String = String.Empty, bytes As Long, buffer(4096) As Byte Using mem As New MemoryStream() Do While True bytes = s.Read(buffer, 0, buffer.Length) mem.Write(buffer, 0, bytes) If bytes = 0 Then Exit Do Loop mem.Position = 0 ReDim buffer(mem.Length) mem.Read(buffer, 0, mem.Length) mem.Seek(0, SeekOrigin.Begin) rv = New StreamReader(mem).ReadToEnd() mem.Close() End Using Return rv.NullOf("Empty response found.") End Function Thanks in advance!

    Read the article

  • Asp.net HttpWebResponse - how can I not depend on WebException for flow control?

    - by Campos
    I need to check whether the request will return a 500 Server Internal Error or not (so getting the error is expected). I'm doing this: HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Method = "GET"; HttpWebResponse response = request.GetResponse() as HttpWebResponse; if (response.StatusCode == HttpStatusCode.OK) return true; else return false; But when I get the 500 Internal Server Error, a WebException is thrown, and I don't want to depend on it to control the application flow - how can this be done?

    Read the article

  • 'WebException' error on back button even when calling 'void' async method

    - by BlazingFrog
    I have a windows phone app that allows the user to interact with it. Each interaction will always result in an async WCF call. In addition to that, some interactions will result in opening the browser, maps, email, etc... The problem is that, when hitting the back button, I sometime get the following error "An error (WebException) occurred while transmitting data over the HTTP channel." with the following stack trace: at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason) at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result) at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.OnGetResponse(IAsyncResult result) at System.Net.Browser.ClientHttpWebRequest.<>c__DisplayClassa.<InvokeGetResponseCallback>b__8(Object state2) at System.Threading.ThreadPool.WorkItem.WaitCallback_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadPool.WorkItem.doWork(Object o) at System.Threading.Timer.ring() My understanding is that it's happening because my app opened another app (browser, maps, etc) before it had the time to execute the EndMyAsyncMethod(System.IAsyncResult result). Fair enough... What's really annoying is that it seems it should get fixed by cloning the server-side method, only making it void with the following operation contract [OperationContract(IsOneWay = true)] but I'm still getting the error. What's worse is that the exception is thrown in a system-generated part of the code and, thus, cannot be manually caught causing the app to just crash. I simply don't understand the need to execute an Endxxx method when it's explicitely marked as OneWay and void. EDIT I did find a similar issue here. It does seem that it is related to the message getting to the service (not the client callback). My next question is: if I'm now calling a method marked AsyncPattern and OneWay, what exactly should I be waiting for on the client to be sure the message was transmitted successfully? This is new service definition: [OperationContract(IsOneWay = true, AsyncPattern = true)] IAsyncResult BeginCacheQueryWithoutCallback(string param1, QueryInfoDataContract queryInfo, AsyncCallback cb, Object s); void EndCacheQueryWithoutCallback(IAsyncResult r); And the implementation: public IAsyncResult BeginCacheQueryWithoutCallback(string param1, QueryInfoDataContract queryInfo, AsyncCallback cb, Object s) { // do some stuff return new CompletedAsyncResult<string>(""); } public void EndCacheQueryWithoutCallback(IAsyncResult r) { }

    Read the article

  • HttpWebRequest.GetResponse() - what specific status codes cause an exception to be thrown?

    - by H. Morrow
    I've hunted around for some definitive documentation on this but haven't had much luck finding any. Basically - the question is - for which HTTP Status codes coming back from the server will HttpWebRequest.GetResponse() generate a WebException after doing something like say, a POST? Specifically - will it generate a WebException for anything other than status 200 OK? Or will it only generate a WebException for say, 400, 404, and 500 (for the sake of argument). I want to know since, the server I'm communicating with defines anything other than HTTP 200 OK coming back as an error condition - and the key is, can I rely on a WebException being generated for anything other than 200? (I've currently written my code so that it'll actually check the return status code everytime to ensure it's 200 OK and if it's not, take appropriate action - but it's alot of duplication between that, and the catch block for a WebException, and I'm hoping to clean it up...) Any relevant links to documentation would be most appreciated. Thanks!

    Read the article

  • System.Net.WebException: Unable to connect to the remote server

    - by Anilkumar
    System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.GetRequestStream() at OmnexCRMFileDownloader.OmnCRMTemplateDataReader.GetProposalData(String lurl) I'm getting the above error when I try to post to a .aspx page.I think it is not Posting to the page I specified. HttpWebRequest.GetRequestStream() is not getting as expected. Pls help.

    Read the article

  • Ftp throws WebException only in .NET 4.0

    - by Trakhan
    I have following c# code. It runs just fine when compiled against .NET framework 3.5 or 2.0 (I did not test it against 3.0, but it will most likely work too). The problem is, that it fails when built against .NET framework 4.0. FtpWebRequest Ftp = (FtpWebRequest)FtpWebRequest.Create(Url_ + '/' + e.Name); Ftp.Method = WebRequestMethods.Ftp.UploadFile; Ftp.Credentials = new NetworkCredential(Login_, Password_); Ftp.UseBinary = true; Ftp.KeepAlive = false; Ftp.UsePassive = true; Stream S = Ftp.GetRequestStream(); byte[] Content = null; bool Continue = false; do { try { Continue = false; Content = File.ReadAllBytes(e.FullPath); } catch (Exception) { Continue = true; System.Threading.Thread.Sleep(500); } } while (Continue); S.Write(Content, 0, Content.Length); S.Close(); FtpWebResponse Resp = (FtpWebResponse)Ftp.GetResponse(); if (Resp.StatusCode != FtpStatusCode.CommandOK) Console.WriteLine(Resp.StatusDescription); The problem is in call Stream S = Ftp.GetRequestStream();, which throws an en instance of WebException with message “The remote server returned an error: (500) Syntax error, command unrecognized”. Does anybody know why it is so? PS. I communicate virtual ftp server in ECM Alfresco.

    Read the article

  • ASP.net WebRequest Exception "System.Net.WebException: The server committed a protocol violation"

    - by Billy
    I call WebRequest.GetResponse() and encounter the error: The server committed a protocol violation. Section=ResponseStatusLine I google this error and add the following lines in web.config: <configuration> <system.net> <settings> <httpWebRequest useUnsafeHeaderParsing="true" /> </settings> </system.net> </configuration> However, it doesn't work. Here is my ASP.net code: HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "HEAD"; using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { ...... }

    Read the article

  • Http 404: Not Found (WebException)

    - by Rajeev
    Hi, I am using a console app/class library to invoke a asp.net web service. The class library queries the database and sends the data to the web service. What I notice is that when the amount of data is huge (with 20 columns and 18K records), i get a HTTP 404: Not Found exception from the web service. I have tried increasing the maxReqeustLength and executionTimeout properties in the httpRuntime tag in the web.config of the web service. Is there any thing that I can do to overcome this? Thanks, Rajeev

    Read the article

  • What exception is thrown if a web service i'm using Times Out?

    - by BT
    I'm calling a .NET web service within my existing .NET webservice, i would like to know what exception is thrown from the web method if timeout happens, i have set the web service timeout to some lower value then the default 90 sec. and want to add business logic if time out happens. Is this the exception i should be looking at? System.Net.WebException

    Read the article

  • WCF method called twice

    - by Saurabh Lalwani
    Hi, I have a web service which is returning data to the desktop application. The problem I am having is, when the web service returns small volume of data everything works fine but when the volume of data is large it throws the following exception: System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. And when I am debugging the web service, I see that this particular method is called twice. It executes the return statement 1st time nothing happens, but when it does execute it for the second time the above mentioned exception is thrown in the desktop app. I found similar posts before on stackoverflow but they did not solve my problem. Can anybody please tell me what's going on in here? Thanks!

    Read the article

  • WCF large message exception

    - by Saurabh Lalwani
    Hi, I have a web service which is returning data to the desktop application. The problem I am having is, when the web service returns small volume of data everything works fine but when the volume of data is large it throws the following exception: System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a receive. Can it be because it is taking a good 4-5 seconds to fetch all the records from the database and the session times out or something? Also, when I am debugging the web service, I see that this particular method is called twice and it is also returning the correct value both times, but for some reason the desktop application seems to be throwing the aforementioned exception. I found similar posts before on stackoverflow but they did not solve my problem. Can anybody please tell me what's going on in here? Thanks!

    Read the article

  • What is the main purpose of WebExceptionStatus.Success?

    - by csharpenter
    I am a bit confused about the purpose of the enum value Success of the WebExceptionStatus enumeration. I did a search and did not find this enumeration being used outside the WebException class. This is very confusing to me. Why would an exception be used to indicate a successful action/state. Am I missing something, or did I not search thouroughly enough? Was it introduced for future functionality? Please if anyone does know its basic purpose I would be thankfull if s/he shares with us the explanation.

    Read the article

  • Link checker ; how to avoid false positives

    - by Burnzy
    I'm working a on a link checker/broken link finder and I am getting many false positives, after double checking I noticed that many error codes were returning webexceptions but they were actually downloadable, but in some other cases the statuscode is 404 and i can access the page from the browse. So here is the code, its pretty ugly, and id like to have something more, id say practical. All the status codes are in that big if are used to filter the ones i dont want to add to brokenlink because they are valid links ( i tested them all ). What i need to fix is the structure (if possible) and how to not get false 404. Thank you! try { HttpWebRequest request = ( HttpWebRequest ) WebRequest.Create ( uri ); request.Method = "Head"; request.MaximumResponseHeadersLength = 32; // FOR IE SLOW SPEED request.AllowAutoRedirect = true; using ( HttpWebResponse response = ( HttpWebResponse ) request.GetResponse() ) { request.Abort(); } /* WebClient wc = new WebClient(); wc.DownloadString( uri ); */ _validlinks.Add ( strUri ); } catch ( WebException wex ) { if ( !wex.Message.Contains ( "The remote name could not be resolved:" ) && wex.Status != WebExceptionStatus.ServerProtocolViolation ) { if ( wex.Status != WebExceptionStatus.Timeout ) { HttpStatusCode code = ( ( HttpWebResponse ) wex.Response ).StatusCode; if ( code != HttpStatusCode.OK && code != HttpStatusCode.BadRequest && code != HttpStatusCode.Accepted && code != HttpStatusCode.InternalServerError && code != HttpStatusCode.Forbidden && code != HttpStatusCode.Redirect && code != HttpStatusCode.Found ) { _brokenlinks.Add ( new Href ( new Uri ( strUri , UriKind.RelativeOrAbsolute ) , UrlType.External ) ); } else _validlinks.Add ( strUri ); } else _brokenlinks.Add ( new Href ( new Uri ( strUri , UriKind.RelativeOrAbsolute ) , UrlType.External ) ); } else _validlinks.Add ( strUri ); }

    Read the article

  • System.UriFormatException: Invalid URI: The hostname could not be parsed.

    - by Shane
    All of a sudden I'm getting the following error on my website. It doesnt access a db. just a simple website using .net 2.0. I did recently apply the available windows server 2003 service packs. Could that have changed things? I should add the error randomly comes and goes and has been doing so for today and yesterday. I leave it for 5 minutes and the error is gone. Server Error in '/' Application. Invalid URI: The hostname could not be parsed. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.UriFormatException: Invalid URI: The hostname could not be parsed. Source Error: An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below. Stack Trace: [UriFormatException: Invalid URI: The hostname could not be parsed.] System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind) +5367536 System.Uri.CreateUri(Uri baseUri, String relativeUri, Boolean dontEscape) +31 System.Uri..ctor(Uri baseUri, String relativeUri) +34 System.Net.HttpWebRequest.CheckResubmit(Exception& e) +5300867 [WebException: Cannot handle redirect from HTTP/HTTPS protocols to other dissimilar ones.] System.Net.HttpWebRequest.GetResponse() +5314029 System.Xml.XmlDownloadManager.GetNonFileStream(Uri uri, ICredentials credentials) +69 System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials) +3929371 System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn) +54 System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver) +74 System.Threading.CompressedStack.runTryCode(Object userData) +70 System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData) +0 System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state) +108 System.Xml.XmlTextReaderImpl.OpenUrl() +186 System.Xml.XmlTextReaderImpl.Read() +208 System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace) +112 System.Xml.XmlDocument.Load(XmlReader reader) +108 System.Web.UI.WebControls.XmlDataSource.PopulateXmlDocument(XmlDocument document, CacheDependency& dataCacheDependency, CacheDependency& transformCacheDependency) +303 System.Web.UI.WebControls.XmlDataSource.GetXmlDocument() +153 System.Web.UI.WebControls.XmlDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +29 System.Web.UI.WebControls.BaseDataList.GetData() +39 System.Web.UI.WebControls.DataList.CreateControlHierarchy(Boolean useDataSource) +264 System.Web.UI.WebControls.BaseDataList.OnDataBinding(EventArgs e) +55 System.Web.UI.WebControls.BaseDataList.DataBind() +75 System.Web.UI.WebControls.BaseDataList.EnsureDataBound() +55 System.Web.UI.WebControls.BaseDataList.CreateChildControls() +65 System.Web.UI.Control.EnsureChildControls() +97 System.Web.UI.Control.PreRenderRecursiveInternal() +53 System.Web.UI.Control.PreRenderRecursiveInternal() +202 System.Web.UI.Control.PreRenderRecursiveInternal() +202 System.Web.UI.Control.PreRenderRecursiveInternal() +202 System.Web.UI.Control.PreRenderRecursiveInternal() +202 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +4588

    Read the article

  • System.Net.WebException: The remote server returned an error: (405) Method Not Allowed .exception occurred during the execution of the web request

    - by user88
    When I ran my web application code I got this error on this line. using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()){} Actually when I ran my url directly on browser.It will give proper o/p but when I ran my url in code. It will give exception. Here MyCode is :- string service = "http://api.ean.com/ean-services/rs/hotel/"; string version = "v3/"; string method = "info/"; string hotelId1 = "188603"; int hotelId = Convert.ToInt32(hotelId1); string otherElemntsStr = "&cid=411931&minorRev=[12]&customerUserAgent=[hotel]&locale=en_US&currencyCode=INR"; string apiKey = "tzyw4x2zspckjayrbjekb397"; string sig = "a6f828b696ae6a9f7c742b34538259b0"; string url = service + version + method + "?&type=xml" + "&apiKey=" + apiKey + "&sig=" + sig + otherElemntsStr + "&hotelId=" + hotelId; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url) as HttpWebRequest; request.Method = "POST"; request.ContentType = "text/xml"; request.ContentLength = 0; XmlDocument xmldoc = new XmlDocument(); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { StreamReader responsereader = new StreamReader(response.GetResponseStream()); var responsedata = responsereader.ReadToEnd(); xmldoc = (XmlDocument)JsonConvert.DeserializeXmlNode(responsedata); xmldoc.Save(@"D:\FlightSearch\myfile.xml"); xmldoc.Load(@"D:\FlightSearch\myfile.xml"); DataSet ds = new DataSet(); ds.ReadXml(Request.PhysicalApplicationPath + "myfile.xml"); GridView1.DataSource = ds.Tables["HotelSummary"]; GridView1.DataBind(); }

    Read the article

  • A DirectoryCatalog class for Silverlight MEF (Managed Extensibility Framework)

    - by Dixin
    In the MEF (Managed Extension Framework) for .NET, there are useful ComposablePartCatalog implementations in System.ComponentModel.Composition.dll, like: System.ComponentModel.Composition.Hosting.AggregateCatalog System.ComponentModel.Composition.Hosting.AssemblyCatalog System.ComponentModel.Composition.Hosting.DirectoryCatalog System.ComponentModel.Composition.Hosting.TypeCatalog While in Silverlight, there is a extra System.ComponentModel.Composition.Hosting.DeploymentCatalog. As a wrapper of AssemblyCatalog, it can load all assemblies in a XAP file in the web server side. Unfortunately, in silverlight there is no DirectoryCatalog to load a folder. Background There are scenarios that Silverlight application may need to load all XAP files in a folder in the web server side, for example: If the Silverlight application is extensible and supports plug-ins, there would be a /ClinetBin/Plugins/ folder in the web server, and each pluin would be an individual XAP file in the folder. In this scenario, after the application is loaded and started up, it would like to load all XAP files in /ClinetBin/Plugins/ folder. If the aplication supports themes, there would be a /ClinetBin/Themes/ folder, and each theme would be an individual XAP file too. The application would qalso need to load all XAP files in /ClinetBin/Themes/. It is useful if we have a DirectoryCatalog: DirectoryCatalog catalog = new DirectoryCatalog("/Plugins"); catalog.DownloadCompleted += (sender, e) => { }; catalog.DownloadAsync(); Obviously, the implementation of DirectoryCatalog is easy. It is just a collection of DeploymentCatalog class. Retrieve file list from a directory Of course, to retrieve file list from a web folder, the folder’s “Directory Browsing” feature must be enabled: So when the folder is requested, it responses a list of its files and folders: This is nothing but a simple HTML page: <html> <head> <title>localhost - /Folder/</title> </head> <body> <h1>localhost - /Folder/</h1> <hr> <pre> <a href="/">[To Parent Directory]</a><br> <br> 1/3/2011 7:22 PM 185 <a href="/Folder/File.txt">File.txt</a><br> 1/3/2011 7:22 PM &lt;dir&gt; <a href="/Folder/Folder/">Folder</a><br> </pre> <hr> </body> </html> For the ASP.NET Deployment Server of Visual Studio, directory browsing is enabled by default: The HTML <Body> is almost the same: <body bgcolor="white"> <h2><i>Directory Listing -- /ClientBin/</i></h2> <hr width="100%" size="1" color="silver"> <pre> <a href="/">[To Parent Directory]</a> Thursday, January 27, 2011 11:51 PM 282,538 <a href="Test.xap">Test.xap</a> Tuesday, January 04, 2011 02:06 AM &lt;dir&gt; <a href="TestFolder/">TestFolder</a> </pre> <hr width="100%" size="1" color="silver"> <b>Version Information:</b>&nbsp;ASP.NET Development Server 10.0.0.0 </body> The only difference is, IIS’s links start with slash, but here the links do not. Here one way to get the file list is read the href attributes of the links: [Pure] private IEnumerable<Uri> GetFilesFromDirectory(string html) { Contract.Requires(html != null); Contract.Ensures(Contract.Result<IEnumerable<Uri>>() != null); return new Regex( "<a href=\"(?<uriRelative>[^\"]*)\">[^<]*</a>", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant) .Matches(html) .OfType<Match>() .Where(match => match.Success) .Select(match => match.Groups["uriRelative"].Value) .Where(uriRelative => uriRelative.EndsWith(".xap", StringComparison.Ordinal)) .Select(uriRelative => { Uri baseUri = this.Uri.IsAbsoluteUri ? this.Uri : new Uri(Application.Current.Host.Source, this.Uri); uriRelative = uriRelative.StartsWith("/", StringComparison.Ordinal) ? uriRelative : (baseUri.LocalPath.EndsWith("/", StringComparison.Ordinal) ? baseUri.LocalPath + uriRelative : baseUri.LocalPath + "/" + uriRelative); return new Uri(baseUri, uriRelative); }); } Please notice the folders’ links end with a slash. They are filtered by the second Where() query. The above method can find files’ URIs from the specified IIS folder, or ASP.NET Deployment Server folder while debugging. To support other formats of file list, a constructor is needed to pass into a customized method: /// <summary> /// Initializes a new instance of the <see cref="T:System.ComponentModel.Composition.Hosting.DirectoryCatalog" /> class with <see cref="T:System.ComponentModel.Composition.Primitives.ComposablePartDefinition" /> objects based on all the XAP files in the specified directory URI. /// </summary> /// <param name="uri"> /// URI to the directory to scan for XAPs to add to the catalog. /// The URI must be absolute, or relative to <see cref="P:System.Windows.Interop.SilverlightHost.Source" />. /// </param> /// <param name="getFilesFromDirectory"> /// The method to find files' URIs in the specified directory. /// </param> public DirectoryCatalog(Uri uri, Func<string, IEnumerable<Uri>> getFilesFromDirectory) { Contract.Requires(uri != null); this._uri = uri; this._getFilesFromDirectory = getFilesFromDirectory ?? this.GetFilesFromDirectory; this._webClient = new Lazy<WebClient>(() => new WebClient()); // Initializes other members. } When the getFilesFromDirectory parameter is null, the above GetFilesFromDirectory() method will be used as default. Download the directory’s XAP file list Now a public method can be created to start the downloading: /// <summary> /// Begins downloading the XAP files in the directory. /// </summary> public void DownloadAsync() { this.ThrowIfDisposed(); if (Interlocked.CompareExchange(ref this._state, State.DownloadStarted, State.Created) == 0) { this._webClient.Value.OpenReadCompleted += this.HandleOpenReadCompleted; this._webClient.Value.OpenReadAsync(this.Uri, this); } else { this.MutateStateOrThrow(State.DownloadCompleted, State.Initialized); this.OnDownloadCompleted(new AsyncCompletedEventArgs(null, false, this)); } } Here the HandleOpenReadCompleted() method is invoked when the file list HTML is downloaded. Download all XAP files After retrieving all files’ URIs, the next thing becomes even easier. HandleOpenReadCompleted() just uses built in DeploymentCatalog to download the XAPs, and aggregate them into one AggregateCatalog: private void HandleOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { Exception error = e.Error; bool cancelled = e.Cancelled; if (Interlocked.CompareExchange(ref this._state, State.DownloadCompleted, State.DownloadStarted) != State.DownloadStarted) { cancelled = true; } if (error == null && !cancelled) { try { using (StreamReader reader = new StreamReader(e.Result)) { string html = reader.ReadToEnd(); IEnumerable<Uri> uris = this._getFilesFromDirectory(html); Contract.Assume(uris != null); IEnumerable<DeploymentCatalog> deploymentCatalogs = uris.Select(uri => new DeploymentCatalog(uri)); deploymentCatalogs.ForEach( deploymentCatalog => { this._aggregateCatalog.Catalogs.Add(deploymentCatalog); deploymentCatalog.DownloadCompleted += this.HandleDownloadCompleted; }); deploymentCatalogs.ForEach(deploymentCatalog => deploymentCatalog.DownloadAsync()); } } catch (Exception exception) { error = new InvalidOperationException(Resources.InvalidOperationException_ErrorReadingDirectory, exception); } } // Exception handling. } In HandleDownloadCompleted(), if all XAPs are downloaded without exception, OnDownloadCompleted() callback method will be invoked. private void HandleDownloadCompleted(object sender, AsyncCompletedEventArgs e) { if (Interlocked.Increment(ref this._downloaded) == this._aggregateCatalog.Catalogs.Count) { this.OnDownloadCompleted(e); } } Exception handling Whether this DirectoryCatelog can work only if the directory browsing feature is enabled. It is important to inform caller when directory cannot be browsed for XAP downloading. private void HandleOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { Exception error = e.Error; bool cancelled = e.Cancelled; if (Interlocked.CompareExchange(ref this._state, State.DownloadCompleted, State.DownloadStarted) != State.DownloadStarted) { cancelled = true; } if (error == null && !cancelled) { try { // No exception thrown when browsing directory. Downloads the listed XAPs. } catch (Exception exception) { error = new InvalidOperationException(Resources.InvalidOperationException_ErrorReadingDirectory, exception); } } WebException webException = error as WebException; if (webException != null) { HttpWebResponse webResponse = webException.Response as HttpWebResponse; if (webResponse != null) { // Internally, WebClient uses WebRequest.Create() to create the WebRequest object. Here does the same thing. WebRequest request = WebRequest.Create(Application.Current.Host.Source); Contract.Assume(request != null); if (request.CreatorInstance == WebRequestCreator.ClientHttp && // Silverlight is in client HTTP handling, all HTTP status codes are supported. webResponse.StatusCode == HttpStatusCode.Forbidden) { // When directory browsing is disabled, the HTTP status code is 403 (forbidden). error = new InvalidOperationException( Resources.InvalidOperationException_ErrorListingDirectory_ClientHttp, webException); } else if (request.CreatorInstance == WebRequestCreator.BrowserHttp && // Silverlight is in browser HTTP handling, only 200 and 404 are supported. webResponse.StatusCode == HttpStatusCode.NotFound) { // When directory browsing is disabled, the HTTP status code is 404 (not found). error = new InvalidOperationException( Resources.InvalidOperationException_ErrorListingDirectory_BrowserHttp, webException); } } } this.OnDownloadCompleted(new AsyncCompletedEventArgs(error, cancelled, this)); } Please notice Silverlight 3+ application can work either in client HTTP handling, or browser HTTP handling. One difference is: In browser HTTP handling, only HTTP status code 200 (OK) and 404 (not OK, including 500, 403, etc.) are supported In client HTTP handling, all HTTP status code are supported So in above code, exceptions in 2 modes are handled differently. Conclusion Here is the whole DirectoryCatelog’s looking: Please click here to download the source code, a simple unit test is included. This is a rough implementation. And, for convenience, some design and coding are just following the built in AggregateCatalog class and Deployment class. Please feel free to modify the code, and please kindly tell me if any issue is found.

    Read the article

  • 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

  • KeepAliveException when using HttpWebRequest.GetResponse

    - by Lucas
    I am trying to POST an attachment to CouchDB using the HttpWebRequest. However, when I attempt "response = (HttpWebResponse)httpWebRequest.GetResponse();" I receive a WebException with the message "The underlying connection was closed: A connection that was expected to be kept alive was closed by the server." I have found some articles stating that setting the keepalive to false and httpversion to 1.0 resolves the situation. I am finding that it does not yeilding the exact same error, plus I do not want to take that approach as I do not want to use the 1.0 version due to how it handles the connection. Any suggestions or ideas are welcome. I'll try them all until one works! public ServerResponse PostAttachment(Server server, Database db, Attachment attachment) { Stream dataStream; HttpWebResponse response = null; StreamReader sr = null; byte[] buffer; string json; string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); string headerTemplate = "Content-Disposition: form-data; name=\"_attachments\"; filename=\"" + attachment.Filename + "\"\r\n Content-Type: application/octet-stream\r\n\r\n"; byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(headerTemplate); byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://" + server.Host + ":" + server.Port.ToString() + "/" + db.Name + "/" + attachment.Document.Id); httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary; httpWebRequest.Method = "POST"; httpWebRequest.KeepAlive = true; httpWebRequest.ContentLength = attachment.Stream.Length + headerbytes.Length + boundarybytes.Length; if (!string.IsNullOrEmpty(server.EncodedCredentials)) httpWebRequest.Headers.Add("Authorization", server.EncodedCredentials); if (!attachment.Stream.CanRead) throw new System.NotSupportedException("The stream cannot be read."); // Get the request stream try { dataStream = httpWebRequest.GetRequestStream(); } catch (Exception e) { throw new WebException("Failed to get the request stream.", e); } buffer = new byte[server.BufferSize]; int bytesRead; dataStream.Write(headerbytes,0,headerbytes.Length); attachment.Stream.Position = 0; while ((bytesRead = attachment.Stream.Read(buffer, 0, buffer.Length)) > 0) { dataStream.Write(buffer, 0, bytesRead); } dataStream.Write(boundarybytes, 0, boundarybytes.Length); dataStream.Close(); // send the request and get the response try { response = (HttpWebResponse)httpWebRequest.GetResponse(); } catch (Exception e) { throw new WebException("Invalid response received from server.", e); } // get the server's response json try { dataStream = response.GetResponseStream(); sr = new StreamReader(dataStream); json = sr.ReadToEnd(); } catch (Exception e) { throw new WebException("Failed to access the response stream.", e); } // close up all our streams and response sr.Close(); dataStream.Close(); response.Close(); // Deserialize the server response return ConvertTo.JsonToServerResponse(json); }

    Read the article

  • the HTTP request is unauthorized with client authentication scheme 'Anonymous'

    - by user1246429
    I use firstdata webservice API.I use C# client call firstdata webservice API with WCF. But show error message: "But show error message "System.ServiceModel.Security.MessageSecurityException: The HTTP request is unauthorized with client authentication scheme 'Anonymous'. The authentication header received from the server was ''. --- System.Net.WebException: The remote server returned an error: (401) Unauthorized. at System.Net.HttpWebRequest.GetResponse() at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) --- End of inner exception stack trace --- Server stack trace: at System.ServiceModel.Channels.HttpChannelUtilities.ValidateAuthentication(HttpWebRequest request, HttpWebResponse response, WebException responseException, HttpChannelFactory factory) at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResponse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factory, WebException responseException, ChannelBinding channelBinding) at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout) at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout) at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout) at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation) at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message) Exception rethrown at [0]: at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) at com.firstdata.globalgatewaye4.api.ServiceSoap.SendAndCommit(SendAndCommitRequest request) at com.firstdata.globalgatewaye4.api.ServiceSoapClient.com.firstdata.globalgatewaye4.api.ServiceSoap.SendAndCommit (SendAndCommitRequest request) at com.firstdata.globalgatewaye4.api.ServiceSoapClient.SendAndCommit(Transaction SendAndCommitSource)" My web.config info below: <behaviors> <endpointBehaviors> <behavior name="FDGGBehavior"> <clientCredentials> <clientCertificate findValue="WS1909642825._.1" storeLocation="LocalMachine" x509FindType="FindBySubjectName" storeName="TrustedPeople" /> <serviceCertificate> <authentication certificateValidationMode="PeerTrust" /> </serviceCertificate> </clientCredentials> </behavior> </endpointBehaviors> </behaviors> <binding name="ServiceSoap" closeTimeout="00:01:00" openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true"> <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" /> <security mode="TransportWithMessageCredential"> <transport clientCredentialType="Certificate" proxyCredentialType="Ntlm" /> <message clientCredentialType="UserName" algorithmSuite="Default" /> </security> </binding> <endpoint address="https://api.globalgatewaye4.firstdata.com/transaction/v11" binding="basicHttpBinding" bindingConfiguration="ServiceSoap" contract="com.firstdata.globalgatewaye4.api.ServiceSoap" name="ServiceSoap" behaviorConfiguration="FDGGBehavior" /> How can resolve question?

    Read the article

  • LINQ insert to database by WCF Service from Silverlight app

    - by Rafal
    Hi I have a problem during insert to database by LINQ command in WCF Service from Silverlight application. Receiving data works fine - select works in LINQ and shows data from database(sql server 2008). When i try to insert data, the Error ocures: System.Net.WebException: The remote server returned an error: NotFound. ---> System.Net.WebException: The remote server returned an error: NotFound. at System.Net.Browser.BrowserHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult) at System.Net.Browser.BrowserHttpWebRequest.<>c__DisplayClass5.<EndGetResponse>b__4(Object sendState) at System.Net.Browser.AsyncHelper.<>c__DisplayClass2.<BeginOnUI>b__0(Object sendState) --- End of inner exception stack trace --- at System.Net.Browser.AsyncHelper.BeginOnUI(SendOrPostCallback beginMethod, Object state) at System.Net.Browser.BrowserHttpWebRequest.EndGetResponse(IAsyncResult asyncResult) at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelAsyncRequest.CompleteGetResponse(IAsyncResult result)} It looks the same, when i had a wrong ClientConfig/Web.config file. Please Help...I need to insert some data:)

    Read the article

  • How to Force an Exception from a Task to be Observed in a Continuation Task?

    - by Richard
    I have a task to perform an HttpWebRequest using Task<WebResponse>.Factory.FromAsync(req.BeginGetRespone, req.EndGetResponse) which can obviously fail with a WebException. To the caller I want to return a Task<HttpResult> where HttpResult is a helper type to encapsulate the response (or not). In this case a 4xx or 5xx response is not an exception. Therefore I've attached two continuations to the request task. One with TaskContinuationOptions OnlyOnRanToCompletion and the other with OnlyOnOnFaulted. And then wrapped the whole thing in a Task<HttpResult> to pick up the one result whichever continuation completes. Each of the three child tasks (request plus two continuations) is created with the AttachedToParent option. But when the caller waits on the returned outer task, an AggregateException is thrown is the request failed. I want to, in the on faulted continuation, observe the WebException so the client code can just look at the result. Adding a Wait in the on fault continuation throws, but a try-catch around this doesn't help. Nor does looking at the Exception property (as section "Observing Exceptions By Using the Task.Exception Property" hints here). I could install a UnobservedTaskException event handler to filter, but as the event offers no direct link to the faulted task this will likely interact outside this part of the application and is a case of a sledgehammer to crack a nut. Given an instance of a faulted Task<T> is there any means of flagging it as "fault handled"? Simplified code: public static Task<HttpResult> Start(Uri url) { var webReq = BuildHttpWebRequest(url); var result = new HttpResult(); var taskOuter = Task<HttpResult>.Factory.StartNew(() => { var tRequest = Task<WebResponse>.Factory.FromAsync( webReq.BeginGetResponse, webReq.EndGetResponse, null, TaskCreationOptions.AttachedToParent); var tError = tRequest.ContinueWith<HttpResult>( t => HandleWebRequestError(t, result), TaskContinuationOptions.AttachedToParent |TaskContinuationOptions.OnlyOnFaulted); var tSuccess = tRequest.ContinueWith<HttpResult>( t => HandleWebRequestSuccess(t, result), TaskContinuationOptions.AttachedToParent |TaskContinuationOptions.OnlyOnRanToCompletion); return result; }); return taskOuter; } with: private static HttpDownloaderResult HandleWebRequestError( Task<WebResponse> respTask, HttpResult result) { Debug.Assert(respTask.Status == TaskStatus.Faulted); Debug.Assert(respTask.Exception.InnerException is WebException); // Try and observe the fault: Doesn't help. try { respTask.Wait(); } catch (AggregateException e) { Log("HandleWebRequestError: waiting on antecedent task threw inner: " + e.InnerException.Message); } // ... populate result with details of the failure for the client ... return result; } (HandleWebRequestSuccess will eventually spin off further tasks to get the content of the response...) The client should be able to wait on the task and then look at its result, without it throwing due to a fault that is expected and already handled.

    Read the article

1 2 3 4 5  | Next Page >