C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Training   ASP.NET Web Hosting    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

Play Silverlight Games or Submit your Silverlight applications and earn 90% AdSense revenue.

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




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: Points: 5



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

Author: Ashish Jaiman    14 Jun 2004Member Level: Bronze   Points : 0
you should have called response.close in finally


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 Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
Related Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use