Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating a REST WCF Service From an Existing XSD Schema

DZone's Guide to

Creating a REST WCF Service From an Existing XSD Schema

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

A reader of my blog sent me an email asking the following question:

“I have an XSD that I am required to use to export my company's data. How can I use that XSD and return data to them in a web method? I should be able to return a data set with the information formatted the way the XSD defines but I have no idea how to do that. Any ideas would save me a ton of time and grief!”

Turns out this is a really good question, and I think one a lot of developers struggle with primarily because the majority of developers are scared of XSD schemas.  Hopefully I can change that.  An XML Schema is really simple and it is your friend. 

What is an XSD or Xml Schema Definition?

An XML Schema describes the structure of an XML document.

That’s it, see, it isn’t that hard after all!

As a developer think of an XSD the same way you would when creating business rules to validate objects before storing them into a database.  Some items in objects cannot be null, some can.  Some need to have their data formatted (email address for example) and others need to not exceed certain lengths, etc. 

When dealing with an XML document, we need to apply the same type of rules and this is where the XSD comes in.  Once we have an XSD to describe an XML document we can guarantee any XML data we receive conforms to these rules.

Ok, enough intro, let’s get coding.

The Schema

In the case of the reader’s question, an XSD schema already existed.  To save time, I’ve taken then general idea of the schema I was sent and slimmed it down for simplicity sakes.  The schema represents an XML document that will contain job listings. Here is a view of the schema from the schema explorer in Visual Studio as well as the schema itself (again slimmed down).

<xsd:schema
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://keithelder.net/Jobs"
xmlns:xs="http://keithelder.net/Jobs">

<xsd:complexType name="JobListing">
<xsd:sequence>
<xsd:element maxOccurs="unbounded" minOccurs="1" name="job" type="xs:Job" />
</xsd:sequence>
</xsd:complexType>

<xsd:complexType name="Job">
<xsd:sequence>
<xsd:element maxOccurs="1" minOccurs="1" name="Title" type="xsd:string"></xsd:element>
<xsd:element maxOccurs="1" minOccurs="1" name="Description" type="xsd:string"></xsd:element>
<xsd:element maxOccurs="1" minOccurs="1" name="Location" type="xs:Address"></xsd:element>
<xsd:element minOccurs="0" maxOccurs="1" name="PostingDate" type="xsd:date"></xsd:element>
<xsd:element minOccurs="0" maxOccurs="1" name="CloseDate" type="xsd:date"></xsd:element>
<xsd:element minOccurs="0" maxOccurs="1" name="Benefits" type="xsd:string"></xsd:element>
<xsd:element maxOccurs="1" minOccurs="1" name="Salary" type="xsd:string"></xsd:element>
<xsd:element maxOccurs="1" minOccurs="0" name="JobType" type="xs:JobType"></xsd:element>
<xsd:element minOccurs="0" maxOccurs="1" name="Function" type="xs:JobFunction"></xsd:element>
<xsd:element minOccurs="0" maxOccurs="1" name="Category" type="xs:JobCategory"></xsd:element>
</xsd:sequence>
</xsd:complexType>

<xsd:simpleType name="JobType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="full-time"></xsd:enumeration>
<xsd:enumeration value="part-time"></xsd:enumeration>
<xsd:enumeration value="contractor"></xsd:enumeration>
</xsd:restriction>
</xsd:simpleType>

<xsd:complexType name="Address">
<xsd:sequence>
<xsd:element minOccurs="0" maxOccurs="1" name="Street" type="xsd:string"></xsd:element>
<xsd:element minOccurs="0" maxOccurs="1" name="City" type="xsd:string"> </xsd:element>
<xsd:element minOccurs="0" maxOccurs="1" name="Country" type="xsd:string"></xsd:element>
</xsd:sequence>
</xsd:complexType>

<xsd:simpleType name="JobCategory">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="Automotive"/>
<xsd:enumeration value="Banking"/>
<xsd:enumeration value="Construction"/>
<xsd:enumeration value="Internet"/>
<xsd:enumeration value="Retail"/>
<xsd:enumeration value="Services"/>
</xsd:restriction>
</xsd:simpleType>

<xsd:simpleType name="JobFunction">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="Chief Peanut Butter Spreader"/>
<xsd:enumeration value="I ran the whole ship"/>
<xsd:enumeration value="Other"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>

Once we have a schema defined like this we can generate code to be used for a service.  We have a tool at our disposal that is available within the Visual Studio Command Prompt called XSD.exe.  This executable does a lot of things but one thing it can do is generate code from an XML Schema Definition. 

When generating from the XSD file I was sent there was a problem with it.  Here is the walk through of that story so you can follow along.

When I first tried this on the reader’s original XSD I got an error:

Warning: cannot generate classes because no top-level elements with complex type were found.

What does this mean?  Well, look at the screen shot of the XML Schema Explorer above.  Do you see the <> green icons?  Well those represent an XML Element.  An element is a fancy name for an XML tag like:  <Cows>Bramar</Cows> 

Let me roll this up and take another screen shot so you can start to see the problem (i have to hit my magic number of 12 screen shots anyway :) ).

See the problem?  There isn’t an element in this schema (no green <> thingy).  What this means is we have a schema which just lists complex types of elements and enumerations.  There isn’t any “xml” in this schema.  The fix is simple though.  Add an element to the schema.

<xsd:element name="JobListing" type="xs:Job" />

Now we have a green thingy icon which means this XSD contains at least one element.  Basically think of the JobListing element as the root element.

Now that we have an element we can generate a C# class file from this XSD:

The code generated is about 350 lines so I’m not going to include it in the article.  There are some nice things happening for us when the C# classes are generated using xsd.exe. For starters the enumerations in the XSD are turned into C# enumerations.  The classes are marked serializable and they have the appropriate XML attributes on the properties to serialize these objects into XML.  This is a good thing since it means we didn’t have to create it.  Code generation is your friend.  Now that we have C# objects we can serialize these to XML easily. 

The Service

The first thing we need to do is create the WCF service.  For this example I chose to create a WCF Service Application in Visual Studio 2008.  After the project is initialized, the first thing we need to do is define the contract for the service.  In other words, what is coming in and going back out.  Since we have generated our code using the XSD utility we are going to use the XmlSerializer with our service.  The reason is this will make sure our XML formatted the way we intended.  While we are at it, I’ve made the service a RESTful type of service.  Here is the contract.

[ServiceContract]
public interface IJobService
{

[OperationContract]
[XmlSerializerFormat]
[System.ServiceModel.Web.WebGet(UriTemplate="/jobs/{type}", RequestFormat=WebMessageFormat.Xml)]
List<Job> GetJobListings(string type);
}

The contract above has one method GetJobListings().  This method has two additional attributes.  One, the attribute to mark the method to serialize using the XmlSerializer and two the attribute to turn the method into a RESTful service.  In other words our service can be accessed like this:

http://localhost/service.svc/jobs/full-time

Now that the contract is setup, we just need a class to implement this contract on.  Here’s a quick and dirty implementation.

public class Service1 : IJobService
{

#region IJobService Members

public List<Job> GetJobListings(string type)
{
return GetJobs();
}

private static List<Job> GetJobs()
{
var jobs = new List<Job>();
jobs.Add(new Job { JobType= JobType.parttime, Category = JobCategory.Banking, Benefits= "You are on your own.", Description="I did something" });
jobs.Add(new Job { JobType= JobType.fulltime, Category = JobCategory.Banking, Benefits= "You get something." });
jobs.Add(new Job { JobType= JobType.contractor, Category = JobCategory.Banking, Benefits= "Times are tuff, deal with it." });
jobs.Add(new Job { JobType= JobType.fulltime, Category = JobCategory.Banking, Benefits= "How does $700 billion sound?" });
return jobs;
}
#endregion
}

Now all we have left is to get this working is to configure WCF to support our RESTful implementation.  In order to do this we are going to use the webHttpBinding.  Here is the WCF configuration to implement our RESTful service.

<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="rest" />
</webHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="WcfService1.Service1Behavior"
name="WcfService1.Service1">
<endpoint address="mex" binding="mexHttpBinding" name="wsdl"
contract="IMetadataExchange" />
<endpoint address="" behaviorConfiguration="NewBehavior" binding="webHttpBinding"
bindingConfiguration="" name="web" contract="WcfService1.IJobService" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="NewBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="WcfService1.Service1Behavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

That’s it, we are all setup.  Now all we have to do is launch the service and browse to the URL we outlined earlier to get our results.

This may seem like a lot of steps but it really isn’t.  I encourage you to take this example and play with it.  You can download the solution below.

Download Solution WcfService.zip

 

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:

Published at DZone with permission of Keith Elder. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}