TechBubbles

Archive for the 'Webservices' Category

Validating XML Document Using XSD in C#.NET

Introduction

This post explains how to apply  Schema Definition Language(XSD) to Extensible Markup Language () document. Basics of XSD.

Create an Document

  1. Start Visual Studio .NET
  2. Create a new File.
  3. Add the following data to the Document
<Employee EmployeeID="123">
   <EmployeeName>James Bond</EmployeeName>
</Employee>

  4.  Save the file as Employee. file 

Create the XSD Schema, and Link to Document

1. Start Visual Studio .NET

2. Create a new empty text file

3. Add the following XSD Schema definitions to describe the document.

<? version="1.0"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <xsd:element name="Employee">
      <xsd:complexType>
         <xsd:sequence>
            <xsd:element name="EmployeeName" type="xsd:string"/>
         </xsd:sequence>
         <xsd:attribute name="EmployeeID" use="required" type="xsd:int"/>
      </xsd:complexType>
   </xsd:element>
</xsd:schema>

4. Save the file as Employee.xsd 
5. Open the original Employee. file, and link it to the XSD schema as follows
<? version="1.0"?>
<Employee EmployeeID="123"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="Employee.xsd">
   <EmployeeName>Rugby jersey</EmployeeName>
</Employee>

6. Save the modified as EmployeeWithXSD..

Validate Document

1. Load the EmployeeWithXSD. using XmlTextReader as follows:

XmlTextReader r = new XmlTextReader("C:\\EmployeeWithXSD.");
XmlValidatingReader v = new XmlValidatingReader(r);
v.ValidationType = ValidationType.Schema;
v.ValidationEventHandler +=
   new ValidationEventHandler(MyValidationEventHandler);
while (v.Read())
{
   // Can add code here to process the content.
}
v.Close();

// Check whether the document is valid or invalid.
if (isValid)
   Console.WriteLine("Document is valid");
else
   Console.WriteLine("Document is invalid");
public static void MyValidationEventHandler(object sender,
                                            ValidationEventArgs args)
{
   isValid = false;
   Console.WriteLine("Validation event\n" + args.Message);
}

2. Build and run the application to use the XSD schema to validate the  

    document.

1 comment

XML Schema Basics(XSD)

Introduction

This post gives a basic overview of Schema and how to use in development. schema describes what document contains and content of the document what fields and sub elements it can contain.

Standards for Describing Document

  • DTD : was the First formulized standard.
  • XDR: Much comprehensive standard than DTD.
  • XSD: Currently de facto standard for describing the documents. There are two versions in use 1.0 and 1.1. An XSD schema it self is a document.

XSD Elements

Elements are building blocks for any document, element defines the structure of the document. The following is the syntax to define the element in XSD Schema.

Example:

<xs: element name=”abc” type=”xyz” /> 

  1. An Element must have the name property, the same will appear in the document.
  2. Type property describes about what can be contained in the element when it appears in document. eg: xs:string, xs:integer, xs:boolean or xs:date

Example:

Sample XSD

<xs:element name="Employee_dob"
                    type="xs:date"/>

Sample

<Employee_dob>
     2000-01-12T12:13:14Z
</Employee_dob>

Fixed and Default Properties

The XSD element can contain the Fixed or Default properties.

Default means that if no value specified in the document then application uses the default value specified in the XSD document.

Example:

<xs:element name="Employee_name" type="xs:string" default="unknown"/>

Fixed means the value in the document can only have the value specified in the XSD.

Example:

<xs:element name="Customer_location" type="xs:string" fixed="UK"/> 

Cardinality

Specifies how many times an element can appear can be called Cardinality. it is specified using the attributes minOccurs and maxOccurs. Both attributes can assigned a non-negative value.

The default value for minOccurs and maxOccurs is 1.

Example:

<xs:element name="Employee_hobbies"

                    type="xs:string"

                    minOccurs="2"

                    maxOccurs="10"/>

 

Employee_hobbies element must appear at least twice and not more than 10 times in the document.

 

Simple Types

We can define our own types by modifying the existing types.

example: Define a code, that may be an integer with a max limit.

<xs:element name="Employee" type="xs:string"/> 
Complex Types:  is a container for other elements which specifies child
elements an element can contain.
Example:
<xs:element name="Employee">
    <xs:complexType>
            <xs:sequence>
                <xs:element name="Dob" type="xs:date" />
                <xs:element name="Address" type="xs:string" />
            </xs:sequence>
        </xs:complexType>
</xs:element> 
  1. Created a definition for element Employee
  2. <xs:complexType> is a container for other <xs:elements>
  3. Complex type do not have the type attribute and contains the <xs:sequence> element.
  4. The sequence element specifies that document must appear in the same order they are declared in the XSD Schema.
<Employee>
    <Dob> 2000-01-12T12:13:14Z </Dob>
    <Address> 39 spring field road London </Address>
</Employee>
2 comments

WSE Settings 3.0 Tool

The features can be enabled by using 3.0 tool which is a graphical user interface in visual studio 2005. You have to download the WSE 3.0 for .NET to configure the 3.0 tool.

To open the Settings 3.0 tool from Visual Studio 2005.

  1. Open the Solution or project that you want to use the with.
  2. Right click the project point to Settings 3.0 and click

  WSEsettings

To use the settings 3.0 Tool from the start menu

1. Click Start, point to Microsoft 3.0, and then click Configuration Tool.

WSEStart

Read more

2 comments

Overview of WSE 3.0

Introduction

Enhancements is a .NET class library to develop using latest protocols.

Features

1 comment

HOST ASP.NET Web service in a Windows service

The following is the procedure to host a web service in windows service.

  1. Open Visual Studio 2005.
  2. Create an Web service.

          a. File menu, choose New Web Site

          b. In the New Web Site dialogue box, select the Web Service.

          c. Enter the address of web server and click Ok.

3. Add code to implement the Web Service.

4. Create a Windows service.

         a. File menu, choose New Project

         b. In the New Project dialogue box, select windows service.

         c. Specify the name and click Ok.

5. Add references to the Microsoft.Web.Services3, System.Web.Services, and System.Web assemblies.

6. Add source file and configuration file to the Windows service project.

    a. Right click the windows service project, point to Add choose Existing Item.

    b. Navigate to the configuration file in the web service folder select

       Web.config, and click Add.

    c. Right click the windows service project, point to Add choose Existing Item.

    d. Navigate to App_code folder web service project select the source file   

       Service1.cs, and click Add.

    e. Rename the Web.config file to app.config.

7. Open the source file in windows service project

    write the following code in OnStart Method

protected override void OnStart(string[] args)
{
    Uri address = new Uri("soap.tcp://localhost/TestService");
    SoapReceivers.Add(new EndpointReference(address), typeof(Service ));
}
8. Write the following code in OnStop Method.
protected override void OnStop()
 { SoapReceivers.Clear(); }
9.Write the following code in Main Method
static void Main()
{
    System.ServiceProcess.ServiceBase[] ServicesToRun;
    // Change the following line to match.
    ServicesToRun = new System.ServiceProcess.ServiceBase[] 
    { new WindowsServiceToHostASMXWebService() };
    System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}

10. Install the Windows Service.

1 comment

SOAP Message Routing with WSE

A application using can be designed by setting up a intermediary computer that is configured to run on router. Clients send messages to router instead of to the web service.

Router

Benefits of using router is computer that hosting a web service can be taken offline for maintenance with out modifying the client code or its configuration.

SOAP-Routing

Administrator prepares a web.config file that containing the referral cache containing the URL for Backup computer. Back computer is  prepared by administrator to redirect the Requests when Primary computer containing the web service is offline.

In the above diagram client sends the SOAP messages to a Router, Which delegates the message to another web server based on the content in referral cache. In this scenario Referral cache is configured to send the SOAP Message to Web server B, but it can be modified to send it to the Web server C.

1 comment

MTOM Support to Web Service

Overview of MTOM

Using MTOM an application can send or receive a large amount of data. MTOM allows message-level security to be applied to the message including binary data. MTOM encodes the SOAP message and transmits the message as .

Following is the procedure to send large amount of data using MTOM

  1. Open the web service project in Visual studio 2005

  2.   Enable the project to use by

        a. In solution explorer right click the project and then click Settings

        b. Select the general tab

        c. Select Enable this project for Enhancements and 

           Enable Microsoft Enhancements SOAP Protocol 

           Factory.

3. Specify that web service can accept SOAP messages encoded using MTOM.

        a. In solution explorer right click the project and then click  Settings.

        b. Select the Messaging tab.

        c. Choose optional or always for the Server Mode.

           always MTOM mode specifies that all incoming and outgoing SOAP  

           messages must be MTOM encoded.

           optional MTOM mode specifies that whether or not all incoming and  

           outgoing messages can be encoded.

Define a Web service method that returns a byte array.

[WebMethod]
public byte[] GetFile(string fileName)

{

    byte[] response;
    String filePath = AppDomain.CurrentDomain.BaseDirectory 
+ @"App_Data\" + fileName;
    response = File.ReadAllBytes(filePath);
    return response;

}

4. Configure the Web server to handle the larger amount of data.

<configuration>
  <system.web>
  <httpRuntime maxMessageLength="409600"
    executionTimeoutInSeconds="300"/>
  </system.web>
</configuration>
2 comments

Digital Signing the SOAP Message

allows you to digitally sign a SOAP Messages by overriding the SecureMessage method.

To sign a SOAP message

1. The following code example overrides the SecureMessage method.

public override void SecureMessage(SoapEnvelope envelope, Security security)
{

//Obtain the security token with which you want to sign the SOAP message with.

KerberosToken kerbToken = new 
KerberosToken("host/" + hostname + "@" + domainName);
// Add the security token.
security.Tokens.Add(kerbToken);
// Specify the security token to sign the message with.
MessageSignature sig = new MessageSignature(kerbToken);
// Add the digital signature to the SOAP message.
security.Elements.Add(sig);

  }

2 comments

Adding Security Credentials to SOAP

The 3.0 for .NET enables the developers for creating one or more security credentials that can be added to the SOAP Message.

The following procedure describes how to add one or more security credentials to a SOAP Message.A computer must be configured to accept the SOAP Messages embedded with the security credentials.

Two types of security credentials that can be setup for the computer

  1. X.509 certificate.
  2. Username and Password.

You can configure the computer for X.509 certificate by reading the  SOAP Messages signed by an X.509 Certificate.

You can also configure the computer for Username Token by validating SOAP Messages signed by Username Token.

Following procedure is To Add a security token to SOAP

1.  Open the Web Service Client project

2.Add references to the Microsoft.Web.Services3 and System.Web.Services assemblies. 

3. Add a Web Reference to the Web service that is to receive the SOAP message signed with the UsernameToken.

4. Add the folllowing user directives

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography.X509Certificates;

using Microsoft.Web.Services3;
using Microsoft.Web.Services3.Design;
using Microsoft.Web.Services3.Security;
using Microsoft.Web.Services3.Security.Tokens;

 5. Write the following code by overriding the SecureMessage Method  in web  service.

public override void SecureMessage(SoapEnvelope envelope, Security security)
{
UsernameToken userToken;
userToken = new UsernameToken(userName, userPasswordEquivalent,
    PasswordOption.SendNone);
// Adds the token to the SOAP header.
security.Tokens.Add(userToken);
}
2 comments

Verify SOAP Messages Signed using Username and Password

To validate digital signatures for incoming SOAP Messages created using Username Token, Must be configured.

The following procedure explains how to configure a to validate digital signatures created using Username Token.

1. Start Visual studio 2005

2. File Menu, New then click Project.

3. Select Web Service in  the templates pane.

4. Add a reference to the Microsoft.Web.Services3 assembly.

5. In the Web.config file include the <SoapServerProtocolFactory> element in <webServices> section.

<configuration>
   <system.web>
        <webServices>
            <soapServerProtocolFactory 
type="Microsoft.Web.Services3.WseProtocolFactory,
 Microsoft.Web.Services3,
 Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
        </webServices>
    </system.web>
   </system.web>
</configuration>

  Write the following code to validate the SOAP Message

Read more

2 comments

Next Page »