<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Code Reference &#187; Servcies</title>
	<atom:link href="http://sullivan.net/blog/tag/servcies/feed/" rel="self" type="application/rss+xml" />
	<link>http://sullivan.net/blog</link>
	<description>A collection of code for my reference (and perhaps other people too)</description>
	<lastBuildDate>Wed, 25 Jan 2012 17:53:32 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Add a POST method to the WCF service</title>
		<link>http://sullivan.net/blog/2010/06/add-post-method-to-service/</link>
		<comments>http://sullivan.net/blog/2010/06/add-post-method-to-service/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 10:54:40 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=376</guid>
		<description><![CDATA[NOTE: This continues the series from the post Read the GET request parameters in the AfterReceiveRequest() method I changed the name of the SchemeTest() method to SimpleTest() because the scheme test will be done on the POST request sending XML, not on a GET request. Here is the new interface: namespace WCFServiceWithScheme { [ServiceContract] public [...]]]></description>
			<content:encoded><![CDATA[<p>NOTE: This continues the series from the post <a href="http://sullivan.net/blog/2010/06/read-get-request-parameters-in-the-afterreceiverequest-method/">Read the GET request parameters in the AfterReceiveRequest() method</a></p>
<p>I changed the name of the SchemeTest() method to SimpleTest() because the scheme test will be done on the POST request sending XML, not on a GET request.</p>
<p>Here is the new interface:</p>
<pre class="brush: c#">
namespace WCFServiceWithScheme
{
    [ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        [WebGet(UriTemplate = &quot;SimpleTest?name={name}&quot;)]
        string SimpleTest(string name);

        [OperationContract]
        [WebInvoke(Method = &quot;POST&quot;, UriTemplate = &quot;SchemeTest&quot;,
           BodyStyle = WebMessageBodyStyle.Bare,
           RequestFormat = WebMessageFormat.Xml)]
        string SchemeTest(RequestObject theRequest);
    }
}
</pre>
<p>Here are the new public methods:</p>
<pre class="brush: c#">
namespace WCFServiceWithScheme
{
    public class TestService : ITestService
    {
        public string SimpleTest(string name)
        {
            return &quot;The name is &quot; + name;
        }

        public string SchemeTest(RequestObject theRequest)
        {
            return &quot;nothing interesting&quot;;
        }
    }
}
</pre>
<p>We have to create the simple object that will be POSTed in the request. I called it 'RequestObject'.<br />
Notice we have included a namespace in the DataContract. This will also have to be sent in the request to the service.</p>
<pre class="brush: c#">
namespace WCFServiceWithScheme
{
    [DataContract(Namespace = &quot;http://WCFServiceWithScheme&quot;)]
    public class RequestObject
    {
        [DataMember]
        public string FirstName { get; set; }
        [DataMember]
        public string LastName { get; set; }
        [DataMember]
        public short Age
        {
            get { return age; }
            set { age = value; }
        }

        private short age = 0;
    }
}
</pre>
<p>The XML submitted for this object is here. Notice the namespace is included.</p>
<pre class="brush: c#">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&gt;
&lt;RequestObject xmlns=&quot;http://WCFServiceWithScheme&quot;&gt;
     &lt;Age&gt;21&lt;/Age&gt;
     &lt;FirstName&gt;Howard&lt;/FirstName&gt;
     &lt;LastName&gt;Lumpy&lt;/LastName&gt;
&lt;/RequestObject&gt;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/06/add-post-method-to-service/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Read GET request parameters in the AfterReceiveRequest() method</title>
		<link>http://sullivan.net/blog/2010/06/read-get-request-parameters-in-the-afterreceiverequest-method/</link>
		<comments>http://sullivan.net/blog/2010/06/read-get-request-parameters-in-the-afterreceiverequest-method/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 10:11:04 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=367</guid>
		<description><![CDATA[NOTE: This continues the series from the post Expand the simple service with IDispatchMessageInspector On a GET request, the relevant data is in the parameters. Here is how to read this data: Determine the request's mothod (GET or POST) You don't know what method is called or how it was called. Get the URITemplateMatchResults Get [...]]]></description>
			<content:encoded><![CDATA[<p>NOTE: This continues the series from the post <a href="http://sullivan.net/blog/2010/06/wcf-service-with-idispatchmessageinspector/">Expand the simple service with IDispatchMessageInspector</a></p>
<p>On a GET request, the relevant data is in the parameters. Here is how to read this data:</p>
<ul>
<li>Determine the request's mothod (GET or POST)<br />
             You don't know what method is called or how it was called.</li>
<li>Get the URITemplateMatchResults</li>
<li>Get the operation name (method) that was called.</li>
<li>Get the RequestUri</li>
<li>Loop thru the Querry Parameters</li>
<li>Loop thru the Bound Variables</li>
</ul>
<p>NOTE: Any request to the service will run thru there. If you have 10 different GET and POST methods in your service, a request to any of them will go thru here before it goes to the called method.</p>
<pre class="brush: c#">
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
    // Get the request message from the request
    HttpRequestMessageProperty requestMessage = request.Properties[&quot;httpRequest&quot;] as HttpRequestMessageProperty;
    string method = string.Empty;
    if (requestMessage != null)
    {
        // The method will be GET or POST.
        method = requestMessage.Method;
    }

    // Get the UriTemplateMatchResults from the request.
    // Here you can see some of the fun things that are revealed.
    UriTemplateMatch results = internalCopy.Properties[&quot;UriTemplateMatchResults&quot;] as UriTemplateMatch;
    if (results != null)
    {
        // Get the operation name from the request.
        // Here you can see what method was called in the Service.
        // Since we have only one method (SchemeTest), it should be this.
        // We can add a simple &#039;HelloWorld&#039; method to see this value change.
        string operationName = string.Empty;
        if (results.RelativePathSegments.Count &gt; 0)
            operationName = results.RelativePathSegments[results.RelativePathSegments.Count - 1];

        //
        string requestUri = results.RequestUri.ToString();

        // If the request method is GET, then you can play with the query parameters, uri template, and bound variables
        if (method == &quot;GET&quot;)
        {

            // Loop thru the querry parameters
            NameValueCollection queryParameters = results.QueryParameters;
            foreach (var p in queryParameters)
            {
                Console.WriteLine(p);
            }

            // The Uri template is the same as in the Attribute of the interface: [WebGet(UriTemplate = &quot;SchemeTest?name={name}&quot;)]
            string template = results.Template.ToString();

            // You can loop thru the key in the variables passed in.
            NameValueCollection boundVariables = results.BoundVariables;
            foreach (string key in boundVariables.AllKeys)
            {
                // Variable names are always in UPPER case. Don&#039;t know why.
                if (key == &quot;NAME&quot;)
                    Console.WriteLine(&quot;This is the &#039;name&#039; key&quot;);
            }
        }

       Object correlationState = new object();
       return correlationState;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/06/read-get-request-parameters-in-the-afterreceiverequest-method/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>CreateBufferedCopy of request in MessageInspector of WCF Service</title>
		<link>http://sullivan.net/blog/2010/06/createbufferedcopy-of-request/</link>
		<comments>http://sullivan.net/blog/2010/06/createbufferedcopy-of-request/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 09:55:28 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=364</guid>
		<description><![CDATA[NOTE: This continues the series from Expand the simple service with IDispatchMessageInspector When your web service is called, before the request reaches the main service method, the 'AfterReceiveRequest()' method is fired. Here is where you can inspect the request. Very important to know, you must make a copy of the message because reading the original [...]]]></description>
			<content:encoded><![CDATA[<p>NOTE: This continues the series from <a href="http://sullivan.net/blog/2010/06/wcf-service-with-idispatchmessageinspector/">Expand the simple service with IDispatchMessageInspector</a></p>
<p>When your web service is called, before the request reaches the main service method, the 'AfterReceiveRequest()' method is fired.<br />
Here is where you can inspect the request.</p>
<p>Very important to know, you must make a copy of the message because reading the original message changes its State from 'created' to 'copied' and downstream processing won't work. Do this by creating a buffered copy.<br />
NOTE: This applies mostly to getting the message body from a POST request.</p>
<pre class="brush: c#">
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
    Console.WriteLine(&quot;Inside the ApplyClientBehavior&quot;);

    // Create a buffered copy of the request.
    // You can then use the internal copy to work with.
    MessageBuffer buffer = request.CreateBufferedCopy(Int32.MaxValue);
    request = buffer.CreateMessage();
    Message internalCopy = buffer.CreateMessage();
    buffer.Close();

    // Check the message state easily
    Console.WriteLine(&quot;State of message: &quot; + internalCopy.State);

    Object correlationState = new object();
    return correlationState;
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/06/createbufferedcopy-of-request/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WCF Service with IDispatchMessageInspector</title>
		<link>http://sullivan.net/blog/2010/06/wcf-service-with-idispatchmessageinspector/</link>
		<comments>http://sullivan.net/blog/2010/06/wcf-service-with-idispatchmessageinspector/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 08:13:34 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=350</guid>
		<description><![CDATA[If you want to do any pre or post inspection of a web service such as scheme validation, you can use the IDispatchMessageInspector. This example is based on the Simple Service example. I modified the Simple Service example and added the IDispatchMessageInspector. The IDispatchMessageInspector gives you access to 2 events. - AfterReceiveRequest() fires before you [...]]]></description>
			<content:encoded><![CDATA[<p>If you want to do any pre or post inspection of a web service such as scheme validation, you can use the IDispatchMessageInspector.</p>
<p>This example is based on the <a href="http://sullivan.net/blog/2009/08/wcf-simple-servcie/">Simple Service</a> example. I modified the Simple Service example and added the IDispatchMessageInspector.</p>
<p>The IDispatchMessageInspector gives you access to 2 events.<br />
 - AfterReceiveRequest() fires before you enter the web service method:<br />
   object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext) { return new Object; }<br />
 - BeforeSendReply() fires after you leave the web service method:<br />
   void BeforeSendReply(ref Message reply, object correlationState) { }</p>
<p>The object returned from the first method is the 'correlationSate' object of the 2nd method. If your custom validation fails in the first, you can return a 'correlationState' object that the 2nd method will receive automatically. This allows you to return 'Bad Request' or something like that.</p>
<p>There is nothing unusual about the Interface for the service as you can see in ITestService.cs:</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

using System.ServiceModel.Web;

namespace WCFServiceWithScheme
{
    // NOTE: If you change the interface name &quot;ITestService&quot; here, you must also update the reference to &quot;ITestService&quot; in Web.config.

    [ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        [WebGet(UriTemplate = &quot;SchemeTest?name={name}&quot;)]
        string SchemeTest(string name);
    }
}
</pre>
<p>There is also nothing unusual about the class that inherits from the interface. TestService.svc.cs:</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFServiceWithScheme
{
    public class TestService : ITestService
    {
        public string SchemeTest(string name)
        {
            return &quot;The name is &quot; + name;
        }
    }
}
</pre>
<p>The differences begin to show in the Web.config.<br />
You will see the 'behaviorExtensions' tag and the additional addition to the 'endpointBehaviors'.<br />
The name for the 'behaviorExtensions' is the new behavior in the 'endpointBehavior'.<br />
The behaviorExtensions' TYPE is the name of the BehaviorExtensionElement class followed by the namespace. </p>
<p>The system.serviceModel in the Web.confi:</p>
<pre class="brush: c#">
  &lt;system.serviceModel&gt;

    &lt;!-- Required for IDispatchMessageInspector --&gt;
    &lt;extensions&gt;
      &lt;behaviorExtensions&gt;
        &lt;add name=&quot;restHttpBehavior&quot; type=&quot;WCFServiceWithScheme.MyBehaviorExtensionElement, WCFServiceWithScheme, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&quot;/&gt;
      &lt;/behaviorExtensions&gt;
    &lt;/extensions&gt;

    &lt;bindings&gt;
      &lt;!-- Minimum for WebHttp --&gt;
      &lt;webHttpBinding&gt;
        &lt;binding name=&quot;WCFServiceWithScheme.MyDefaultBinding&quot;/&gt;
      &lt;/webHttpBinding&gt;
    &lt;/bindings&gt;

    &lt;behaviors&gt;

      &lt;!-- serviceBehaviors --&gt;
      &lt;serviceBehaviors&gt;
        &lt;behavior name=&quot;WCFServiceWithScheme.MyServiceBehavior&quot;&gt;
          &lt;serviceMetadata httpGetEnabled=&quot;true&quot; /&gt;
          &lt;serviceDebug includeExceptionDetailInFaults=&quot;false&quot; /&gt;
        &lt;/behavior&gt;
      &lt;/serviceBehaviors&gt;

      &lt;!-- endpointBehaviors --&gt;
      &lt;endpointBehaviors&gt;
        &lt;behavior name=&quot;WCFServiceWithScheme.MyWebBehavior&quot;&gt;
          &lt;webHttp/&gt;
          &lt;restHttpBehavior/&gt;
        &lt;/behavior&gt;
      &lt;/endpointBehaviors&gt;

    &lt;/behaviors&gt;

    &lt;services&gt;

      &lt;!-- Minimum for WebHttp --&gt;
      &lt;service behaviorConfiguration=&quot;WCFServiceWithScheme.MyServiceBehavior&quot; name=&quot;WCFServiceWithScheme.TestService&quot;&gt;

        &lt;!-- Minimum for WebHttp --&gt;
        &lt;endpoint address=&quot;web&quot; behaviorConfiguration=&quot;WCFServiceWithScheme.MyWebBehavior&quot; binding=&quot;webHttpBinding&quot; contract=&quot;WCFServiceWithScheme.ITestService&quot; bindingConfiguration=&quot;WCFServiceWithScheme.MyDefaultBinding&quot;&gt;
          &lt;identity&gt;
            &lt;dns value=&quot;localhost&quot;/&gt;
          &lt;/identity&gt;
        &lt;/endpoint&gt;

      &lt;/service&gt;

    &lt;/services&gt;
  &lt;/system.serviceModel&gt;
</pre>
<p>There are 2 new classes that you must create:<br />
* A MessageInspector class that inherits from IDispatchMessageInspector<br />
* A BehaviorExtensionElement class that inherits from BehaviorExtensionElement and IEndpointBehavior.</p>
<p>The MessageInspector class contains the AfterReceiveRequest and BeforeSendReply methods.<br />
Place break points in these methods and you can see the order in which they are fired.</p>
<p>The MyMessageInspector.cs class:</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel.Dispatcher;

namespace WCFServiceWithScheme
{
    public class MyMessageInspector : IDispatchMessageInspector
    {

        #region IDispatchMessageInspector Members

        public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
        {
            Console.WriteLine(&quot;Inside the ApplyClientBehavior&quot;);
            // Good idea to return error class stuff to let you know if anything happened in here
            Object correlationState = new object();
            return correlationState;
        }

        public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            // !!!!!!!!! correlationState comes from the AfterReceiveRequest method !!!!!!!!!!!!!
            // If the AfterReceiveRequest method determines it is a bad request, this is where you return, &#039;Bad Request&#039;
            Console.WriteLine(&quot;Inside the ApplyClientBehavior&quot;);
        }

        #endregion
    }
}
</pre>
<p>The BehaviorExtensionElement class contains several methods. The most important one is 'ApplyDispatchBehavior(). This is where you add your message inspector.</p>
<p>The Validate() is fired only during initialization of the service and before ApplyDispatchBehavior().<br />
To test this when running locally, do an IISreset, place a break point in the Validate() method and the other methods, and hit F5 to start debugging. </p>
<p>MyBehaviorExtensionElement.cs</p>
<pre class="brush: c#">
using System;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;

namespace WCFServiceWithScheme
{
    public class MyBehaviorExtensionElement : BehaviorExtensionElement, IEndpointBehavior
    {
        #region BehaviorExtensionElement
        public override Type BehaviorType
        {
            get { return typeof(MyBehaviorExtensionElement); }
        }

        protected override object CreateBehavior()
        {
            return new MyBehaviorExtensionElement();
        }
        #endregion

        #region IEndpointBehavior Members

        public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            Console.WriteLine(&quot;Inside the AddBindingParameters&quot;);
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
        {
            Console.WriteLine(&quot;Inside the ApplyClientBehavior&quot;);
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
        {
            Console.WriteLine(&quot;Adding custom message inspector...&quot;);
            endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new MyMessageInspector());
        }

        public void Validate(ServiceEndpoint endpoint)
        {
            Console.WriteLine(&quot;Inside the Validate&quot;);
        }

        #endregion
    }
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/06/wcf-service-with-idispatchmessageinspector/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>WCF Web Service with Scheme Validation and other tricks</title>
		<link>http://sullivan.net/blog/2010/06/wcf-web-service-with-scheme-validation-and-other-tricks/</link>
		<comments>http://sullivan.net/blog/2010/06/wcf-web-service-with-scheme-validation-and-other-tricks/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 08:12:56 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=357</guid>
		<description><![CDATA[This series of posts will cover the various aspects of creating a WCF web service that will use a scheme to validate. NOTE: This is different than the Secure WCF REST webservice I posted earlier. The previous one uses the WCF REST Starter Kit and has a very simple Web.config. This series covers: Creating a [...]]]></description>
			<content:encoded><![CDATA[<p>This series of posts will cover the various aspects of creating a WCF web service that will use a scheme to validate.</p>
<p>NOTE: This is different than the <a href="http://sullivan.net/blog/2009/12/secure-wcf-rest-part1-xml-schema-validation/">Secure WCF REST webservice</a> I posted earlier. The previous one uses the WCF REST Starter Kit and has a very simple Web.config.</p>
<p>This series covers:</p>
<ul>
<li>Creating a <a href="http://sullivan.net/blog/2009/08/wcf-simple-servcie/">Simple Service</a> based on REST</li>
<li><a href="http://sullivan.net/blog/2010/06/wcf-service-with-idispatchmessageinspector/">Expand the simple service with IDispatchMessageInspector</a></li>
<li><a href="http://sullivan.net/blog/2010/06/read-get-request-parameters-in-the-afterreceiverequest-method/">Read the GET request parameters in the AfterReceiveRequest() method</a></li>
<li><a href="http://sullivan.net/blog/2010/06/add-post-method-to-service/">Add a POST method to the service</a></li>
<li>How and why you should <a href="http://sullivan.net/blog/2010/06/createbufferedcopy-of-request/">use 'CreateBufferedCopy' to clone the request</a></li>
<li><a href="http://">Read the message body in a POST request</a></li>
<li>Loading and using the scheme</li>
<li>Dynamically expanding the UriTemplate on a Get request</li>
<li>How to optionally embed the XSD file in the assembly</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2010/06/wcf-web-service-with-scheme-validation-and-other-tricks/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Secure WCF REST webservice &#8211; part 1 &#8211; Validate XML with Schema</title>
		<link>http://sullivan.net/blog/2009/12/secure-wcf-rest-part1-xml-schema-validation/</link>
		<comments>http://sullivan.net/blog/2009/12/secure-wcf-rest-part1-xml-schema-validation/#comments</comments>
		<pubDate>Mon, 21 Dec 2009 11:31:53 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Serialization]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=243</guid>
		<description><![CDATA[I have spent a good amount of time workig to implement a good XML validation method. I followed may leads and ended with a simple solution. My goals were: * use WCF/REST * Use a Schema to validate the incoming XML request * Extend the deserialize method turn prohibit DTDs and to disable external entities [...]]]></description>
			<content:encoded><![CDATA[<p>I have spent a good amount of time workig to implement a good XML validation method. I followed may leads and ended with a simple solution.</p>
<p><strong>My goals were:</strong><br />
* use WCF/REST<br />
* Use a Schema to validate the incoming XML request<br />
* Extend the deserialize method turn prohibit DTDs and to disable external entities<br />
* Filter IPs based on a list in the Config file<br />
* Use the newer WebServiceHost2 from the WCF REST Starter Kit</p>
<p><strong>Problems I had:</strong><br />
* I tried extending IDispatchMessageInspector and IClientMessageInspector to add schema validation. This worked great on WS Services (wsHttpBinding), but I could not get it to work on WebServices (webHttpBinding). I could not find any exampels of working solution on the net on how to do this with web services. (here is the blog post on what I did come up with). I abandoned this approach.</p>
<p>* Schema validation is done on the xml before it is derialized or when it is deserialized to an object. Because I could not access the deserialization before accepting the incoming xml request, I was forced to have the incoming object type 'XElement' rather than the destination object.</p>
<p><strong>My solution:</strong><br />
* I used the new WCF REST Starter Kit. This reduces the confit file to almost nothing. The endpoints are set automatically. All adjustments can be done thru attributes on the service method itself.</p>
<p>Here is my config file:</p>
<pre class="brush: c#">
&lt;?xml version=&quot;1.0&quot;?&gt;
&lt;configuration&gt;
  &lt;appSettings&gt;
     ...
  &lt;/appSettings&gt;

  &lt;system.web&gt;
		&lt;compilation debug=&quot;true&quot;/&gt;
  &lt;/system.web&gt;

  &lt;system.serviceModel&gt;
		&lt;serviceHostingEnvironment aspNetCompatibilityEnabled=&quot;true&quot;/&gt;
  &lt;/system.serviceModel&gt;
&lt;/configuration&gt;
</pre>
<p>My Service:</p>
<pre class="brush: c#">
// The following line sets the default namespace for DataContract serialized typed to be &quot;&quot;
[assembly: ContractNamespace(&quot;&quot;, ClrNamespace = &quot;ThisIsMyService&quot;)]

namespace ThisIsMyService
{
    // TODO: Please set IncludeExceptionDetailInFaults to false in production environments
    [ServiceBehavior(IncludeExceptionDetailInFaults = true), AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed), ServiceContract]
    public partial class Service
    {
        [WebHelp(Comment = &quot;This is my service&quot;)]
        [WebInvoke(UriTemplate = &quot;MyService&quot;)]
        [OperationContract]
        public XElement MyService(XElement requestXml)
        {
            // Schema validation and deserialization are both done at the same time.
            // If there is a problem, null is returned and an exception is thrown with a HTTPStatusCode of Bad Request.
            var validatedObject = Helper.XmlToObject(requestXml, typeof(RequestObject),
                ConfigurationManager.AppSettings[&quot;SchemaPath&quot;].ToString(),
                ConfigurationManager.AppSettings[&quot;SchemaNamespace&quot;].ToString());

            // I do all the process and other work in the helper class to keep this clean.
            if (validatedObject is RequestObject)
                return new Helper().DoStuff((RequestObject)validatedObject);

            // If there is problem validating the incoming request XML, then the validated object will be null
            // Error validating request - return nothing
            return new XElement(&quot;root&quot;);
        }
    }
}
</pre>
<p>My service is very basic. All the logic is done in the helper class.</p>
<p>My helper class contains the static validation XMLtoObject method and the methods for doing the work of the service.</p>
<p>When you deserialize XML to an object, you can add a schema that will be used to check the XML.<br />
What you don't easily find in the documentation, is the fact that the Schema must be read and validated before it can be added to the reader that reads and deserializes the incoming xml request.</p>
<pre class="brush: c#">
public class EngineServiceHelper
{
    /// &lt;summary&gt;
    /// A schema is an XML file like all the rest.
    /// It also must be loaded and deserialized.
    /// To use a schema, it must be placed in a XmlSchemaSet.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;xml&quot;&gt;&lt;/param&gt;
    /// &lt;param name=&quot;DestinationType&quot;&gt;&lt;/param&gt;
    /// &lt;param name=&quot;schemaPath&quot;&gt;&lt;/param&gt;
    /// &lt;param name=&quot;xmlNamespace&quot;&gt;&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    public static object XmlToObject(XElement xml, Type DestinationType, string schemaPath, string xmlNamespace)
    {
        ErrorMessage = string.Empty;
        ErrorsCount = 0;

        XmlSchemaSet schemaSet = new XmlSchemaSet();
        schemaSet.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);
        schemaSet.Add(xmlNamespace, schemaPath);

        if (schemaSet.Count &gt; 0)
        {
            try
            {
                // Set the setting for reading the Schema file
                XmlReaderSettings schemaSettings = new XmlReaderSettings();
                schemaSettings.ValidationType = ValidationType.Schema;
                schemaSettings.Schemas.Add(schemaSet);
                // To make the service more secure and prevent XML Bombs and such, disable DTDs
                xmlRequestSettings.ProhibitDtd = true;
                // Limit the size of the elements - 1024 = 1Kb
                schemaSettings.MaxCharactersFromEntities = 1024;
                // Adding the validation event handler prevents validation errors from throwing an exception.
                // We want to control when and how an exception is thrown.
                schemaSettings.ValidationEventHandler += new ValidationEventHandler(settings_ValidationEventHandler);
                // create the reader for reading the schema
                XmlReader schemaReader = XmlReader.Create(xml.CreateReader(), schemaSettings);

                // Set the settings for reading the incoming XML request
                XmlReaderSettings xmlRequestSettings = new XmlReaderSettings();
                // To make the service more secure and prevent XML Bombs and such, disable DTDs
                xmlRequestSettings.ProhibitDtd = true;
                // Limit the size of the elements - 1024 = 1Kb
                schemaSettings.MaxCharactersFromEntities = 1024;
                // Create the reader for reading the XML request.
                XmlReader xmlReader = XmlReader.Create(schemaReader, xmlRequestSettings);

                // Deserialize the XML to an object
                XmlSerializer serializer = new XmlSerializer(DestinationType, xmlNamespace);
                object returnObject = serializer.Deserialize(xmlReader);

                // If there are errors, throw an exception
                if (ErrorsCount &gt; 0)
                    throw new Exception(ErrorMessage);

                // If ther are no problems, return the deserialized object
                return returnObject;
            }
            catch (Exception ex)
            {
                // Using the WebProtocolException in the WCF REST Starter Kit, you can throw
                // and exception and choose the HTTPStatusCode that will be displayed to the end user.
                throw new WebProtocolException(HttpStatusCode.BadRequest, &quot;Your XML is invalid: &quot; + ex.Message, null);
            }
        }
        return null;
    }

    /// &lt;summary&gt;
    /// Check the error severity and create the error message.
    /// Increment the error counter.
    /// &lt;/summary&gt;
    /// &lt;param name=&quot;sender&quot;&gt;&lt;/param&gt;
    /// &lt;param name=&quot;e&quot;&gt;&lt;/param&gt;
    public static void settings_ValidationEventHandler(object sender, ValidationEventArgs e)
    {
        if (e.Severity == XmlSeverityType.Error)
        {
            ErrorMessage = &quot;ERROR: &quot; + ErrorMessage + e.Message + &quot;\r\n&quot;;
            ErrorsCount++;
        }
        else
        {
            ErrorMessage = &quot;WARNING: &quot; + ErrorMessage + e.Message + &quot;\r\n&quot;;
            ErrorsCount++;
        }
    }
}
</pre>
<p>The validation event handler allows you to catch the validation errors and handle them yourself.<br />
I am checking the error severity and returning a message that reflects it.</p>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2009/12/secure-wcf-rest-part1-xml-schema-validation/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Object serialization for a WCF DataContact</title>
		<link>http://sullivan.net/blog/2009/10/object-serialization-for-wcf-data-contract/</link>
		<comments>http://sullivan.net/blog/2009/10/object-serialization-for-wcf-data-contract/#comments</comments>
		<pubDate>Fri, 09 Oct 2009 13:22:25 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Serialization]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=193</guid>
		<description><![CDATA[The object you use for your WCF Data Contract should be simple. By default the only Attribute requried is '[DataMember]' on the properties and '[DataContract]' on the class. These attributes define how the object will be serialized. The serialization is VERY important. If your serialization is not correct, you will get unpredictable behavior. Some of [...]]]></description>
			<content:encoded><![CDATA[<p>The object you use for your WCF Data Contract should be simple. By default the only Attribute requried is '<strong>[DataMember]</strong>' on the properties and '<strong>[DataContract]</strong>' on the class.</p>
<p>These attributes define how the object will be serialized. The serialization is VERY important.</p>
<p>If your serialization is not correct, you will get unpredictable behavior. Some of the problems I experienced was values not being passed into the object from the xml string, exceptions thrown when the order is not correct or incorrect default values entered.</p>
<p>The most important items I found were<br />
* order (alphabetical)<br />
* root element attributes (<myRootNode xmlns="http://schemas.datacontract.org/2004/07/myNamespaceForMyService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">)<br />
* zero default for int values ('<myId>0</myId>')<br />
* represent all possible values, even if they are not used ('<node></node>' vs '<node/>' does not make a difference until it is an int/numeric/etc.)</p>
<p>Some of these are no-brainers. But the order? Why should the order matter when the DataMember attributes don't specify an order? It does and there seems to be no reason why.</p>
<p>Here is my object:</p>
<pre class="brush: c#">
[DataContract]
public sealed class InputXMLObject
{
    // Required
    [DataMember(IsRequired = true)]
    public string Language { get; set; }
    [DataMember(IsRequired = true)]
    public string Name { get; set; }
    [DataMember(IsRequired = true)]
    public int MyId { get; set; }

    // Optional
    [DataMember(IsRequired = false, EmitDefaultValue = true)]
    public string SomeThing { get; set; }
    [DataMember(IsRequired = false, EmitDefaultValue = true)]
    public string SomethingElse { get; set; }
    [DataMember(IsRequired = false, EmitDefaultValue = true)]
    public string Timestamp { get; set; }
}
</pre>
<p>I serialized it with this nifty little method. I like it because it is generic. The most important part about it that it uses System.Runtime.Serialization.DataContractSerializer. I found this method on <a href="https://msmvps.com/blogs/peterritchie/archive/2009/05/04/unit-testing-wcf-data-contract-serialization.aspx">Peter Ritchie's blog</a>.</p>
<pre class="brush: c#">
public static string ContractObjectToXml&lt;T&gt;(T obj)
{
    DataContractSerializer dataContractSerializer = new DataContractSerializer(obj.GetType());
    String text;
    using (MemoryStream memoryStream = new MemoryStream())
    {
        dataContractSerializer.WriteObject(memoryStream, obj);
        byte[] data = new byte[memoryStream.Length];
        Array.Copy(memoryStream.GetBuffer(), data, data.Length);
        text = Encoding.UTF8.GetString(data);
    }
    return text;
}
</pre>
<p>After serialization, the object looked like this:</p>
<pre class="brush: c#">
&lt;InputXMLObject2 xmlns=&quot;http://schemas.datacontract.org/2004/07/MyService&quot; xmlns:i=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&gt;&lt;Language&gt;UK&lt;/Language&gt;&lt;MyId&gt;5&lt;/MyId&gt;&lt;Name&gt;Billy&lt;/Name&gt;&lt;SomeThing i:nil=&quot;true&quot;/&gt;&lt;SomethingElse i:nil=&quot;true&quot;/&gt;&lt;Timestamp i:nil=&quot;true&quot;/&gt;&lt;/InputXMLObject2&gt;
</pre>
<p>I made it a bit more simple (the ' i:nil="true"' is not necessary):</p>
<pre class="brush: c#">
&lt;InputXMLObject xmlns=&quot;http://schemas.datacontract.org/2004/07/EMyService&quot; xmlns:i=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&gt;
	&lt;Language&gt;UK&lt;/Language&gt;
	&lt;MyId&gt;5&lt;/MyId&gt;
	&lt;Name&gt;Billy&lt;/Name&gt;
	&lt;SomeThing&gt;&lt;/SomeThing&gt;
	&lt;SomethingElse&gt;&lt;/SomethingElse&gt;
	&lt;Timestamp&gt;&lt;/Timestamp&gt;
&lt;/InputXMLObject&gt;
</pre>
<p>My interface:</p>
<pre class="brush: c#">
[ServiceContract]
public interface IEngineService
{
    [OperationContract]
    string MyServiceMethod(InputXMLObject inputXMLObject);
}
</pre>
<p>The class:</p>
<pre class="brush: c#">
public class EngineService : IEngineService
{
	public string MyServiceMethod(InputXMLObject inputXMLObject)
	{
           // do something
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2009/10/object-serialization-for-wcf-data-contract/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>WCF &#8211; Simple servcie</title>
		<link>http://sullivan.net/blog/2009/08/wcf-simple-servcie/</link>
		<comments>http://sullivan.net/blog/2009/08/wcf-simple-servcie/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 14:12:26 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=123</guid>
		<description><![CDATA[There several steps to set up a WCF service. You first add a WCF service to your project. I am using a simple project called 'SandboxWebsite'. When you add the WCF service, it will create 3 files (I chose the name TestService): * ITestService.cs // the interface * TestService.cs // the service method * TestService.svc [...]]]></description>
			<content:encoded><![CDATA[<p>There several steps to set up a WCF service. You first add a WCF service to your project. I am using a simple project called 'SandboxWebsite'.<br />
When you add the WCF service, it will create 3 files (I chose the name TestService):<br />
* ITestService.cs   // the interface<br />
* TestService.cs    // the service method<br />
* TestService.svc    // the service that is called (just a placeholder file)</p>
<p>First the interface for the service (ITestService.sc).<br />
The interface has the 'ServiceContract' interface.<br />
The service method has the 'OperationContract'.<br />
You will notice the attribute 'WebGet()'. This specifies the service will be accessed via GET. (This uses the class System.ServiceModel.Web - it must be added as a reference as well. Confirm also that System.ServiceModel has also been added and is incuded in the 'Using' list).</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel.Web;

namespace WCFService
{
    [ServiceContract]
    public interface ITestService
    {
        [OperationContract]
        [WebGet()]
        string Hello();
    }
}
</pre>
<p>Then the actual service itself (TestService.cs):</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCFService
{
    public class TestService : ITestService
    {
        public string Hello()
        {
            return &quot;Hello world&quot;;
        }
    }
}
</pre>
<p>The file TestService.svc contains only placholder info:</p>
<blockquote><p><%@ ServiceHost Language="C#" Debug="true" Service="TestService" CodeBehind="~/App_Code/TestService.cs" %></p></blockquote>
<p>That was the easy part.<br />
Now for the Web.config file.<br />
All additions go under '<system.serviceModel>'</p>
<p>The 4 additions are:<br />
* binding<br />
* service behavior<br />
* endpoint behaviors<br />
* endpoint</p>
<p>Our service uses 'webHttpBinding' service. Other binding types are 'wsHttpBinding' and 'mexHttpBinding' (not covered here... yet...)</p>
<p>The web.config settings</p>
<pre class="brush: c#">
   &lt;system.serviceModel&gt;

    &lt;bindings&gt;
      &lt;!-- Minimum for WebHttp --&gt;
      &lt;webHttpBinding&gt;
        &lt;binding name=&quot;WCFService.MyDefaultBinding&quot;/&gt;
      &lt;/webHttpBinding&gt;
    &lt;/bindings&gt;

    &lt;behaviors&gt;

      &lt;!-- serviceBehaviors --&gt;
      &lt;serviceBehaviors&gt;
        &lt;behavior name=&quot;WCFService.MyServiceBehavior&quot;&gt;
          &lt;serviceMetadata httpGetEnabled=&quot;true&quot; /&gt;
          &lt;serviceDebug includeExceptionDetailInFaults=&quot;false&quot; /&gt;
        &lt;/behavior&gt;
      &lt;/serviceBehaviors&gt;

      &lt;!-- endpointBehaviors --&gt;
      &lt;endpointBehaviors&gt;
        &lt;behavior name=&quot;WCFService.MyWebBehavior&quot;&gt;
          &lt;webHttp/&gt;
        &lt;/behavior&gt;
      &lt;/endpointBehaviors&gt;

    &lt;/behaviors&gt;

    &lt;services&gt;

      &lt;!-- Minimum for WebHttp --&gt;
      &lt;service behaviorConfiguration=&quot;WCFService.MyServiceBehavior&quot; name=&quot;WCFService.TestService&quot;&gt;

        &lt;!-- Minimum for WebHttp --&gt;
        &lt;endpoint address=&quot;web&quot; behaviorConfiguration=&quot;WCFService.MyWebBehavior&quot; binding=&quot;webHttpBinding&quot; contract=&quot;WCFService.ITestService&quot; bindingConfiguration=&quot;WCFService.MyDefaultBinding&quot;&gt;
          &lt;identity&gt;
            &lt;dns value=&quot;localhost&quot;/&gt;
          &lt;/identity&gt;
        &lt;/endpoint&gt;

      &lt;/service&gt;

    &lt;/services&gt;
  &lt;/system.serviceModel&gt;
</pre>
<p>How do I call it?</p>
<p>This service is set up to be called via GET, so it is easy. (your localhost port may be different)</p>
<blockquote><p>http://localhost:3041/SandboxWebsite/TestService.svc/Web/Hello</p></blockquote>
<p>This returns:</p>
<blockquote><p><string>Hello world</string></p></blockquote>
<p>To call this in code, it is almost as easy.<br />
Create a HTTPWebRequest. Pass in the URL. Specify the Method as GET. Get the response stream. Read the respons stream to the end and you have it.</p>
<pre class="brush: c#">
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(&quot;http://localhost:3041/SandboxWebsite/TestService.svc/Web/Hello&quot;);
request.Method = &quot;GET&quot;;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string s = reader.ReadToEnd();
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2009/08/wcf-simple-servcie/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\ Temporary ASP.NET Files</title>
		<link>http://sullivan.net/blog/2009/08/cwindowsmicrosoft-netframeworkv2-0-50727temporary-asp-net-files/</link>
		<comments>http://sullivan.net/blog/2009/08/cwindowsmicrosoft-netframeworkv2-0-50727temporary-asp-net-files/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 13:36:48 +0000</pubDate>
		<dc:creator>Darren</dc:creator>
				<category><![CDATA[c#]]></category>
		<category><![CDATA[Servcies]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://sullivan.net/blog/?p=116</guid>
		<description><![CDATA[If you don't know this directory, you have not yet worked much with VisualStudio and WCF (windows communication foundation). C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files Microsoft screwed up again. The temporary asp.net files are not being overwritten by newer version when necessary. While working with WCF services, I doscovered at least 30% of the time I had to [...]]]></description>
			<content:encoded><![CDATA[<p>If you don't know this directory, you have not yet worked much with VisualStudio and WCF (windows communication foundation).</p>
<blockquote><p>C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files</p></blockquote>
<p>Microsoft screwed up again. The temporary asp.net files are not being overwritten by newer version when necessary. While working with WCF services, I doscovered at least 30% of the time I had to manually delete the folder associated with my project. </p>
<p>However, do delete that temporary folder, I had to close Visual Studio. F@*K Microsoft! You all should know how long VS takes to close and open. Not nice.</p>
<p>Here is the error message that I have learned to hate (on my local Dutch langauge computer):</p>
<blockquote><p>Kan bestand of assembly App_Web_pjcv_bjk, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null of een van de afhankelijkheden hiervan niet laden. Het systeem kan het opgegeven bestand niet vinden.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://sullivan.net/blog/2009/08/cwindowsmicrosoft-netframeworkv2-0-50727temporary-asp-net-files/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

