Exception Handling in Web Services (2) _ Server

Source: Internet
Author: User
Tags constant exception handling

Implementation of Web services to achieve this example, we create a Web service called Categoriesservice that selects a visual C#asp.netweb service as a template for the project. Once you create the project, we add a method named Addcategories, and add the following code to this method:

[WebMethod]

Publicbooladdcategories (Stringxml)

{

Try

{

using (Sqlconnectionconn=newsqlconnection ())

{

if (Validatexml (XML))

{

Xmldocumentdoc=newxmldocument ();

Doc. Loadxml (XML);

Conn. connectionstring=

"Server=localhost;uid=sa;pwd=thiru;database=northwind";

Conn. Open ();

Xmlnamespacemanagernsmanager=new

XmlNamespaceManager (Doc. NameTable);

Addthenamespacetothenamespacemanager

Nsmanager.addnamespace ("Catns",

"Http://tempuri.org/CategoriesNamespace");

Xmlnodecategorynode=

Doc. Documentelement.selectsinglenode ("Catns:category",

Nsmanager);

Stringcategoryname=

Categorynode.selectsinglenode ("Catns:categoryname",

Nsmanager). InnerText;

stringcategorydescription=

Categorynode.selectsinglenode ("Catns:categorydescription",

Nsmanager). InnerText;

Sqlcommandcommand=new

SqlCommand ("Usp_insertcategories", conn);

Command.commandtype=commandtype.storedprocedure; Addthecategorynameparameter

Sqlparameterparamcategoryname=new

SqlParameter ("@CategoryName", sqldbtype.nvarchar,15);

Paramcategoryname.direction=parameterdirection.input;

Paramcategoryname.value=categoryname;

Command. Parameters.Add (Paramcategoryname);

Addthedescriptionparameter

Sqlparameterparamdescription=new

SqlParameter ("@Description", Sqldbtype.text);

Paramdescription.direction=parameterdirection.input;

Paramdescription.value=categorydescription;

Command. Parameters.Add (paramdescription); Command. ExecuteNonQuery ();

}

Else

Throw

RaiseException ("Addcategories",

"Http://tempuri.org/CategoriesService",

Builder. ToString (),

"Addcategories", "faultcode.client";

}

Returntrue;

}

catch (Soapexceptionsoapex)

{

Throwsoapex;

}

catch (Exceptionex)

{

EventLog.WriteEntry ("Test", ex. message);

Throw

RaiseException ("Addcategories",

"Http://tempuri.org/CategoriesService", ex. Message,

"1000", ex. Source,faultcode.server);

}

As the name suggests, the Addcategories method is responsible for adding category details to the Categories table in the Northwind database. Before performing the add operation, the Addcategories method verifies the added XML data using an external XML schema file, and if the checksum fails, throws an exception to the client of the Web service.

Let's take a rough look at the code above. First, the XML data is passed to it, and the Validatexml method is invoked. We'll see the code for the Validatexml method in a second. The Validatexml method returns True or false, depending entirely on whether the XML checksum succeeds. If true, a XmlDocument object instance is created and the XML data is imported, and the ConnectionString property is set to initialize the SqlConnection object. Then call the SqlConnection object's Open method. Second, create a XmlNamespaceManager instance and call the AddNamespace method to associate a namespace. Once the namespace is associated, we can use the namespace identifier to refer to the correct XML element. Again, create a SqlParameter object instance to add parameters to the stored procedure. Finally, the ExecuteNonQuery method of the SqlCommand object is invoked to execute the stored procedure.

If the Validatexml method returns False, the SoapException is thrown with an assistant method named RaiseException. We're going to talk about RaiseException now. The RaiseException method is a basic helper method that encapsulates the code used to throw an exception from a Web service. The last parameter of the RaiseException method is an enumerated constant, which is defined as follows.

Publicenumfaultcode

{

Client=0,

Server=1

}

The XML checksum failure indicates that the client supplied invalid XML data. In this case, we should set the enumeration constants to client and point out this error to the client application. This allows us to notify the client application that it is possible to check the format of the input data before calling the Web service again. If the Web service fails for some other reason (for example, the database server is not available), you need to set the enumeration constant to server. This means that the failure of the Web service is due to some server-side problems, and the client application can request it in a few seconds. In fact, capturing the general exception in the catch block is exactly what we're going to do. (Source: Pconline)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.