C# Tutorials and offshore development in India
Tutorials Resources Forum Reviews Communities Interview Jobs Projects Training Videos


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...


Birthday Greetings
Learn Windows 7: Epic Browser   This Article gives you the Complete Details about Epic Browser.



Resources » Articles » .NET Framework »

Handling The Network Errors


Posted Date: 01 Jun 2004    Resource Type: Articles    Category: .NET Framework
Author: ANITA MARY JOSEPHMember Level: Gold    
Rating: 1 out of 5Points: 5


To fully handle all network exceptions that the program might generate, you must monitor calls to Create(), GetResponse(), and GetResponseStream(). Each type of potential error is described in this article.



Exceptions Generated by Create()
The Create() method defined by WebRequest can generate three exceptions. If the protocol specified by the URI prefix is not supported, then NotSupportedException is thrown. If the URI format is invalid, UriFormatException is thrown. It can also throw an ArgumentNullException if it is called with a null reference, but this is not an error generated by networking.




Exceptions Generated by GetResponse()
If an error occurs when obtaining a response by calling GetResponse(), a WebException is thrown. In addition to the members defined for all exceptions, WebException adds two properties that relate to network errors: Response and Status.

You can obtain a reference to the WebResponse object inside an exception handler through the Response property. This is the object that would have been returned by GetResponse() if an exception had not occurred. It is defined like this:

public WebResponse Response { get; }

When an error occurs, you can use the Status property of WebException to find out what went wrong. It is defined like this:

public WebExceptionStatus { get; }

WebExceptionStatus is an enumeration that contains the following values:


ConnectFailure
ConnectionClosed
KeepAliveFailure
NameResolutionFailure
Pending
PipelineFailure
ProtocolError
ProxyNameResolutionFailure
ReceiveFailure
RequestCanceled
SecureChannelFailure
SendFailure
ServerProtocolViolation
Success
Timeout
TrustFailure



Once the cause of the error has been determined, your program can take appropriate action.




Exceptions Generated by GetResponseStream()
The GetResponseStream() method of GetResponse can throw a ProtocolViolationException, which in general means that some error occurred relative to the specified protocol. As it relates to GetResponseStream(), it means that no valid response stream is available. Also, an IOException could occur while reading the stream.

Example:

// Handling Network Exceptions.
using System;
using System.Net;
using System.IO;

class Exception
{
public static void Main()
{
int ch;
try
{
//Create a WebRequest to a URI.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://dotnetspider.com");

//send that request and return the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

//obtain an input stream from the response.
Stream stream = response.GetResponseStream();

//Read & Display the html, press ENTER after 400 characters are displayed.
for(int i = 1; ; i++)
{
ch = stream.ReadByte();
if (ch == -1) break;
Console.WriteLine((char)ch);
if((i % 400) == 0)
{
Console.Write("\nPress ENTER");
Console.Read();
}
}

response.Close();
}
catch(WebException exc)
{
Console.WriteLine("Network Error: " + exc.Message + "\nStatus Code: " + exc.Status);
}
catch(ProtocolViolationException exc)
{
Console.WriteLine("Protocol Error: " +exc.Message);
}
catch(UriFormatException exc)
{
Console.WriteLine("URI Format Error Error: " +exc.Message);
}
catch(NotSupportedException exc)
{
Console.WriteLine("Unkown Protocol: " +exc.Message);
}
catch(IOException exc)
{
Console.WriteLine("I/O Error: " +exc.Message);
}
Console.Read();
}
}


Now the exceptions that the networking methods might generate have been caught.
For example, if you change the call to Create() as shown here,

WebRequest.Create("http://dotnetspider.com/yellow.aspx");

and then recompile and run the program, you will see the output:

Network Error: The remote server returned an error: (404) Not Found.
Status Code: ProtocolError

Since the dotnetspider.com web site does not have a directory called “yellow“, this URI is not found, as the output confirms.





Responses to the resource: "Handling The Network Errors"
Author: Ashish Jaiman    14 Jun 2004Member Level: Bronze   Points : 0
you should have called response.close in finally


Author: pankaj kumar singh    17 Apr 2010Member Level: Silver   Points : 0
good work


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Redirecting the Standard Streams
Previous Resource: How To Call ActiveX DLL in .Net Environment
Return to Resources
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



About Us    Contact Us    Privacy Policy    Terms Of Use