Microsoft KB Archive/833381

= How to implement custom fault codes with ASP.NET Web services =

Article ID: 833381

Article Last Modified on 4/29/2007

-

APPLIES TO


 * Microsoft Web Services Enhancements for Microsoft .NET 1.1
 * Microsoft Web Services Enhancements for Microsoft .NET 2.0

-



IN THIS TASK

 * SUMMARY
 * Requirements
 * Create a Web Service that raises a custom exception
 * Create a console application that consumes the Web Service and handles the custom exception
 * REFERENCES



SUMMARY
This step-by-step article describes how to raise a custom exception that exposes the method for dividing two numbers in a Web service and how to create a console application that consumes the Web Service and handles the custom exception.

back to the top

Requirements
This article assumes that you are familiar with the following topics:
 * Programming with Microsoft ASP.NET 1.1 or with ASP.NET 1.0
 * Handling exceptions in the Microsoft .NET Framework 1.1 or in the .NET Framework 1.0

The following list outlines the recommended hardware, software, network infrastructure, and service packs that you need:
 * Microsoft Visual Studio .NET 2003 or Microsoft Visual Studio .NET 2002
 * Microsoft Internet Information Server 6.0 or Microsoft Internet Information Server 5.0
 * Microsoft 2003 .NET Server, Microsoft Windows XP, or Microsoft Windows 2000 Server

back to the top

How to create a Web Service that raises a custom exception
 Click Start, point to Programs, point to Microsoft Visual Studio .NET, and then click Microsoft Visual Studio .NET. On the File menu, click New, and then click Project. Under Project types, click Visual C# Projects. Under Templates, click ASP.NET Web Service. Type http:// /MathService in the Location box, and then click OK.

Note In this step, ServerName is a placeholder for the actual name of the server.  Add the following namespaces to the Server1.asmx.cs file: using System.Web.Services.Protocols; using System.Xml;  Flag each method that will be exposed from the service with a WebMethod attribute.

Note You must define the methods to encapsulate the functionality of your service. Without the WebMethod attribute, the methods will not be exposed from the service. However, every method does not have to use the WebMethod attribute. It might be useful to hide some implementation details that are called by public Web service methods. It might also be useful to hide some implementation details if the WebService class is also used in local applications. A local application can use any public class, but only methods with the WebMethod attribute can be accessed remotely as Web services.</li>  Add the following methods to the Service1 class in the Service1.asmx.cs file: [WebMethod] public float Divide(int firstParameter, int secondParameter) {   float result; try {       result = OperationDivision(firstParameter, secondParameter); }   catch(InvalidParameterException ex) {       throw RaiseException(&quot;http://tempuri.org/MathService&quot;,&quot;Divide&quot;,ex.Message,        &quot;1000&quot;,ex.Source, &quot;Client.InvalidInputParameter&quot;); }   return result; }

private float OperationDivision(int firstParameter, int secondParameter) {   //Throw a custom exception if the second parameter is ZERO. if (secondParameter == 0) {       InvalidParameterException invalidParameter = new InvalidParameterException(&quot;Second parameter passed from client to WebMethod [Divide] is ZERO (0).&quot;) ; throw invalidParameter; }   return (firstParameter / secondParameter); }

private SoapException RaiseException(string uri, string webServiceNamespace, string errorMessage, string errorNumber, string errorSource, string specificFaultCode) {   XmlQualifiedName faultCodeLocation = null; //Create fault code that is specific to the Application exception. faultCodeLocation = new XmlQualifiedName(specificFaultCode, &quot;http://schemas.xmlsoap.org/soap/envelope/&quot;); XmlDocument xmlDoc = new XmlDocument; //Create the Detail node. XmlNode rootNode = xmlDoc.CreateNode(XmlNodeType.Element, SoapException.DetailElementName.Name, SoapException.DetailElementName.Namespace); //Build specific details for the SoapException. //Add the first child of the detail XML element. XmlNode errorNode = xmlDoc.CreateNode(XmlNodeType.Element,&quot;Error&quot;, uri); //Create and then set the value for the ErrorNumber node. XmlNode errorNumberNode = xmlDoc.CreateNode(XmlNodeType.Element,&quot;ErrorNumber&quot;, uri ); errorNumberNode.InnerText = errorNumber; //Create and then set the value for the ErrorMessage node. XmlNode errorMessageNode = xmlDoc.CreateNode(XmlNodeType.Element,    &quot;ErrorMessage&quot;,  uri ); errorMessageNode.InnerText = errorMessage; //Create and then set the value for the ErrorSource node. XmlNode errorSourceNode = xmlDoc.CreateNode(XmlNodeType.Element,&quot;ErrorSource&quot;, uri); errorSourceNode.InnerText = errorSource; //Append the Error child element nodes to the root detail node. errorNode.AppendChild(errorNumberNode); errorNode.AppendChild(errorMessageNode); errorNode.AppendChild(errorSourceNode); //Append the Detail node to the root node. rootNode.AppendChild(errorNode); //Construct the exception. SoapException soapEx = new SoapException(errorMessage, faultCodeLocation, uri, rootNode); //Raise the exception back to the caller. return soapEx; } </li>  Add the following class to the &quot;MathService&quot; namespace: public class InvalidParameterException: ArgumentException {   public InvalidParameterException {   }    public InvalidParameterException(string message) : base(message) {   }    public InvalidParameterException(string message, Exception inner) : base(message, inner) {   } } </li> On the Build menu, click Build Solution to build the Web service.</li></ol>

back to the top

How to create a console application that consumes the Web Service and handles the custom exception
<ol> Click Start, point to Programs, point to Microsoft Visual Studio .NET, and then click Microsoft Visual Studio .NET.</li> Under Project types, click Visual C# Projects.</li> Under Templates, click Console Application, and then click OK.</li> Add a Web reference to the &quot;MathService&quot; Web service that you created in the &quot;Create a Web Service that raises a custom exception&quot; section as follows.

Note In this step, you create a proxy class on the client computer. After the proxy class is created, you can create objects based on the proxy class. Typically, each method call that is made by using these objects goes to the uniform resource identifier (URI) of the Web service as a SOAP request. <ol style="list-style-type: lower-alpha;"> On the Project menu, click Add Web Reference.</li> In the Add Web Reference dialog box, type the URL for the Web service in the URL text box, and then click Add Reference.

Note If you set the local computer to host the Web service, type the following URL in the URL text box:

http://localhost/MathService/Service1.asmx

</li></ol> </li>  Add the following code at the top: using System.Web.Services.Protocols; using System.Xml; </li>  Add the following code to the Main method to create an instance of the proxy object: localhost.Service1 myMathService = new localhost.Service1; </li>  Add the following code to the Main method to invoke a method on the proxy object that you created in step 5: try {   Console.WriteLine(&quot;6 / 0 = {0}&quot;,myMathService.Divide(6, 0)); } catch (SoapException soapEx) {   //Load the Detail element of the SoapException object. XmlDocument doc = new XmlDocument; doc.LoadXml(soapEx.Detail.OuterXml); XmlNamespaceManager nsManager = new XmlNamespaceManager(doc.NameTable); //Add the namespace to the NamespaceManager. nsManager.AddNamespace(&quot;errorNS&quot;, &quot;http://tempuri.org/MathService&quot;); XmlNode categoryNode = doc.DocumentElement.SelectSingleNode(&quot;errorNS:Error&quot;,nsManager); string errorNumber = categoryNode.SelectSingleNode(&quot;errorNS:ErrorNumber&quot;,nsManager).InnerText; string errorMessage = categoryNode.SelectSingleNode(&quot;errorNS:ErrorMessage&quot;,nsManager).InnerText; string errorSource = categoryNode.SelectSingleNode(&quot;errorNS:ErrorSource&quot;,nsManager).InnerText; Console.WriteLine(&quot;Error occured in the Web Service &quot;); Console.WriteLine(&quot;Error Number : &quot; + errorNumber); Console.WriteLine(&quot;Error Message : &quot; + errorMessage); Console.WriteLine(&quot;Error Source : &quot; + errorSource); //Custom fault code that is created at the WebService is accessible in the client application. //By using this custom fault code, this error message, and this error number, //the client application can receive a type of exception thrown in WebService. Console.WriteLine(&quot;Fault code specific to Application Exception : &quot;+soapEx.Code.Name.ToString); Console.ReadLine; } catch (Exception ex) {   Console.WriteLine(&quot;Error: &quot; + ex.Message); } </li> On the Build menu, click Build Solution.</li> On the Debug menu, click Start to test the application.</li></ol>

back to the top

<div class="references_section">