<?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>ENTech Solutions</title>
	<atom:link href="http://www.entechsolutions.com/feed" rel="self" type="application/rss+xml" />
	<link>http://www.entechsolutions.com</link>
	<description>Just another WordPress site</description>
	<lastBuildDate>Mon, 20 Feb 2012 04:30:52 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1</generator>
		<item>
		<title>WebHooks and WebSockets in ASP.NET</title>
		<link>http://www.entechsolutions.com/hooks-and-sockets-for-web-apps?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=hooks-and-sockets-for-web-apps</link>
		<comments>http://www.entechsolutions.com/hooks-and-sockets-for-web-apps#comments</comments>
		<pubDate>Thu, 16 Feb 2012 18:42:21 +0000</pubDate>
		<dc:creator>sarah</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[HTML5]]></category>
		<category><![CDATA[WebHook]]></category>
		<category><![CDATA[WebSocket]]></category>

		<guid isPermaLink="false">http://www.entechsolutions.com/?p=423</guid>
		<description><![CDATA[Responding to a third party event in a browser One hurdle developers face when dealing with browsers is that once a page is loaded, we are done. If we want to get new data to the client we need to initiate a new request from the browser. AJAX helps us but it is not usually ...]]></description>
			<content:encoded><![CDATA[<div>
<h3>Responding to a third party event in a browser</h3>
<div><span>One hurdle developers face when dealing with browsers is that once a page is loaded, we are done. If we want to get new data to the client we need to initiate a new request from the browser. AJAX helps us but it is not usually ideal to continually poll a server to check for new information. With the advent of the <b><a target="_blank" href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-09">HTML5 WebSocket</a></b> protocol, we can push data from the server to the client to alert the browser when something happens server side.</p>
<p>Taking this a step further, a browser can respond to an event that happens on some third party server  by taking advantage of <b><a href="http://wiki.webhooks.org/" target="_blank">WebHooks</a></b>. This article discusses how this might be achieved using ASP.NET.<br />
</span></div>
<div>&nbsp;</div>
<h2><span>WebHook</span></h2>
<blockquote><p>&#8220;The concept of a WebHook is simple. A WebHook is an HTTP callback: an HTTP POST that occurs when something happens; a simple event-notification via HTTP POST.&#8221; -<a href="http://wiki.webhooks.org/" target="_blank">http://wiki.webhooks.org</a></p></blockquote>
<div>Using WebHooks, you can request event notification from some third party by supplying a callback url. The WebHook provider will post information to your callback url whenever something happens. This way you don&#8217;t have to periodically, or worse, constantly, poll the third party to ask if anything has happened. <span>It is a super simple concept with powerful implications.</span></div>
<div><span><br />
	When an event occurs, a WebHook provider will gather 3 pieces of information to send to a client:</span></div>
<ul style="margin-left: 40px;">
<li><strong>event_type</strong> : ex: &#8220;product_added&#8221;, customer_created&#8221; or &#8220;appointment_booked&#8221;.</li>
<li><strong>event_source</strong>: This describes where the event was initiated.</li>
<li><strong>data</strong>: Information about the event that occurred. This should include a timestamp and a unique identifier.</li>
</ul>
<div><br/> What the client does with this information is, of course, entirely up to the client. It can update a database, store the data in a cache, post the data to the cloud, email the data to your congressman, etc. The options are limited only by your imagination! The power of WebHooks lies in what the client does with the data it receives. If the client doesn&#8217;t do anything <em>useful</em>, there&#8217;s not much power to it.</div>
<div><span></p>
<p>	<b>Here is an example of a WebHook provider implementation in C#.</b></span></div>
<div><span>In this example I gather the relevant data into an object called an &#8220;Event&#8221;, serialize it to JSON, and post it to the callback urls. </span></div>
<div>
<pre class="brush: csharp; title: ; notranslate">

// This method should be called after any event occurs
public Event OnEventOccurred(EventType eventType, EventSource eventSource, object data)
{
	var e = RecordEvent(eventType, eventSource, data);
	PostToClients(e);
	return e;
}

//  Record event with a unique identifier and timestamp
private static Event RecordEvent(EventType eventType, EventSource eventSource, object data)
{
	var e = new Event()
			    {
			        ID = Guid.NewGuid(),
			        EventType = eventType.ToString(),
			        EventSource = eventSource.ToString(),
			        Data = data,
			        TimeStamp = DateToTimeStamp(DateTime.Now.ToUniversalTime())
			    };

	e.Save();
	return e;
}

// This method serializes the event data into JSON and posts to the callback urls
private void PostToClients(Event e)
{
	JavaScriptSerializer ser = new JavaScriptSerializer();
	string postData = ser.Serialize(e);

	// Retrieve list of callback urls
	var subscribers = GetWebHookClients(e);
	foreach (var subscriber in subscribers)
	{
		MakeHttpRequest(subscriber.CallBackUrl, postData);
	}
}

private void MakeHttpRequest(string callbackUrl, string data)
{
	var uri = new Uri(callbackUrl);

	var req = (HttpWebRequest)WebRequest.Create(uri);
	req.KeepAlive = true;
	req.Method = &quot;POST&quot;;
	Stream reqStream = req.GetRequestStream();

	if (data != null)
	{
		byte[] reqBytes = Encoding.UTF8.GetBytes(data);
		reqStream.Write(reqBytes, 0, reqBytes.Length);
	}

	reqStream.Close();
	reqStream.Close();
	WebResponse res = req.GetResponse();
	StreamReader read = new StreamReader(res.GetResponseStream());
	string fullResponse = read.ReadToEnd();
}
</pre>
</div>
<div><span>Now that we have a WebHook provider, we need a client.<br />
</span></div>
<div><span><br />
<b>Here is an example of a </span>WebHook Client<span> using a RESTful WCF service.</b><br />
You will see from the code that a client is just an endpoint that receives data and does something with it.<br />
<br/>The resulting callback url from this code will be <a href="http://localhost:53927/WebHookListenerService.svc/listen" target="_blank"> http://localhost:53927/WebHookListenerService.svc/listen</a>.<br />
<br/>In this example, the listener just saves the data to a text file when it receives it.  In a real world application, I would probably want to store this data in a distributed cache so the app can share the data with another app.  Also, since WebHooks are meant to find out about things that are happening <i>now</i>, a caching mechanism in which the data expires makes sense.</span></div>
<div><span><br />This is the WCF service contract:</span></div>
<pre class="brush: csharp; title: ; notranslate">
[ServiceContract]
public interface IWebHookListenerService
{
	[WebInvoke(Method = &quot;POST&quot;,
	BodyStyle = WebMessageBodyStyle.Bare,
	RequestFormat = WebMessageFormat.Json,
	ResponseFormat = WebMessageFormat.Json,
	UriTemplate = &quot;/listen&quot;)]
	void Receive(Stream postedData);
}
</pre>
<p><br/></p>
<div><span>And the implementation:</span></div>
<pre class="brush: csharp; title: ; notranslate">
public class WebHookListenerService : IWebHookListenerService
{
	// Endpoint to receive data posted by a webhook server
	public void Receive(Stream postedData)
	{
		string data = new StreamReader(postedData).ReadToEnd();
		if (String.IsNullOrEmpty(data)) return;

		DoSomethingWithTheData(data);
	}

	// Do something with incoming messages.
	// For demo, we will simply persist them to a file.
	private void DoSomethingWithTheData(string jsonData)
	{
		FileDataStore.StoreMessage(jsonData);
	}
}
</pre>
<div><span><br />
	<br />
	This is very nice, but I haven&#8217;t done anything useful with the information I received from the WebHook.  I just wrote it to a file.</span></div>
<div><span><br />
	For a web based application, I want do something in a <em>web browser</em> when an event occurs.</span></div>
<div><span>The problem is, now that I have been notified that an event has occurred, how do I notify a browser?</span></div>
<div><span><br/>This is where WebSockets can help.</p>
<p></span></div>
<h2>WebSocket</h2>
<blockquote><p>
The WebSocket Protocol is essentially an independent <strong>TCP-based protocol </strong>where a connection is established between a client/browser and a server and then both sides can send data back and forth without a new handshake.
</p></blockquote>
<div>This means we can open a connection from a browser to the server and, once the connection is established, the server can begin to push messages to the client at will. Then the browser can do something when it receives a new message such as show something on the screen, play a ringtone, etc.</div>
<div><span></p>
<p>	For a browser to initiate a websocket connection to a server, it sends an HTTP request with the following headers: </span></div>
<div style="margin-left:10px"><span>&#8220;Connection:Upgrade&#8221;</span></div>
<div style="margin-left:10px"><span>&#8220;Upgrade:WebSocket&#8221;</span></div>
<div>
	<br />
	The server will respond with a status code &#8220;101 Switching Protocols&#8221;.<br />
This is sample of the request and response:</div>
<div><span>	<br /></span></div>
<div><span> </span></div>
<div  style="margin-left:10px">
<div>Request URL: ws://localhost:8080/websession</div>
<div>Request Method: GET</div>
<div>Status Code: 101 Switching Protocols</div>
</div>
<div>Request Headers</div>
<div style="margin-left:10px">
<div>Connection: Upgrade</div>
<div>Host: localhost:8080</div>
<div>Origin: <a href="http://localhost:53927/" target="_blank">http://localhost:53927</a></div>
<div>Sec-WebSocket-Key: vPkYt7muES+evHN2AxXasw==</div>
<div>Sec-WebSocket-Version: 13</div>
<div>Upgrade: websocket</div>
<div>(Key3): 00:00:00:00:00:00:00:00</div>
</div>
<div>Response Headers</div>
<div style="margin-left:10px">
<div>Connection: Upgrade</div>
<div>Sec-WebSocket-Accept: 4+7cCQ4YGQh9jjDlnIRv6qwgVlM=</div>
<div>Upgrade: WebSocket</div>
<div>(Challenge Response): 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00</div>
</div>
<div><span><b><br/>The JavaScript for a browser to initiate a WebSocket connection is as follows.</b></span></div>
<pre class="brush: jscript; title: ; notranslate">
var socketserver_url = 'ws://localhost:8080/websession';
var socket = new WebSocket(socketserver_url);
socket.onopen = function () {
	alert('handshake successfully established. May send data now...');
};
socket.onmessage = function (e) {
	//var d = JSON.parse(e.data);
	console.log(e);
	$('#received_messages').append('WebSockets message received: ' + e.data + '
');
	alert('data received');
};
socket.onerror = function (data) {
	console.log(data);
	alert('errors occurred: ' + data);
};
socket.onclose = function () {
	alert('connection closed');
};
</pre>
<div><span>Once the connection is open, the browser will raise the socket.onmessage() event when a new message is received from the server.</span></div>
<p><span><br />
<b>The server side code for a WebSocket is as follows.</b><br />
It is shown here as a console app that listens for WebSocket requests at ws://localhost:8080/websession.</p>
<pre class="brush: csharp; title: ; notranslate">

static void Main(string[] args)
{
	var listener = new TcpListener(IPAddress.Loopback, 8080);
	listener.Start();

	while (true)
	{
		Listen(listener);
	}
}

// Listen for some connection request
private static void Listen(TcpListener listener)
{
	using (var client = listener.AcceptTcpClient())
	using (var stream = client.GetStream())
	{
		var headers = new Dictionary();
		string line = string.Empty;
		while ((line = ReadLine(stream)) != string.Empty)
		{
			var tokens = line.Split(new char[] {':'}, 2);
			if (!string.IsNullOrWhiteSpace(line) &amp;&amp; tokens.Length &gt; 1)
			{
				headers[tokens[0]] = tokens[1].Trim();
			}
		}

		// Get key sent by client and compute socket accept value
		var key = headers[&quot;Sec-WebSocket-Key&quot;];
		String secWebSocketAccept = ComputeWebSocketHandshakeSecurityHash09(key);

		// Setup headers for response
		var response =
			&quot;HTTP/1.1 101 Switching Protocols&quot; + Environment.NewLine +
			&quot;Upgrade: WebSocket&quot; + Environment.NewLine +
			&quot;Connection: Upgrade&quot; + Environment.NewLine +
			&quot;Sec-WebSocket-Accept: &quot; + secWebSocketAccept + Environment.NewLine +
			Environment.NewLine;

		var bufferedResponse = Encoding.UTF8.GetBytes(response);
		stream.Write(bufferedResponse, 0, bufferedResponse.Length);

		SendMessageToClient(stream);
	}
}

// Determine which data is ready to receive and push to client
private static void SendMessageToClient(NetworkStream stream)
{
	// Add data to response.  Get messages received from webhook
	string responseData = String.Empty;
	List messages = GetDataAlreadyReceivedFromWebHook(null, null);
	foreach (string message in messages)
	{
		responseData += message + &quot;,&quot;;
	}
	responseData = responseData.TrimEnd(&quot;,&quot;.ToCharArray());

	List lb = new List();
	lb.Add(0x81);
	lb.Add(0x04);
	// add the payload
	lb.AddRange(Encoding.UTF8.GetBytes(&quot;Test&quot;));
	//write it!
	stream.Write(lb.ToArray(), 0, 6);
}
</pre>
<div><span></p>
<p>	When the server wants to send a new message to the browser, it will write to the client&#8217;s stream like this:</span></div>
<pre class="brush: csharp; title: ; notranslate">
stream.Write(bufferedMessage, 0, bufferedMessage .Length);
</pre>
<div><span><br />
Now, a browser can respond to some event that happens on some third party system.<br />
<br/><br />
<hr noshade><br/></p>
<h3>Some words of caution on WebSockets</h3>
<p>There are a few things you should be aware of before attempting to implement WebSockets. </p>
<ol style="margin-left:20px">
<li>
 First, .NET 4.5 has some low level socket functionality with the System.Net.WebSockets namespace and there is also a really promising NuGet library. You should definitely check this out before trying to implement WebSockets.<br />
<a href="http://paulbatum.github.com/WebSocket-Samples/AspNetWebSocketEcho/" target="_blank">http://paulbatum.github.com/WebSocket-Samples/AspNetWebSocketEcho/</a><br/><a target="_blank" href="http://www.techbubbles.com/aspnet/websockets-in-asp-net-4-5/">http://www.techbubbles.com/aspnet/websockets-in-asp-net-4-5/</a><br/><br/></li>
<li>Second, the protocol for WebSockets has rapidly evolved. Many examples you will find implement  Hixie-75 or Hixie-76. This article is based on Hybi-09.  Given that not all browsers support this protocol, in particular IE, you can not really implement WebSockets for critical functionality in an enterprise application at this point.<br />
<br/>Here is a related article: <b><a target="_blank" href="http://www.hanselman.com/blog/YourUsersDontCareIfYouUseWebSockets.aspx">You users don&#8217;t care if you use websockets</a></b><br/><br />
This is the protocol evolution<br />
<table class="wikitable">
<tbody>
<tr>
<th><a rel="nofollow" class="external text" target="_blank" href="http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75">hixie-75</a></th>
</tr>
<tr>
<th><a rel="nofollow" target="_blank" class="external text" href="http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76">hixie-76</a><br />
<a rel="nofollow" target="_blank" class="external text" href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-00">hybi-00</a></th>
</tr>
<tr>
<th><a rel="nofollow" target="_blank"  class="external text" href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-06">hybi-06</a></th>
</tr>
<tr>
<th><a rel="nofollow" target="_blank" class="external text" href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07">hybi-07</a></th>
</tr>
<tr>
<th><a rel="nofollow" class="external text" target="_blank" href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-09">hybi-09</a></th>
</tr>
<tr>
<th><a rel="nofollow" class="external text" target="_blank" href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10">hybi-10</a></th>
</tr>
<tr>
<th><a class="external mw-magiclink-rfc" target="_blank" href="http://www.entechsolutions.com//tools.ietf.org/html/rfc6455">RFC 6455</a></th>
</tr>
</tbody>
</table>
<p><br/>
</li>
</ol>
<h3>LINKS</h3>
<p></span></div>
<div style="margin-left:20px">
<b><a href="http://www.techbubbles.com/aspnet/websockets-in-asp-net-4-5/" target="_blank">.NET 4.5 WebSockets</a> </b><br />
<a href="http://www.techbubbles.com/aspnet/websockets-in-asp-net-4-5/" target="_blank">http://www.techbubbles.com/aspnet/websockets-in-asp-net-4-5/</a><br />
<a href="http://paulbatum.github.com/WebSocket-Samples/AspNetWebSocketEcho/" target="_blank">http://paulbatum.github.com/WebSocket-Samples/AspNetWebSocketEcho/</a><br/><br />
<b><a href="http://html5demos.com/web-socket" target="_blank">http://html5demos.com/web-socket</a></b><br/>WebSocket Demo based on Node<br/><br />
<b><a href="http://nowjs.com/" target="_blank"> http://nowjs.com/</a> </b><br />
SUPER COOL NODE LIBRARY which provides easy to use functionality for the browser and server to talk back and forth. (No, this is not a Node article, but you should check it out anyway!)<br/><br />
<b><a href="http://websocket.org/" target="_blank">http://websocket.org/</a></b><br/>
</div>
<p><br/></p>
<h3>Download</h3>
<p><b><a href="http://dl.dropbox.com/u/18263783/WebHooks.7z" target="_blank">CLICK TO DOWNLOAD SOURCE CODE FOR THIS ARTICLE</a></b><br />
The download contains a Visual Studio 2010 .NET solution which implements both the client and the server side parts of WebHooks and WebSockets. It contains the following 3 projects:<br/></p>
<ol style="margin-left:20px">
<li><b>WebClient.csproj</b><br />
	<br/>This contains the WebHook listener service at <a href="http://localhost:53927/WebHookListenerService.svc" target="_blank">http://localhost:53927/WebHookListenerService.svc</a>. <br/> Run this application so the callback url is available when the WebHookServer wants to post to it when new events occur. When the ClientApp receives a new event, it simply writes the data to a text file at c:/temp/webhook.txt.  Check this file to see that you are receiving messages.<br/>			</p>
</li>
<li><b>WebHookServer.csproj</b><br />
<br/>Contains a RESTful WCF Service which simply posts event information to the ClientApp&#8217;s callback url.  To invoke the service to post an event: <br/><br/><span><a href="http://localhost:53936/WebHookService.svc/event/post?eventType=APPOINTMENT_CREATED&amp;eventSource=API&amp;data=some_thing_happened" target="_blank">http://localhost:53936/WebHookService.svc/event/post?eventType=APPOINTMENT_CREATED&amp;eventSource=API&amp;data=some_thing_happened</a></span><br />
<br/><b>Note:</b> This is a simplified example. In a real application you will want to add code to verify that the client receives the data successfully, deactivate unresponsive callback urls, add signature to your messages so the client can verify who you are, and more.</span><br />
<br/></li>
<li><b>WebSocketServer.csproj</b><br />
<br/><span>A console application which listens for socket connection requests and also monitors the c:/temp/webhook.txt file for new data. When new data is detected, it pushes it to the connected clients. To run this project and make a connection between it and the ClientApp, run the console app. Then open the default page in the ClientApp,  <a href="http://localhost:53927/Default.aspx" target="_blank">http://localhost:53927/Default.aspx</a>, which will make the connection to the socket server at ws://localhost:8080/websession.</span><br />
<br/><b>Note:</b> The WebSocket implementation in this download only performs the initial handshake and sends one message to the client. The full implementation of WebSockets is more complicated having to handle multiple connections.<br />
This is a nice full implementation in C#: <a href="http://ashishware.com/websocksample.shtml"  target="_blank">http://ashishware.com/websocksample.shtml</a></p>
<p><b>Note:</b>  This sample does not run in FireFox. Please run the socket client in Chrome.</p>
</li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.entechsolutions.com/hooks-and-sockets-for-web-apps/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>WCF and Dynamic SSL</title>
		<link>http://www.entechsolutions.com/wcf-and-dynamic-ssl?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wcf-and-dynamic-ssl</link>
		<comments>http://www.entechsolutions.com/wcf-and-dynamic-ssl#comments</comments>
		<pubDate>Fri, 03 Feb 2012 16:42:19 +0000</pubDate>
		<dc:creator>Mike</dc:creator>
				<category><![CDATA[WCF]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[SSL]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[dynamic]]></category>
		<category><![CDATA[programmatically]]></category>
		<category><![CDATA[tutorial]]></category>

		<guid isPermaLink="false">http://www.entechsolutions.com/?p=344</guid>
		<description><![CDATA[Here at ENTech Solutions we maintain several environments which include production, staging, QA and development. Each of these environments has its own setup with production and QA having their own SLL certificates.  Stable and most of our local development environments do not. We can use self signed certs on our local development systems, but for ...]]></description>
			<content:encoded><![CDATA[<p>Here at ENTech Solutions we maintain several environments which include <em>production</em>, <em>staging</em>, <em>QA </em>and <em>development</em>.   Each of these environments has its own setup with production and QA having their own  SLL certificates.  Stable and most of our local development environments do  not.  We can use self signed certs on our local development systems, but for staging this is  not an option.  We need a way to enable or disable SSL depending on environment.  In this post I&#8217;ll show you how to work with WCF and SSL at run time.  It assumes you have a working service running with a configuration file with one endpoint.</p>
<h2>Setting SSL via Configuration Files</h2>
<p>Adding SSL support to a WCF app is rather easy.  In the config file (web.config or app.config) set the bindings security to <em>Transport</em>.  For basic http binding it is set as:</p>
<pre class="brush: xml; title: ; notranslate">
 &lt;bindings&gt;
  &lt;basicHttpBinding&gt;
   &lt;binding name=&quot;HttpBinding&quot;&gt;
    &lt;security mode=&quot;Transport&quot;&gt;
</pre>
<p>For web binding it is set similarly as:</p>
<pre class="brush: xml; title: ; notranslate">
 &lt;bindings&gt;
  &lt;webHttpBinding&gt;
   &lt;binding name=&quot;HttpBinding&quot;&gt;
    &lt;security mode=&quot;Transport&quot;&gt;
</pre>
<h2>Programmatically working with SSL</h2>
<p>Instead of having the system automatically create the service host, we are going to:</p>
<ol>
<li>Override the method that creates the service host</li>
<li>Create it manually while still using the configuration settings</li>
<li>Make changes to the service objects as needed</li>
</ol>
<p>To start off we will set up our service with a standard  configuration, one end point, and using <em>Transport </em>security mode binding.  I have found it is easier and safer to have SSL turned on by default and turn it off as needed.</p>
<p>To override the service host code we need to create a service factory class.</p>
<pre class="brush: csharp; title: ; notranslate">
public class OurServiceFactory : ServiceHostFactory
{
 public override ServiceHostBase
                   CreateServiceHost(string constructorString, Uri[] baseAddresses)
 {
  return null; // null for now
 }
}
</pre>
<p>We need a way to have the system use our factory instead of the default code.  To do this in a WCF web site modify the Service.svc file.</p>
<pre class="brush: csharp; title: ; notranslate">
&lt;%@ ServiceHost  language=&quot;c#&quot;  Factory=&quot;OurServiceFactory&quot; %&gt;
</pre>
<p>To create the service host manually we modify CreateServiceHost method as:</p>
<pre class="brush: csharp; title: ; notranslate">
public override ServiceHostBase
          CreateServiceHost(string constructorString, Uri[] baseAddresses)
{
 var serviceHost = new ServiceHost(typeof(OurService), baseAddresses);

 return serviceHost;
}
</pre>
<p>When the above CreateServiceHost method is called, a new service host is created.  The ServiceHost constructor tries to match the name of the service type with the configuration file and uses those settings.  This allows us to use the configuration file while giving the ability to make changes programmatically.</p>
<p>In this example EnableSSL can be set true on <em>production </em>and <em>QA </em>environments, false otherwise.</p>
<pre class="brush: csharp; title: ; notranslate">
public override ServiceHostBase
                 CreateServiceHost(string constructorString, Uri[] baseAddresses)
{
 var serviceHost = new ServiceHost(typeof(Service), baseAddresses);

 if (!EnableSSL)  // we enable SSL by default
 {
  var endpoint
        = serviceHost.Description.Endpoints[0]; // assume first and only endpoint.
  endpoint.Address
        = new EndpointAddress(baseAddresses[0].ToString().Replace(&quot;https&quot;, &quot;http&quot;));

  if (endpoint.Binding is WebHttpBinding)
   ((WebHttpBinding) endpoint.Binding).Security.Mode
        = WebHttpSecurityMode.None;

  if (endpoint.Binding is BasicHttpBinding)
   ((BasicHttpBinding) endpoint.Binding).Security.Mode
        = BasicHttpSecurityMode.None;
 }
 return serviceHost;
}
</pre>
<p>The above code demonstrates how to to set security mode for both WebHttpBinding and BasicHttpBinding, but only <em>one </em>would be necessary.</p>
<p>To consume this service using a standard service consumer C# application would look like:</p>
<pre class="brush: csharp; title: ; notranslate">
WCFService.ServiceClient service = new ServiceClient();
if (!EnableSSL)
{
 service.Endpoint.Address
                   = new EndpointAddress(&quot;http://wcf/service.svc&quot;);
 (service.Endpoint.Binding as BasicHttpBinding).Security.Mode
                   = BasicHttpSecurityMode.None;
}
</pre>
<h2>Conclusion</h2>
<p>WCF provides a ton of configuration options that can be set via configuration or programmactially.  The above factory can be used to programmatically change many settings and not just security options.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.entechsolutions.com/wcf-and-dynamic-ssl/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Using partial request/response in WCF</title>
		<link>http://www.entechsolutions.com/using-partial-requestresponse-in-wcf?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=using-partial-requestresponse-in-wcf</link>
		<comments>http://www.entechsolutions.com/using-partial-requestresponse-in-wcf#comments</comments>
		<pubDate>Mon, 30 Jan 2012 07:31:07 +0000</pubDate>
		<dc:creator>anup</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[API]]></category>
		<category><![CDATA[request]]></category>
		<category><![CDATA[response]]></category>

		<guid isPermaLink="false">http://www.entechsolutions.com/?p=327</guid>
		<description><![CDATA[I got inspiration to research on this topic after reading partial request/response email a week ago. This was the link mentioned in the email. http://googlecode.blogspot.com/2010/03/making-apis-faster-introducing-partial.html Partial request/response is also used in LinkedIn APIs.  http://blog.linkedin.com/2009/07/08/brandon-duncan-java-one-building-consistent-restful-apis-in-a-high-performance-environment/ In their API documentation, they have sample partial requests. They call it FieldSelectors: More on this link https://developer.linkedin.com/documents/field-selectors So what exactly ...]]></description>
			<content:encoded><![CDATA[<p>I got inspiration to research on this topic after reading partial request/response email a week ago. This was the link mentioned in the email.</p>
<p><a href="http://googlecode.blogspot.com/2010/03/making-apis-faster-introducing-partial.html"><span style="color: #0000ff">http://googlecode.blogspot.com/2010/03/making-apis-faster-introducing-partial.html</span></a></p>
<p>Partial request/response is also used in LinkedIn APIs.  <a href="http://blog.linkedin.com/2009/07/08/brandon-duncan-java-one-building-consistent-restful-apis-in-a-high-performance-environment/"><span style="color: #0000ff">http://blog.linkedin.com/2009/07/08/brandon-duncan-java-one-building-consistent-restful-apis-in-a-high-performance-environment/</span></a><br />
In their API documentation, they have sample partial requests. They call it FieldSelectors: More on this link <a href="https://developer.linkedin.com/documents/field-selectors"><span style="color: #0000ff">https://developer.linkedin.com/documents/field-selectors</span></a></p>
<p><strong>So what exactly is Partial request/response?</strong></p>
<p>-    In API calls, we often use default request and retrieve default response. Partial request or Field Selector allows us to request the data that we want. The API response will contain just those data and elements that we have requested and not the whole default result.<br />
Enabling partial request/response in our existing API calls will help in increasing efficiency. I think there is no doubt about it.</p>
<p>In our current application– If you want to retrieve just a location name, the city and state of one of the business. You will be using GetLocation with appropriate parameters. Current implementation returns a large response with many elements that you will not be using. The current response is 2007 bytes, where as partial response would be only 690 bytes. APIs will be much more efficient if we can avoid unnecessary data that just go wasted. This will save the bandwidth as well./</p>
<p><strong>Current Request</strong></p>
<div class="framed_box">
<div class="framed_box_content">GET /GetLocation</div>
</div>
<p><strong>Current Response</strong></p>
<div class="framed_box">
<div class="framed_box_content">&lt;s:Envelope xmlns:s=&#8221;http://schemas.xmlsoap.org/soap/envelope/&#8221;&gt;<br />
&lt;s:Body&gt;<br />
&lt;GetLocationResponse xmlns=&#8221;https://www.spa-booker.com/soap/customer&#8221;&gt;<br />
&lt;GetLocationResult xmlns:a=&#8221;https://www.spa-booker.com&#8221; xmlns:i=&#8221;http://www.w3.org/2001/XMLSchema-instance&#8221;&gt;<br />
&lt;a:AccountName&gt;spaladoc&lt;/a:AccountName&gt;<br />
&lt;a:Address&gt;<br />
&lt;a:City&gt;Metuchen&lt;/a:City&gt;<br />
&lt;a:Country&gt;<br />
&lt;a:ID&gt;1&lt;/a:ID&gt;<br />
&lt;a:Name&gt;United States&lt;/a:Name&gt;<br />
&lt;/a:Country&gt;<br />
&lt;a:State&gt;NJ&lt;/a:State&gt;<br />
&lt;a:Street1&gt;6500 New Ave&lt;/a:Street1&gt;<br />
&lt;a:Street2 i:nil=&#8221;true&#8221;/&gt;<br />
&lt;a:Zip&gt;11215&lt;/a:Zip&gt;<br />
&lt;/a:Address&gt;<br />
&lt;a:BusinessName&gt;Spa La Documentation&lt;/a:BusinessName&gt;<br />
&lt;a:BusinessType&gt;<br />
&lt;a:ID&gt;13&lt;/a:ID&gt;<br />
&lt;a:Name&gt;Spa&lt;/a:Name&gt;<br />
&lt;/a:BusinessType&gt;<br />
&lt;a:CultureName&gt;en-US&lt;/a:CultureName&gt;<br />
&lt;a:CurrencyCode&gt;USD&lt;/a:CurrencyCode&gt;<br />
&lt;a:Description i:nil=&#8221;true&#8221;/&gt;<br />
&lt;a:EmailAddress&gt;gfdgfd@gfd.com&lt;/a:EmailAddress&gt;<br />
&lt;a:FeatureLevel&gt;Unlimited&lt;/a:FeatureLevel&gt;<br />
&lt;a:FirstName&gt;Test&lt;/a:FirstName&gt;<br />
&lt;a:ID&gt;3749&lt;/a:ID&gt;<br />
&lt;a:LastName&gt;Booker&lt;/a:LastName&gt;<br />
&lt;a:Password i:nil=&#8221;true&#8221;/&gt;<br />
&lt;a:Phone&gt;6323197663&lt;/a:Phone&gt;<br />
&lt;a:SpaFinderId i:nil=&#8221;true&#8221;/&gt;<br />
&lt;a:Status&gt;Demo&lt;/a:Status&gt;<br />
&lt;a:TimeZone&gt;<br />
&lt;a:ID&gt;18&lt;/a:ID&gt;<br />
&lt;a:Name&gt;(GMT-05:00) Eastern Time (US &amp;amp; Canada)&lt;/a:Name&gt;<br />
&lt;a:StandardName&gt;Eastern Standard Time&lt;/a:StandardName&gt;<br />
&lt;/a:TimeZone&gt;<br />
&lt;a:WebSite i:nil=&#8221;true&#8221;/&gt;<br />
&lt;a:ArgumentErrors i:nil=&#8221;true&#8221;/&gt;<br />
&lt;a:ErrorCode&gt;0&lt;/a:ErrorCode&gt;<br />
&lt;a:ErrorMessage i:nil=&#8221;true&#8221;/&gt;<br />
&lt;a:IsSuccess&gt;true&lt;/a:IsSuccess&gt;<br />
&lt;/GetLocationResult&gt;<br />
&lt;/GetLocationResponse&gt;<br />
&lt;/s:Body&gt;<br />
&lt;/s:Envelope&gt;</div>
</div>
<p><strong>Partial Request</strong></p>
<div class="framed_box">
<div class="framed_box_content">Get /GetLocation?fields=(businessname, city, state)</p>
<p>Or /GetLocation(businessname,city,state)</p></div>
</div>
<p><strong>Partial Response</strong></p>
<div class="framed_box">
<div class="framed_box_content">&lt;s:Envelope xmlns:s=&#8221;http://schemas.xmlsoap.org/soap/envelope/&#8221;&gt;<br />
&lt;s:Body&gt;<br />
&lt;GetLocationResponse xmlns=&#8221;https://www.spa-booker.com/soap/customer&#8221;&gt;<br />
&lt;GetLocationResult xmlns:a=&#8221;https://www.spa-booker.com&#8221; xmlns:i=&#8221;http://www.w3.org/2001/XMLSchema-instance&#8221;&gt;<br />
&lt;a:City&gt;Metuchen&lt;/a:City&gt;<br />
&lt;a:State&gt;NJ&lt;/a:State&gt;<br />
&lt;a:BusinessName&gt;Spa La Documentation&lt;/a:BusinessName&gt;<br />
&lt;a:ArgumentErrors i:nil=&#8221;true&#8221;/&gt;<br />
&lt;a:ErrorCode&gt;0&lt;/a:ErrorCode&gt;<br />
&lt;a:ErrorMessage i:nil=&#8221;true&#8221;/&gt;<br />
&lt;a:IsSuccess&gt;true&lt;/a:IsSuccess&gt;<br />
&lt;/GetLocationResult&gt;<br />
&lt;/GetLocationResponse&gt;<br />
&lt;/s:Body&gt;<br />
&lt;/s:Envelope&gt;</p>
</div>
</div>
<p><em>This is the part I of the blog. I will try to add more on the implementation part.</em></p>
<p>-Anup</p>
]]></content:encoded>
			<wfw:commentRss>http://www.entechsolutions.com/using-partial-requestresponse-in-wcf/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to write unit tests for JSON, XML and SOAP endpoints of WCF Service</title>
		<link>http://www.entechsolutions.com/wcf-web-service-for-soap-json-and-xml-with-unit-tests?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wcf-web-service-for-soap-json-and-xml-with-unit-tests</link>
		<comments>http://www.entechsolutions.com/wcf-web-service-for-soap-json-and-xml-with-unit-tests#comments</comments>
		<pubDate>Fri, 13 Jan 2012 10:00:19 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.entechsolutions.com/?p=169</guid>
		<description><![CDATA[Background In a recent project I worked on WCF service with the following requirements: Support requests and responses in SOAP, JSON and XML. Support GET and POST requests. Be able to Unit Test SOAP, JSON and XML requests CLICK HERE TO DOWNLOAD SOURCE CODE FOR WCF SERVICE and UNIT TESTS table.sample { border-width: 1px; border-spacing: ...]]></description>
			<content:encoded><![CDATA[<h2>Background</h2>
<p>In a recent project I worked on WCF service with the following requirements:</p>
<div>
<ol>
<li> Support requests and responses in SOAP, JSON and XML.</li>
<li>Support GET and POST requests.</li>
<li>Be able to Unit Test SOAP, JSON and XML requests</li>
</ol>
</div>
<p />
<p />
<b><a href="http://www.entechsolutions.com/downloads/sampleapi.zip">CLICK HERE TO DOWNLOAD SOURCE CODE FOR WCF SERVICE and UNIT TESTS</a></b><br />
</p>
<style type="text/css">
table.sample {
	border-width: 1px;
	border-spacing: 2px;
	border-style: outset;
	border-color: gray;
	border-collapse: separate;
	background-color: white;
}
table.sample th {
	border-width: 1px;
	padding: 3px;
	border-style: inset;
	border-color: gray;
	background-color: white;
	-moz-border-radius: ;
}
table.sample td {
	border-width: 1px;
	padding: 3px;
	border-style: inset;
	border-color: gray;
	background-color: white;
	-moz-border-radius: ;
}
</style>
<h2>The WCF Service </h2>
<div>For a sample application I made a Math service that allows for Adding two values together.</div>
<pre class="brush: csharp; title: ; notranslate">

	public class MathService
	{
		public int Add(int value1, int value2)
		{
			int sum = value1 + value2;
			return sum;
		}
	}
</pre>
<p>To access this service through WCF,  I added the following IService contract:</p>
<pre class="brush: csharp; title: ; notranslate">
	[ServiceContract(Namespace = &quot;apidoc.sampleapi.com&quot;, Name = &quot;SampleApi&quot;)]
	public interface IService
	{
		[WebGet( UriTemplate = &quot;Add?value1={value1}&amp;amp;value2={value2}&amp;amp;apiKey={apiKey}&quot;, BodyStyle = WebMessageBodyStyle.Bare)]
                AddRs AddWithHttpGet(int value1, int value2, string apiKey);

		[WebInvoke(Method = &quot;POST&quot;, UriTemplate = &quot;Add&quot;, BodyStyle = WebMessageBodyStyle.Bare)]
		AddRs Add(AddRq rq);
	}
</pre>
<p>There is only two functions. The first one allows for using Get and passing all the parameters in query string.  The second one allows passing objects using Post.  In both cases the methods return results in object format.</p>
<p>This service can be called in the following ways:</p>
<table width="1000px" class="sample">
<tbody>
<tr>
<th>Method</th>
<th>Message Format</th>
<th>Url</th>
<th>Sample Request</th>
<th>Response</th>
</tr>
<tr>
<td>GET</td>
<td>JSON</td>
<td>http://localhost/ApiDoc.SampleApi/json/add?value1=5&amp;value2=11&amp;apiKey=test-key</td>
<td>in Url</td>
<td>
<pre class="brush: jscript; title: ; notranslate">
{&quot;IsSuccess&quot;:true,&quot;Sum&quot;:16}
</pre>
</td>
</tr>
<tr>
<td>GET</td>
<td>XML</td>
<td>http://localhost/ApiDoc.SampleApi/xml/add?value1=5&amp;value2=11&amp;apiKey=test-key</td>
<td>in Url</td>
<td>
<pre class="brush: xml; title: ; notranslate">
&lt;AddRs xmlns=&quot;apidoc.sampleapi.com&quot; xmlns:i=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&gt;
	&lt;IsSuccess&gt;true&lt;/IsSuccess&gt;
	&lt;Sum&gt;16&lt;/Sum&gt;
&lt;/AddRs&gt;
</pre>
</td>
</tr>
<tr>
<td>POST</td>
<td>JSON</td>
<td>http://localhost/ApiDoc.SampleApi/json/add</td>
<td>
<pre class="brush: jscript; title: ; notranslate">
{&quot;Value1&quot;:5,&quot;Value2&quot;:11,&quot;ApiKey&quot;:&quot;test-key&quot;}
</pre>
</td>
<td>
<pre class="brush: jscript; title: ; notranslate">
{&quot;IsSuccess&quot;:true,&quot;Sum&quot;:16}
</pre>
</td>
</tr>
<tr>
<td>POST</td>
<td>XML</td>
<td>http://localhost/ApiDoc.SampleApi/xml/add</td>
<td>
<pre class="brush: xml; title: ; notranslate">
&lt;AddRq xmlns=&quot;apidoc.sampleapi.com&quot;&gt;
  &lt;ApiKey&gt;test-key&lt;/ApiKey&gt;
  &lt;Value1&gt;5&lt;/Value1&gt;
  &lt;Value2&gt;11&lt;/Value2&gt;
&lt;/AddRq&gt;
</pre>
</td>
<td>
<pre class="brush: xml; title: ; notranslate">
&lt;AddRs xmlns=&quot;apidoc.sampleapi.com&quot; xmlns:i=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&gt;
	&lt;IsSuccess&gt;true&lt;/IsSuccess&gt;
	&lt;Sum&gt;16&lt;/Sum&gt;
&lt;/AddRs&gt;
</pre>
</td>
</tr>
<tr>
<td>POST</td>
<td>SOAP</td>
<td>http://localhost/ApiDoc.SampleApi/service.svc</td>
<td>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; ?&gt;
&lt;s:Envelope xmlns:s=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;&gt;
  &lt;s:Body&gt;
    &lt;Add xmlns=&quot;apidoc.sampleapi.com&quot;&gt;
      &lt;rq xmlns:i=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&gt;
        &lt;ApiKey&gt;
          test-key
        &lt;/ApiKey&gt;
        &lt;Value1&gt;
          5
        &lt;/Value1&gt;
        &lt;Value2&gt;
          11
        &lt;/Value2&gt;
      &lt;/rq&gt;
    &lt;/Add&gt;
  &lt;/s:Body&gt;
&lt;/s:Envelope&gt;
</pre>
</td>
<td>
<pre class="brush: xml; title: ; notranslate">
&lt;?xml version=&quot;1.0&quot; ?&gt;
&lt;s:Envelope xmlns:s=&quot;http://schemas.xmlsoap.org/soap/envelope/&quot;&gt;
  &lt;s:Body&gt;
    &lt;AddResponse xmlns=&quot;apidoc.sampleapi.com&quot;&gt;
      &lt;AddResult xmlns:i=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;&gt;
        &lt;IsSuccess&gt;
          true
        &lt;/IsSuccess&gt;
        &lt;Sum&gt;
          16
        &lt;/Sum&gt;
      &lt;/AddResult&gt;
    &lt;/AddResponse&gt;
  &lt;/s:Body&gt;
&lt;/s:Envelope&gt;
</pre>
</td>
</tr>
</tbody>
</table>
<p></p>
<h2>Unit Testing</h2>
<h3>Unit Testing SOAP in WCF Service</h3>
<p>Unit testing SOAP is pretty easy.  You create a service reference to Web Service and use the following code to check if Sum comes out correctly when authentication key is valid:</p>
<pre class="brush: csharp; title: ; notranslate">
       [Test]
        public void Add_WhenValidApiKey_ReturnsSum()
        {
            var client = new SampleApiSoapService.SampleApiClient(&quot;soap&quot;);

            var addRequest = new SampleApiSoapService.AddRq
            {
                Value1 = 5,
                Value2 = 11,
                ApiKey = Const.ValidApiKey
            };

            var addResponse = client.Add(addRequest);
            Assert.AreEqual(addResponse.Sum, 16);
        }
</pre>
<p>You may notice that for Request/Response objects I am using suffix Rq/Rs.  I previously tried to use full names (Request/Response), but this was causing some conflicts with Proxy generated classes which also use Request/Response.</p>
<h3>Unit Testing JSON in WCF Service</h3>
<p>This is where it gets interesting. To be able to submit request in JSON from server side, I am using dynamic objects.  This is one of the best features in C# 4.0.  Basically you create a new object without having to declare a class.  So here are the steps to make sure &#8220;Add&#8221; operation works using JSON Post/Get.</p>
<ol>
<li>create a dynamic class that matches JSON datastructure</li>
<li>Serialize it to JSON</li>
<li>Send json to web service</li>
<li>Deserilize response to a dynamic object</li>
<li>Make sure that response has value that I expected</li>
<ol>
<p>Here it the code for testing POST:</p>
<pre class="brush: csharp; title: ; notranslate">
        [Test]
        public void Add_WhenMethodPost_And_ValidApiKey_ReturnsSum()
        {
            var addRequest = new
            {
                Value1 = 5,
                Value2 = 11,
                ApiKey = Const.ValidApiKey
            };

            var url = string.Format(&quot;{0}/json/add&quot;, Const.WebServiceUrl);
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = &quot;POST&quot;;
            request.ContentType = &quot;application/json; charset=utf-8&quot;;

            var jsSerializer = new JavaScriptSerializer();
            var jsonAddRequest = jsSerializer.Serialize(addRequest);

            var writer = new StreamWriter(request.GetRequestStream());
            writer.Write(jsonAddRequest);
            writer.Close();

            var httpWebResponse = (HttpWebResponse)request.GetResponse();

            string jsonString;
            using (var sr = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                jsonString = sr.ReadToEnd();
            }

            var jsonAddResponse = jsSerializer.Deserialize&lt;dynamic&gt;(jsonString);

            Assert.AreEqual(16, jsonAddResponse[&quot;Sum&quot;]);
        }
</pre>
<p>Here it the code for testing GET:</p>
<pre class="brush: csharp; title: ; notranslate">
       [Test]
        public void Add_WhenMethodGet_And_ValidApiKey_ReturnsSum()
        {
            var url = string.Format(&quot;{0}/json/add?value1={1}&amp;amp;value2={2}&amp;amp;apiKey={3}&quot;, Const.WebServiceUrl, 5, 11,
                                    Const.ValidApiKey);
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.Method = WebRequestMethods.Http.Get;
            httpWebRequest.Accept = &quot;application/json&quot;;

            string jsonString;
            var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

            using (var sr = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                jsonString = sr.ReadToEnd();
            }

            var jsSerializer = new JavaScriptSerializer();
            var jsonAddResponse = jsSerializer.Deserialize&lt;dynamic&gt;(jsonString);

            Assert.AreEqual(16, jsonAddResponse[&quot;Sum&quot;]);
        }
</pre>
<h3>Unit Testing XML in WCF Service</h3>
<p>Testing XML is similar to JSON.  </p>
<ol>
<li>create a dynamic class that matches XMLdatastructure</li>
<li>Serialize it to XML</li>
<li>Send XML structure to web service</li>
<li>Deserialize response to a dynamic object</li>
<li>Make sure that response has value that I expected</li>
</ol>
<p></p>
<p>The only issue is that XmlSerializer doesn&#8217;t have as great support for dynamic objects as JsonSerializer.  I found a bunch of info on this subject:<br />
Link 1: <a href="http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx">Serializing dynamic objects to XML</a><br />
Link 2: <a href=" http://www.codeproject.com/Tips/227139/Converting-XML-to-an-dynamic-object-using-ExpandoO">Deserializing dynamic objects (ExpandoObject) from XML</a></p>
<p>I put this info together as well as a bunch of unit tests and &#8220;Voila&#8221;.  Now converting dynamic objects to XML and back is extremely easy.  The only issue I encountered was that when deserializing objects, we have no knowledge of property types so all properties of resulting dynamic objects are strings.</p>
<p>Here is the source code to the class DynamicXmlSerializer:</p>
<pre class="brush: csharp; title: ; notranslate">

    public class DynamicXmlSerializer
    {
        private XNamespace _xmlNamespace;

        public DynamicXmlSerializer(XNamespace xmlNamespace = null)
        {
            _xmlNamespace = xmlNamespace;
        }

        //From http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx
        public XElement Serialize(dynamic dynamicObject, String rootNodeName)
        {
            var xmlNode = CreateNewXmlNode(rootNodeName);

            PropertyInfo[] properties;
            properties = dynamicObject.GetType().GetProperties();
            foreach (var property in properties)
            {
                object propertyValue = property.GetValue(dynamicObject, null);
                string propertyName = property.Name;

                if (IsAnonymousType(propertyValue.GetType()))
                {
                    xmlNode.Add(Serialize(propertyValue, propertyName));
                }
                else
                {
                    if (propertyValue.GetType() == typeof(List&lt;dynamic&gt;))
                    {
                        string xmlListNodeName = propertyName;
                        var xmlListNode = CreateNewXmlNode(xmlListNodeName);

                        //Use singular for lists, so if it was Friends - it becomes &quot;Friend&quot;
                        string xmlListItemNodeName = Singularizer.IsPlural(xmlListNodeName)
                                                         ? Singularizer.Singularize(xmlListNodeName)
                                                         : xmlListNodeName;

                        foreach (var element in (List&lt;dynamic&gt;)propertyValue)
                        {
                            xmlListNode.Add(Serialize(element, xmlListItemNodeName));
                        }

                        xmlNode.Add(xmlListNode);
                    }
                    else
                    {
                        xmlNode.Add(CreateNewXmlNode(propertyName, propertyValue));
                    }
                }
            }

            return xmlNode;
        }

        private XElement CreateNewXmlNode(string name, object content = null)
        {
            if (_xmlNamespace != null)
                return new XElement(_xmlNamespace + name, content);
            else
                return new XElement(name, content);
        }

        //From http://stackoverflow.com/questions/1650681/determining-whether-a-type-is-an-anonymous-type
        private static Boolean IsAnonymousType(Type type)
        {
            Boolean hasCompilerGeneratedAttribute = type.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).COUNT() as Computed &gt; 0;
            Boolean nameContainsAnonymousType = type.FullName.Contains(&quot;AnonymousType&quot;);
            Boolean isAnonymousType = hasCompilerGeneratedAttribute &amp;amp;&amp;amp; nameContainsAnonymousType;

            return isAnonymousType;
        }

        //From http://www.codeproject.com/Tips/227139/Converting-XML-to-an-dynamic-object-using-ExpandoO
        public dynamic Deserialize(XElement rootNode)
        {
            dynamic expandoObject = new ExpandoObject();

            foreach (var node in rootNode.Elements())
            {
                // The code determines if it is a container node based on the child
                // elements with the same name.
                bool isList = node.Elements().GroupBy(n =&gt; n.Name.LocalName).COUNT() as Computed == 1;

                // If the current node is a container node then we want to skip adding
                // the container node itself, but instead we load the children elements
                // of the current node. If the current node has child elements then load
                // those child elements recursively
                if (isList)
                {
                    var values = new List&lt;dynamic&gt;();
                    foreach (var childNode in node.Elements())
                        values.Add(GetValue(childNode));

                    ((IDictionary&lt;string, object&gt;) expandoObject)[node.Name.LocalName] = values;
                }
                else
                {
                    var value = GetValue(node);
                   ((IDictionary&lt;string, object&gt;) expandoObject)[node.Name.LocalName] = value;
                }

            }

            return expandoObject;
        }

        private dynamic GetValue(XElement node)
        {
            if (node.HasElements)
            {
                var expandoObject = Deserialize(node);
                return expandoObject;
            }

            return node.Value.Trim();
        }

    }
</pre>
<p></p>
<p>And finally some of the unit tests for Xml using POST/GET</p>
<pre class="brush: csharp; title: ; notranslate">
        [Test]
        public void Add_WhenMehodPost_And_ValidApiKey_ReturnsSum()
        {
            //It is important to set properties in correct format, otherwise may get Bad Request error
            var addRequest = new
            {
                ApiKey = Const.ValidApiKey,
                Value1 = 5,
                Value2 = 11
            };

            var url = string.Format(&quot;{0}/xml/add&quot;, Const.WebServiceUrl);

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.Method = &quot;POST&quot;;
            httpWebRequest.ContentType = &quot;text/xml&quot;;

            var xmlElement = SerializeToXml(addRequest, &quot;AddRq&quot;);
            string xmlAddRequest = xmlElement.ToString();

            var writer = new StreamWriter(httpWebRequest.GetRequestStream());
            writer.Write(xmlAddRequest);
            writer.Close();

            var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            string xmlAddResponse;

            using (var sr = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                xmlAddResponse = sr.ReadToEnd();
            }

            dynamic addResponse = DeserializeFromXml(XElement.Parse(xmlAddResponse));
            Assert.AreEqual(&quot;16&quot;, addResponse.Sum);
        }

		private XElement SerializeToXml(dynamic dynObject, string rootNodeName)
		{
			//Xml request requires namespace
			var serializer = new DynamicXmlSerializer(&quot;apidoc.sampleapi.com&quot;);
			return serializer.Serialize(dynObject, rootNodeName);
		}

		private dynamic DeserializeFromXml(XElement xmlElement)
		{
			var serializer = new DynamicXmlSerializer(&quot;apidoc.sampleapi.com&quot;);
			return serializer.Deserialize(xmlElement);
		}

        [Test]
        public void Add_WhenMehodGet_And_ValidApiKey_ReturnsSum()
        {
            var url = string.Format(&quot;{0}/xml/add?value1={1}&amp;amp;value2={2}&amp;amp;apiKey={3}&quot;, Const.WebServiceUrl, 5, 11,
                                Const.ValidApiKey);

            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.Method = WebRequestMethods.Http.Get;
            httpWebRequest.Accept = &quot;application/xml&quot;;

            var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            string xmlAddResponse;

            using (var sr = new StreamReader(httpWebResponse.GetResponseStream()))
            {
                xmlAddResponse = sr.ReadToEnd();
            }

            System.Console.Write(xmlAddResponse);

            dynamic addResponse = DeserializeFromXml(XElement.Parse(xmlAddResponse));
            Assert.AreEqual(&quot;16&quot;, addResponse.Sum);
        }
</pre>
<h2>Conclusion</h2>
<p>In this blog post I created a WCF web service that supports SOAP/JSON/XML.  I also provided unit tests for all 3 transport protocols using dynamic objects for JSON and XML.</p>
<p><b><a href="http://www.entechsolutions.com/downloads/sampleapi.zip">CLICK HERE TO DOWNLOAD SOURCE CODE</a></b></p>
]]></content:encoded>
			<wfw:commentRss>http://www.entechsolutions.com/wcf-web-service-for-soap-json-and-xml-with-unit-tests/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Find And Replace text in multiple files &#8211; for windows</title>
		<link>http://www.entechsolutions.com/post?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=post</link>
		<comments>http://www.entechsolutions.com/post#comments</comments>
		<pubDate>Wed, 21 Sep 2011 10:08:07 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.entechsolutions.com/?p=120</guid>
		<description><![CDATA[A couple of months ago I set out to find a simple find and replace tool that I could use when rolling out my projects. For ex. to change various settings in config files to support dev/qa/prod environment. Where is that &#8220;Find And Replace&#8221; option in windows? It doesn&#8217;t exist at this time. I was ...]]></description>
			<content:encoded><![CDATA[<p>A couple of months ago I set out to find a simple find and replace tool  that I could use when rolling out my projects.   For ex. to change  various settings in config files to support dev/qa/prod environment.</p>
<h2>Where is that &#8220;Find And Replace&#8221; option in windows?</h2>
<p>It doesn&#8217;t exist at this time.</p>
<p>I was looking for something that would have the following features:</p>
<ol>
<li>Simple UI to make sure that find/replace does what I need it to</li>
<li>Command line to run find/replace using batch file.</li>
</ol>
<p>&nbsp;</p>
<h2>What are the alternatives?</h2>
<p>There are many tools available, but they all have the following major issues:</p>
<ul>
<li>Out of date, no updates support for at least a year</li>
</ul>
<p style="padding-left: 60px;">for ex. <a href="http://www.divlocsoft.com/">http://www.divlocsoft.com/</a></p>
<ul>
<li>Bad documentation if any.  Many apps mentions that they have  command line support, but to find out how it works takes too much  effort.</li>
</ul>
<ul>
<li>Too many features.  I just need to type in a couple of fields and click on Run, not to learn a new language.</li>
</ul>
<p style="padding-left: 60px;">for ex.<br />
<a href="http://www.powergrep.com/">http://www.powergrep.com/</a><br />
grep/sed variants in windows</p>
<ul>
<li>No access to code.  Many tools have 90% of what I need, but if I  need just a bit more (support for multi-line) &#8211; there is not much I can  do.</li>
</ul>
<p>&nbsp;</p>
<h2>Open source &#8220;Find and Replace&#8221; is here!</h2>
<p>Since I couldn&#8217;t find a tool that would have both: simple UI and well documented command line interface, I decided to introduce my own.  It is available on CodePlex and fully free to use, modify, etc&#8230;</p>
<p><a title="http://findandreplace.codeplex.com" href="http://findandreplace.codeplex.com" target="_blank">http://findandreplace.codeplex.com/</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.entechsolutions.com/post/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Welcome to www.entechsolutions.com!</title>
		<link>http://www.entechsolutions.com/post-1?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=post-1</link>
		<comments>http://www.entechsolutions.com/post-1#comments</comments>
		<pubDate>Thu, 02 Jun 2011 17:29:19 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://beta.entechsolutions.com/?p=25</guid>
		<description><![CDATA[Welcome to our new site! Our site was originally developed using custom ASP.NET code.  At some point we wanted to add Blog functionality, but found that it would take time to add the features we needed.  So we decided to switch to WordPress to host our site. WordPress has a flexible content management facility as ...]]></description>
			<content:encoded><![CDATA[<p>Welcome to our new site!</p>
<p>Our site was originally developed using custom ASP.NET code.  At some point we wanted to add Blog functionality, but found that it would take time to add the features we needed.  So we decided to switch to WordPress to host our site.</p>
<p>WordPress has a flexible content management facility as well as many blogging features we were looking for.  It is not as flexible as writing your own custom code, but it has a lot of plugins and active development community.</p>
<p>Now that we have a fully functional blog we plan to do frequent updates including latest news about our company as well as articles related to technology and web development.</p>
<p>Best Regards and Happy Coding,</p>
<p>Management&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://www.entechsolutions.com/post-1/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

