<?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, 16 Apr 2012 12:44:57 +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>How to detect if file is text or binary using C#?</title>
		<link>http://www.entechsolutions.com/how-to-detect-if-file-is-text-or-binary-using-c?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=how-to-detect-if-file-is-text-or-binary-using-c</link>
		<comments>http://www.entechsolutions.com/how-to-detect-if-file-is-text-or-binary-using-c#comments</comments>
		<pubDate>Mon, 16 Apr 2012 11:49:09 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://www.entechsolutions.com/?p=1171</guid>
		<description><![CDATA[When I was working on fnr.exe (Find and Replace Tool), I discovered that it was replacing text in both text and binary files. I figured that replacing text in binary files wasn&#8217;t very safe, so I wanted to exclude binary files from the list of files being searched. After some research, I determined that there ...]]></description>
			<content:encoded><![CDATA[<p>When I was working on <a href="http://findandreplace.codeplexe.com" _targe="blank">fnr.exe (Find and Replace Tool)</a>, I discovered that it was replacing text in both text and binary files.  I figured that replacing text in binary files wasn&#8217;t very safe, so I wanted to exclude binary files from the list of files being searched.</p>
<p>After some research, I determined that there is no 100% way to detect if file is binary or text.  But I did find a solution that worked in all my tests.  It is mentioned here:<br />
<a href="http://stackoverflow.com/questions/910873/how-can-i-determine-if-a-file-is-binary-or-text-in-c" _targe="blank">http://stackoverflow.com/questions/910873/how-can-i-determine-if-a-file-is-binary-or-text-in-c</a></p>
<style>
    a:link {color: blue; text-decoration: underline; }
    a:active {color: blue; text-decoration: underline; }
    a:visited {color: blue; text-decoration: underline; }
    a:hover {color: blue; text-decoration: none; }
</style>
<p>Here is the implementation of detecting 4 consecutive binary zeroes using C#:</p>
<pre class="brush: csharp; title: ; notranslate">

	private bool IsBinaryFile(string filePath, int sampleSize = 10240)
	{
		if (!File.Exists(filePath))
			throw  new ArgumentException(&quot;File path is not valid&quot;, &quot;filePath&quot;);

		var buffer = new char[sampleSize];
		string sampleContent;

		using (var sr = new StreamReader(filePath))
		{
			int length = sr.Read(buffer, 0, sampleSize);
			sampleContent = new string(buffer, 0, length);
		}

		//Look for 4 consecutive binary zeroes
		if (sampleContent.Contains(&quot;&#92;&#48;&#92;&#48;&#92;&#48;&#92;&#48;&quot;))
			return true;

		return false;
	}
</pre>
<p>Default value of sample size is 10KB.  I tried lowering it to 1KB, but then detection stopped working for some of the PDF files.  So with 10KB limit you should be pretty safe.</p>
<p>I created a very simple sample application, so you can try this code out for yourself:</p>
<p><a href="http://dl.dropbox.com/u/25924236/ENTechBlog/BinaryFileChecker/BinaryFileChecker.exe">CLICK HERE TO DOWNLOAD SAMPLE EXE (Single file CheckBinaryFile.exe 11K)</a></p>
<p>Here is the code for Sample Application</p>
<p><a href="http://dl.dropbox.com/u/25924236/ENTechBlog/BinaryFileChecker/BinaryFileChecker.zip">CLICK HERE TO DOWNLOAD SAMPLE CODE (CheckBinaryFile.zip 16K)</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.entechsolutions.com/how-to-detect-if-file-is-text-or-binary-using-c/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Browser Alerts with ASP.NET 4.5 and SignalR</title>
		<link>http://www.entechsolutions.com/browser-alerts-with-asp-net-4-5-and-signalr?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=browser-alerts-with-asp-net-4-5-and-signalr</link>
		<comments>http://www.entechsolutions.com/browser-alerts-with-asp-net-4-5-and-signalr#comments</comments>
		<pubDate>Wed, 04 Apr 2012 13:48:36 +0000</pubDate>
		<dc:creator>sarah</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.entechsolutions.com/?p=1010</guid>
		<description><![CDATA[With the advent of the WebSocket protocol, we can finally push data to browsers at will. I went over the details of the protocol in my last blog so I won&#8217;t go over them again here. To sum it up, the protocol allows a browser to maintain a secure bi-directional connection with the server so ...]]></description>
			<content:encoded><![CDATA[<p>With the advent of the <a target="_blank" href="http://www.websocket.org/">WebSocket</a> protocol, we can finally push data to browsers at will. I went over the details of the protocol in my last <a   target="_blank" href="http://www.entechsolutions.com/hooks-and-sockets-for-web-apps">blog</a> so I won&#8217;t go over them again here.  To sum it up, the protocol allows a browser to maintain a secure bi-directional connection with the server so they can talk back and forth without initiating new requests and passing new headers.  This is great! Let&#8217;s go ahead and use it!</p>
<p>I wanted to write a simple browser alert app which, as the name implies, alerts the browser when something occurs server side. I just want to show a little popup of sorts in the window alerting the user of whatever happened on the server. And, to take it a step further, I want to have the browser respond to something that occurs on a remote server using a <a href="http://wiki.webhooks.org/w/page/13385124/FrontPage" target="_blank">WebHook</a>.</p>
<p>Awesome! Let&#8217;s do it!</p>
<p>Two (big) problems:</p>
<p>1. This is going to take a lot of dev time to implement. Sure, browsers can support the protocol, but now we have to code the server side. This is low level stuff that involves managing connections. I don&#8217;t want to do this. After all, I&#8217;m a .NET programmer not a C++ programmer. <img src='http://www.entechsolutions.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>2.  Not all browsers support it. More importantly, even when the latest browsers do all support it, we really can&#8217;t tell all our users to upgrade just so we can take advantage of this cool new technology.</p>
<p>Luckily, these two obstacles aren&#8217;t really obstacles.  Someone already invented the wheel so we don&#8217;t have to.  The wheels we will use are called <a   target="_blank"  href="http://nuget.org/packages/Microsoft.WebSockets">Microsoft.WebSockets</a> and <a  target="_blank"  href="http://signalr.net/">SignalR</a>.</p>
<h2>ASP.NET 4.5 WebSocket Support</h2>
<p>Running ASP.NET 4.5 on Windows 8 allows you to take advantage of the <a   target="_blank"  href="http://nuget.org/packages/Microsoft.WebSockets">Microsoft.WebSockets</a> library.  This takes care of all the work necessary to manage WebSocket connections on the server side.  There is a class called <strong>WebSocketHandler </strong>which you can inherit and simply override methods like <strong>OnOpen</strong>, <strong>OnClose</strong>, and <strong>OnMessage </strong>to handle requests. Clients are stored in a <strong>WebSocketCollection </strong>and completely managed.  You need to do little more than inherit this class. I am not including an example of this because there are already a few excellent articles and samples. You need to run .NET 4.5 on IIS8 with the WebSocket feature enabled. You can learn all about it by watching Paul Batum&#8217;s wonderfully informative presentation and following his step by step instructions here:  <a  target="_blank"  href="http://www.paulbatum.com/2011/09/getting-started-with-websockets-in.html">http://www.paulbatum.com/2011/09/getting-started-with-websockets-in.html</a>. </p>
<p>So problem # 1 is solved as soon as we upgrade to Windows 8. But what about our users on old browsers. And what if we don&#8217;t yet have Windows 8. In terms of old browsers, generally the approach is to fallback to long polling when WebSockets are not supported. OK, we can long poll. But now we need to write a whole bunch of code to manage this. </p>
<h2>SignalR</h2>
<p>This is where <a  target="_blank"  href="http://signalr.net/">SignalR</a> comes in. SignalR is a set of .NET libraries that does all this and more. In a nutshell, SignalR lets you declare client side JavaScript methods which can be called server side, and server side C# methods that can be called from the browser.  It uses WebSockets but gracefully falls back to long polling when it is not supported, so we don&#8217;t have to worry about our users using old browsers.  There is a SignalR.WebSockets library which depends on Microsoft.WebSockets for use on Windows 8. You can install this library and SignalR will automatically use web sockets when it can. <a target="_blank" href="https://github.com/SignalR/SignalR/wiki/WebSockets">More Info</a></p>
<p>This is how you do it:</p>
<p>1. Create a new empty Web Application project. </p>
<p>2. Add SignalR to your project.  Go to &#8220;Tools&#8221; &#8211;> &#8220;Library Package Manager&#8221; &#8211;> &#8220;Package Manager Console&#8221;. Simply type  &#8220;Import-Package SignalR&#8221; at the command prompt and it will install all the libraries you need into your project. It will add compiled libraries as well as JavaScript files, including jQuery.  </p>
<p>Now you&#8217;re ready to start coding.  And there won&#8217;t be much of that!</p>
<p>Create a new server side class which inherits from SignalR&#8217;s &#8220;Hub&#8221; class.  The SignalR framework will know that all classes derived from &#8220;Hub&#8221; should be exposed to the client side. </p>
<pre class="brush: csharp; title: ; notranslate">
using SignalR.Hubs;
using System.Threading.Tasks;

 public class ChatHub : Hub
  {
        public Task Join()
        {
            // tells SignalR to call client side method &quot;receiveAlertMessage&quot; with these params
            return Clients.receiveAlertMessage (Context.ConnectionId + &quot; joined the server&quot;);

       }
  }
</pre>
<p>The methods in this class will be available on the client side. So in JavaScript we can call the &#8220;Join&#8221; method.  On the server side in this method, we will use the &#8220;Clients&#8221; object to reference all connected client browsers, and then we can call a client side method &#8220;receiveAlertMessage&#8221; on all of the browsers.  All the browsers will have this method invoked and receive the data passed to it.</p>
<p>On the client side of things, you need to make some JavaScript references and create the connection.</p>
<p>These are the JavaScript libraries:</p>
<pre class="brush: jscript; title: ; notranslate">
  &lt;script src=&quot;Scripts/jquery-1.6.4.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;Scripts/jquery.signalR.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
  &lt;script src=&quot;/signalr/hubs&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
</pre>
<p>jQuery and the signalR.js will be installed with the signalR package. The signalr/hubs file does not actually exist on the server. It is a dynamically generated JavaScript file.  You must include this line for signalR to work.</p>
<p>Once you have these scripts included, the browser can create a connection using <i>$.connection.chatHub</i> where &#8220;chatHub&#8221; is the name of your server side class inheriting from &#8220;Hub&#8221;. Once initiated, our connection is established and we can talk back and forth. </p>
<pre class="brush: jscript; title: ; notranslate">
       $(function () {
            // Create proxy
            var chatHub = $.connection.chatHub;

           // Start the connection
            $.connection.hub.start();
        });
</pre>
<p>The object you created on the client, <i>chatHub</i>, is your proxy to the server. You can use it to call methods on the server.  In this example the client won&#8217;t call the server, the server only calls the client to alert it when something happens.</p>
<p>To create a method on the client side to be called by the server, simply assign a function to the connection object you created, <i>chatHub</i>. Here I have a client side method called &#8220;receiveAlertMessage&#8221; which the server can call whenever it wants to tell the browser something.</p>
<p>Here is the client side code in its totality.</p>
<pre class="brush: jscript; title: ; notranslate">
      $(function () {
            // Create proxy
            var chatHub = $.connection.chatHub;

            // Assign client side function to be called by the server
            chatHub.receiveAlertMessage = function (source, type, data) {
                closeAlert();
                $('&lt;li/&gt;').html(data).appendTo($('#alert-messages'));
                showAlert();
            };

            // Start the connection
            $.connection.hub.start(function () {
                // connection may take some time to initiate
                $('.loading').hide();
                $('.content').show();
            });
        });
</pre>
<p><br/><br />
To call this method from the server, simply use the following code anywhere in your application. This code gets all the clients and calls the client side method &#8220;receiveAlertMessage&#8221; with the specified parameters. The client side will do what it wants with this information. In our case it displays an alert to the user.</p>
<pre class="brush: csharp; title: ; notranslate">using SignalR.Infrastructure;
using SignalR.Configuration;
using SignalR.Hosting.AspNet;
using SignalR;
using System.Threading.Tasks;

var connectionManager = AspNetHost.DependencyResolver.Resolve&lt;IConnectionManager&gt;();
dynamic clients = connectionManager.GetClients&lt;ChatHub&gt;();
clients.receiveAlertMessage(source, type, data);
</pre>
<p></p>
<h2>Taking it further with WebHooks</h2>
<p>To take this a step further, the browser can respond to something that happens on a remote system by being a consumer of a  <a href="http://wiki.webhooks.org/w/page/13385124/FrontPage" target="_blank">WebHook</a>.  A WebHook provider is some system that will post data to a callback url you supply when something happens that you want to know about.  As a WebHook consumer, upon receiving this data on your server, you can use SignalR to let the browser know. </p>
<p>In my sample app, there are two web applications called  &#8220;RemoteServer&#8221; and &#8220;MySocketApp&#8221;.  The &#8220;RemoteServer&#8221; application acts as a WebHook provider. When something happens on this server, it will tell all of the subscribed WebHook clients by sending an HTTP post request to the callback urls supplied by the these clients.  &#8220;MySocketApp&#8221; contains a WCF service which serves as a callback url and listens for any data sent by the &#8220;RemoteServer&#8221;. When the service receives some data, it will use SignalR to alert the browser of the new data it received. </p>
<p>I will not go into more details about the WebHook implementation as it is described in detail in my last <a  target="_blank"  href="http://www.entechsolutions.com/hooks-and-sockets-for-web-apps">blog</a>.</p>
<h2>Demo</h2>
<p>I created a poor quality screen cast so you know it works without opening the sln. Sorry, it is much more fun to play with the actual app and I will try to put one online. Here is the video: <a   target="_blank"  href="http://vimeo.com/39857434">http://vimeo.com/39857434</a>.  </p>
<p>The video demonstrates FireFox, IE, and Chrome all responding to an event from a &#8220;RemoteServer&#8221; by showing an alert on the screen. </p>
<h2>Download</h2>
<p>VS2011 sln:<br />
<a  target="_blank"   href="http://sarahleahwolfe.com/MySocketApp.zip">http://sarahleahwolfe.com/MySocketApp.zip</a></p>
<p>The solution contains two web projects, RemoteServer and MySocketApp.  </p>
<p>To run the projects, run MySocketApp&#8217;s default.html in a browser. Then run RemoteServer&#8217;s CreateEvent.html in a browser. Enter some text into the form on this CreateEvent page. The text you enter will be posted to a callback url on MySocketApp.  The callback url will use SignalR to then send this data to the browser and display it on the screen. You will see your text appear in the browser running MySocketApp&#8217;s default.html.</p>
<p><i>Note</i>: This sample does not rely on Microsoft.WebSockets and can be ran in older versions of Windows. For it to use Microsoft.WebSockets on Windows 8, we need to install SignalR.WebSockets and we can not use Express IIS. <a target="_blank" href="https://github.com/SignalR/SignalR/wiki/WebSockets">More Info</a></p>
<h2>Warning</h2>
<p>While not difficult to prevent with some HTML encoding, the combination of WebHooks and pushing data to the browser is potentially a recipe to get your site hacked by JavaScript injection.  Also, the issues of performance, server load, and how well signalR will scale are <strong>critical </strong>considerations. </p>
<h2>Links</h2>
<p>SignalR Hubs QuickStart    ( Basically sums up my entire article )<br />
<a  target="_blank"  href="https://github.com/SignalR/SignalR/wiki/QuickStart-Hubs">https://github.com/SignalR/SignalR/wiki/QuickStart-Hubs/</a> </p>
<p>SignalR<br />
<a  target="_blank"  href="http://signalr.net/">http://signalr.net/</a> </p>
<p>Performance Tuning SignalR<br />
<a href="https://github.com/SignalR/SignalR/wiki/Performance" target="_blank">https://github.com/SignalR/SignalR/wiki/Performance</a></p>
<p>Microsoft.WebSockets<br />
<a   target="_blank"  href="http://nuget.org/packages/Microsoft.WebSockets">http://nuget.org/packages/Microsoft.WebSockets</a></p>
<p>Paul Batum&#8217;s Samples and Presentation<br />
 <a  target="_blank"  href="http://www.paulbatum.com/2011/09/getting-started-with-websockets-in.html">http://www.paulbatum.com/2011/09/getting-started-with-websockets-in.html</a></p>
<p>WebSockets<br />
<a target="_blank" href="http://www.websocket.org/">http://www.websocket.org</a> </p>
<p>WebHooks<br />
<a href="http://wiki.webhooks.org/w/page/13385124/FrontPage" target="_blank">http://wiki.webhooks.org/w/page/13385124/FrontPage</a></p>
<style type="text/css">
#post-1010 a { color: blue; }
#post-1010 a:hover { color: #999; }
</style>
]]></content:encoded>
			<wfw:commentRss>http://www.entechsolutions.com/browser-alerts-with-asp-net-4-5-and-signalr/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Find And Replace (fnr.exe) 1.1 Released</title>
		<link>http://www.entechsolutions.com/find-and-replace-fnr-exe-1-1-released?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=find-and-replace-fnr-exe-1-1-released</link>
		<comments>http://www.entechsolutions.com/find-and-replace-fnr-exe-1-1-released#comments</comments>
		<pubDate>Fri, 30 Mar 2012 18:56:22 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.entechsolutions.com/?p=963</guid>
		<description><![CDATA[You can download release 1.1 from here: http://findandreplace.codeplex.com The new version contains several fixes and improvements. Added Cancel button to cancel long running Find or Replace operations Allow multiple File Masks Previously you would need to either use &#8220;*.*&#8221; or run Replace multiple times, once for each file mask. This new feature allows you to ...]]></description>
			<content:encoded><![CDATA[<p>You can download release 1.1 from here:<br />
<a href="http://findandreplace.codeplex.com" target="_blank">http://findandreplace.codeplex.com</a></p>
<p>The new version contains several fixes and improvements.</p>
<h3>Added Cancel button to cancel long running Find or Replace operations</h3>
<p><a href="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace11_Cancel.png"><img src="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace11_Cancel-580x322.png" alt="Allow Canceling long running operation" title="FindAndReplace11_Cancel" width="580" height="322" class="size-large wp-image-964" /></a></p>
<h3>Allow multiple File Masks</h3>
<p>Previously you would need to either use &#8220;*.*&#8221; or run Replace multiple times, once for each file mask.  This new feature allows you to specify multiple, comma delimited file masks to limit which files you would like to process.</p>
<p><a href="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace11_FileMask_Multiple.png"><img src="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace11_FileMask_Multiple-580x322.png" alt="Multiple File Masks" title="FindAndReplace11_FileMask_Multiple" width="580" height="322" class="size-large wp-image-966" /></a></p>
<h3>Can exclude File Mask</h3>
<p>In many cases it is a lot more efficient to explicitly exclude known binary files like *.exe, *.dll instead of having fnr.exe detect that they are binary.</p>
<p><a href="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace11_Exclude_FileMask.png"><img src="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace11_Exclude_FileMask-580x322.png" alt="Exclude File Masks" title="FindAndReplace11_Exclude_FileMask" width="580" height="322" class="alignnone size-large wp-image-965" /></a></p>
<h3>Detect text file encoding</h3>
<p>There was a bug in last release where fnr.exe would load a file with some foreign characters like &#8216;ç&#8217;  and &#8216;ã&#8217;, but wouldn&#8217;t detect the encoding of the file.  When file with replacements was saved, some of these characters could have been replaced with &#8216;invalid&#8217; chars.<br />
This issue has been fixed and now fnr.exe supports all international files.</p>
<p><a href="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace11_Unicode.png"><img src="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace11_Unicode-580x443.png" alt="Detect Text File Encoding" title="FindAndReplace11_Unicode" width="580" height="443" class="alignnone size-large wp-image-967" /></a></p>
<p>While testing this new feature on command line I discovered that batch files are not very good in dealing with characters above, passed in findText or replaceText.  I found a good solution here:<br />
<a href="http://stackoverflow.com/questions/1427796/batch-file-encoding">http://stackoverflow.com/questions/1427796/batch-file-encoding</a>.  It worked great.</p>
<h3>Persist form values in Registry</h3>
<p>When user clicks Find or Replace button and validation passes &#8211; the application will save form values into registry, so when you open fnr.exe next time, the form values will be pre-filled with last valid state.</p>
<h3>Download Link</h3>
<p>You can download fnr.exe 1.1 from here:<br />
<a href="http://findandreplace.codeplex.com" target="_blank">http://findandreplace.codeplex.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.entechsolutions.com/find-and-replace-fnr-exe-1-1-released/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>On WCF</title>
		<link>http://www.entechsolutions.com/on-wcf?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=on-wcf</link>
		<comments>http://www.entechsolutions.com/on-wcf#comments</comments>
		<pubDate>Thu, 15 Mar 2012 06:59:58 +0000</pubDate>
		<dc:creator>anup</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://www.entechsolutions.com/?p=949</guid>
		<description><![CDATA[In this blog, I will talk about WCF basics. Windows Communication Foundation (WCF) is a framework that provides a runtime environment to expose and consume services. A service is a unit of functionality exposed to the world. The client of a service consumes the functionality provides by the service. Clients and services talk with each ...]]></description>
			<content:encoded><![CDATA[<p><strong>In this blog, I will talk about WCF basics.</strong></p>
<p>Windows Communication Foundation (<strong>WCF</strong>) is a framework that provides a runtime environment to expose and consume services.</p>
<p>A <strong>service </strong>is a unit of functionality exposed to the world. The <strong>client </strong>of a service consumes the functionality provides by the service.</p>
<p>Clients and services talk with each other by sending and receiving <strong>messages</strong>, usually <strong>SOAP, XML</strong>, or <strong>JSON </strong>messages.</p>
<p><strong>WCF </strong>services communicate over transport schemes –<strong> HTTP/HTTPS, TCP, IPC, Peer network, MSMQ, Service bus</strong>.</p>
<p><strong>WCF </strong>exposes <strong>metadata </strong>describing the available functionality and possible ways of communicating with the service.  Metadata is published in <strong>WSDL </strong>(Web Services Description Language) format.</p>
<p>Client always use <strong>proxy </strong>to forward calls to the service and never interacts with the service directly. All services expose <strong>contracts </strong>namely -</p>
<ul>
<li><strong>Service Contracts:</strong> Describe what operation the client can perform on service</li>
<li><strong>Data Contracts</strong>: Define what data types are passed to and from the service</li>
<li><strong>Fault Contracts</strong>: Define errors raised by service and how the service handles and forwards the error to the client</li>
<li><strong>Message Contracts</strong>:  Allow the service to interact directly with message.</li>
</ul>
<p>&nbsp;</p>
<p><strong>WCF </strong>service is hosted in a Windows process called <strong>host process</strong>. A single host process can host multiple services, and the same service type can be hosted in multiple host process.</p>
<p>WCF groups together sets of communication aspects called <strong>bindings</strong>. <strong>Binding </strong>is a set of choices regarding the transport protocol, message encoding, communication pattern, reliability, security, transaction propagation, and interoperability. Clients must use the exact same binding values as the service.</p>
<p>Every service is associated with an <strong>address </strong>that defines where the service is, a binding that defines how to communicate with the service, and a contract that defines what the service does. The fusion of the address, contract, and binding is the <strong>Endpoint</strong>.</p>
<p>Every service must expose at least one business endpoint, and each endpoint has exactly one contract. All endpoints on a service have unique address, and a single service can expose multiple endpoints.</p>
<p>A client needs to import the service contract to its native representation to invoke operation on a service.</p>
<p><strong>History of WCF</strong></p>
<ul>
<li> First release as part of .NET 3.0</li>
<li> Second release as part of .NET 3.5</li>
<li> Third release as part of .NET 4.0</li>
<li> With addition of various new features as of .NET 4.5 beta</li>
</ul>
<p>&nbsp;</p>
<p>These are some basic concepts on WCF to help anyone get started.</p>
<p><em>Credit: Materials in the blog is derived from the book “Programming WCF Services, 3rd edition” by – Juval Löwy</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.entechsolutions.com/on-wcf/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Announcing Find And Replace (fnr.exe) 1.0</title>
		<link>http://www.entechsolutions.com/announcing-find-and-replace-fnr-exe-1-0?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=announcing-find-and-replace-fnr-exe-1-0</link>
		<comments>http://www.entechsolutions.com/announcing-find-and-replace-fnr-exe-1-0#comments</comments>
		<pubDate>Fri, 09 Mar 2012 12:49:09 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[Utility]]></category>

		<guid isPermaLink="false">http://www.entechsolutions.com/?p=883</guid>
		<description><![CDATA[I am super excited to announce the first Stable release of Find and Replace. It contains some major improvements and bug fixes that make fnr.exe the best free open source utility to do batch text replace. At this time it is the only utility that seamlessly supports both windows form as well as command line ...]]></description>
			<content:encoded><![CDATA[<p>I am super excited to announce the first Stable release of Find and Replace.</p>
<p>It contains some major improvements and bug fixes that make fnr.exe the best free open source utility to do batch text replace.  At this time it is the only utility that seamlessly supports both windows form as well as command line interface.</p>
<p>You can download release 1.0 from here:<br />
<a href="http://findandreplace.codeplex.com" target="_blank">http://findandreplace.codeplex.com</a></p>
<p>Here is a list of the features added in this release:</p>
<h3>Preview Matches</h3>
<p>Selecting a row in results grid will display a preview box highlighting all the occurrences of matching text</p>
<p><a href="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_HighlightingMatches.png"><img class="size-large wp-image-884" title="Find And Replace (fnr.exe) - preview matches" src="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_HighlightingMatches-580x435.png" alt="Find And Replace (fnr.exe) - preview matches" width="580" height="435" /></a></p>
<h3>Stats</h3>
<p>Recording and displaying the statistics related to the search, such as<br />
Number of files processed, with matches, failes to open, etc..</p>
<p><a href="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_Stats.png"><img class="size-large wp-image-899" title="Find And Replace (fnr.exe) - preview matches" src="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_Stats-580x317.png" alt="Find And Replace (fnr.exe) - statistics" width="580" height="317" /></a></p>
<p>The statistics in windows form are updated in real time as the search is happening.<br />
When running find/replace on command line statistics are displayed at the end.</p>
<h3>File errors for read/write</h3>
<p>If file can&#8217;t be open for read or write, we indicate that in the results and statistics</p>
<p><a href="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_FileErrors.png"><img class="size-large wp-image-897" title="FindAndReplace10_FileErrors" src="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_FileErrors-580x317.png" alt="Find And Replace (fnr.exe) - file errors" width="580" height="317" /></a></p>
<h3>Support for regular expressions</h3>
<p>Added checkbox to allow finding text using regular expressions</p>
<p><a href="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_RegEx.png"><img class="size-large wp-image-898" title="FindAndReplace10_RegEx" src="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_RegEx-580x435.png" alt="Find And Replace (fnr.exe) - regular expressions" width="580" height="435" /></a></p>
<h3>Fixed a bug that required you to press enter to continue after running fnr.exe from command line</h3>
<p>This issue made it difficult to include call to fnr.exe in batch files.</p>
<h3>Context menu to display containing folder or open the file</h3>
<p><a href="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_ContextMenu.png"><img class="size-large wp-image-895" title="FindAndReplace10_ContextMenu" src="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_ContextMenu-580x434.png" alt="Find And Replace (fnr.exe) - context menu" width="580" height="434" /></a></p>
<h3>Double click on results row to open the file (similar to double clicking in windows explorer)</h3>
<p><a href="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_DoubleClick.png"><img class="size-large wp-image-896" title="FindAndReplace10_DoubleClick" src="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_DoubleClick-580x345.png" alt="Find And Replace (fnr.exe) - row double click" width="580" height="345" /></a></p>
<h3>Displaying results on command line has been changed from tabular view to the list.</h3>
<p>It makes results much much more readable, without any messy word wrapping.</p>
<p><a href="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_CommandLineCleanup.png"><img class="size-large wp-image-894" title="FindAndReplace10_CommandLineCleanup" src="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_CommandLineCleanup-580x250.png" alt="Find And Replace (fnr.exe) - command line" width="580" height="250" /></a></p>
<h3>Binary detection &#8211; skip files that are binary</h3>
<p><a href="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_Binary.png"><img class="size-large wp-image-893" title="FindAndReplace10_Binary" src="http://www.entechsolutions.com/wp-content/uploads/2012/03/FindAndReplace10_Binary-580x435.png" alt="Find And Replace (fnr.exe) - binary detection" width="580" height="435" /></a></p>
<p>This detection is not 100%, so if possible it is better to use appropriate mask like &#8220;*.txt&#8221;, to limit files to text files.</p>
<h3>Download Link</h3>
<p>You can download fnr.exe 1.0 from here:<br />
<a href="http://findandreplace.codeplex.com" target="_blank">http://findandreplace.codeplex.com</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.entechsolutions.com/announcing-find-and-replace-fnr-exe-1-0/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Logging and Reporting Unhandled Exceptions</title>
		<link>http://www.entechsolutions.com/logging-and-reporting-unhandled-exceptions?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=logging-and-reporting-unhandled-exceptions</link>
		<comments>http://www.entechsolutions.com/logging-and-reporting-unhandled-exceptions#comments</comments>
		<pubDate>Sat, 03 Mar 2012 11:49:35 +0000</pubDate>
		<dc:creator>eric</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[Windows]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[ELMAH]]></category>
		<category><![CDATA[Exception]]></category>
		<category><![CDATA[Unhandled Exception]]></category>

		<guid isPermaLink="false">http://www.entechsolutions.com/?p=735</guid>
		<description><![CDATA[In this post I would like to demonstrate how to minimize unhandled exceptions in your project and how to &#8220;handle&#8221; them by providing logging and reporting capabilities. 100% bug free code I used to work for a company that had a slogan &#8220;100% BUG FREE CODE&#8221; (all slogans must be in caps or they are ...]]></description>
			<content:encoded><![CDATA[<p>In this post I would like to demonstrate how to minimize unhandled exceptions in your project and how to &#8220;handle&#8221; them by providing logging and reporting capabilities.</p>
<h1>100% bug free code</h1>
<p>I used to work for a company that had a slogan &#8220;100% BUG FREE CODE&#8221; (all slogans must be in caps or they are not taken seriously).  </p>
<p>It turned out that &#8220;100% bug free code&#8221; was easily achievable using one of the following approaches.</p>
<style>
    li {padding-top:5px;}
    .line-break {height:1em; visibility:hidden;}
    a:link {color: blue; text-decoration: underline; }
    a:active {color: blue; text-decoration: underline; }
    a:visited {color: blue; text-decoration: underline; }
    a:hover {color: blue; text-decoration: none; }</p>
</style>
<ol>
<li>
The application you are writing will never be released to actual users.   As they say the only way to win is not to play.
</li>
<li>
By using code like this:
<pre class="brush: csharp; title: ; notranslate">
      try
      {
         //do something important, like
         SaveTheWorld();
      }
      catch
      {
          //do nothing.  The world is never saved, and no one knows why.
      }
</pre>
<p>This one I have seen many times, sometimes in a scope of a single function, other times in scope of the whole application.   In theory it solves the problem at hand very nicely.  In reality it just sweeps exceptions under the rug and makes debugging, maintenance and customer support much much harder.</p>
<p>If you know a developer who writes code like this, you are allowed to just walk over and punch (or spin kick) him in the liver.  Then give him a look of &#8220;I pity the fool&#8221; and quickly run away before he recovers. You are only helping him to pay back for some of pain and suffering that he has and will cause.
</li>
<li>
Using unit testing and believing that 100% code coverage is the same as &#8220;100% bug free code&#8217;.    I used to go to the church of unit testing every sunday and after chanting &#8220;Unit tests will result in 100% bug free code&#8221; about a 100 times it really did  feel like all my bugs were just a bad dream (It was a nightmare with an actual huge insect running after me). The only problem was that as much as I would like to think that I can put myself into actual end user shoes (I do have special orthopedic shoes for that), that is 100% impossible.   As soon as your application launches, your customers will generate all kinds of exceptions, some real and some only in the minds of the customers, but mostly real.
</li>
</ol>
<div class="line-break"></div>
<p>There are other lesser known approaches, like whenever there is an exception just redirect a customer to the latest &#8220;<a href="http://www.youtube.com/watch?v=y8Kyi0WNg40&#038;feature=related" target="blank">cute chipmunk</a>&#8221; video on youtube.  When customer sees those cute chipmanks any memories of what they were doing will be quickly forgotten.</p>
<p>That works really great the first several times, but you have to be really careful because in no time customer may be sending you error reports that YouTube videos are freezing.</p>
<h1>Bug vs Unhandled Exception</h1>
<p>Unhandled exceptions are only a subset of all the bugs you will encounter.  Let&#8217;s say there is an error in calculating Order Total, where you forget to add the tax at the end. This is not going to result in exception, but it still a bug since original business requirement was not implemented.  This type of bug is much harder to track since you may have to rely on customer to notice the issue and then report it to you with a bonus of some colorful language.  On the other hand when unhandled exception is triggered &#8211; there are ways to setup your application to log it or send it to you by email.  In this way you can buy yourself a little bit of time by diverting customer to a very informative page:</p>
<blockquote><p>
An internal system error has occurred.  Support has been notified and is looking into the issue.  Would you like to play a game of chess while you wait for the resolution?
</p></blockquote>
<p>And while customer is taking a well deserved break playing chess, you can try to fix the exception or at least add it to your TODO list.</p>
<p>In this post we will only talk about bugs related to unhanded exception being thrown.</p>
<h1>Minimizing Unhanded Exceptions</h1>
<p>In a rare case that one of the approaches in &#8217;100% bug free code&#8217; section fails,  here are some ways to minimize your unhandled exceptions.</p>
<h3>Defensive programming</h3>
<p>It may come as a total surprise to you, but writing good code will actually result in less bugs and unhanded exceptions. Please spread the word.</p>
<p><a href="http://en.wikipedia.org/wiki/Defensive_programming" target="blank">From Wikipedia</a>: &#8220;defensive programming is a form of defensive design intended to ensure the continuing function of a piece of software in spite of unforeseeable usage of said software&#8221;.   That should apply to any code that you write, unless your hobby is to spend your weekends fixing unhanded exceptions that should not have happened in the first place. There are plenty of articles written on the subject of defensive programming, so I will not go into too much details.</p>
<p>I would like to highlight a technique called Parameter Checking that will make your functions a lot less error-prone.  Here is one example:</p>
<pre class="brush: csharp; title: ; notranslate">
void JustAnotherFoo(string iAmNotNull, int iAmPositiveInteger)
{
    //Check that parameters are valid
    if (iAmNotNull == null)
          throw new ArgumentException(&quot;I have identity crisis&quot;, &quot;iAmNotNull&quot;);

     if (iAmPositiveInteger &lt;=1)
           throw new ArgumentException(&quot;I am having a bad day&quot;, &quot;iAmPositiveInteger&quot;);

     //Do some stuff that will sometimes break if iAmNotNull is null
     ....

     //Do some other stuff that could break if iAmPositiveInteger is
     //not what he says he is
     ...
}
</pre>
<p>With code like this, you will catch many of the previously unhandled exceptions before they get a chance to cause all kinds of unforeseen errors.</p>
<p>There are many approaches in C# to implementing parameter checking.  </p>
<ul>
<li>
using fluent notation<br />
<a href="http://conditions.codeplex.com" target="blank">http://conditions.codeplex.com</a>
</li>
<li>
with code contracts already included in CLR<br />
<a href="http://visualstudiomagazine.com/articles/2010/06/23/code-contracts.aspx" target="blank">http://visualstudiomagazine.com/articles/2010/06/23/code-contracts.asp</a>
</li>
<li>
using extension methods<br />
<a href="http://weblogs.asp.net/fredriknormen/archive/2008/05/08/how-to-validate-a-method-s-arguments.aspx" target="blank">http://weblogs.asp.net/fredriknormen/archive/2008/05/08/how-to-validate-a-method-s-arguments.aspx</a>
</li>
</ol>
<div class="line-break"></div>
<h3>Unit testing</h3>
<p>As much as I like to harp on the idea that 100% code coverage can solve all life&#8217;s problems, including better night sleep, more satisfying sex life and even a better customer experience in some cases,  writing unit tests can most certainly prevent many cases of unhanded exceptions.  When a new exception is reported, it is a great practice to write a unit test to reproduce the exception (what in unit testing world is called red circle of doom).  Then you fix the issue and make unit test pass (which in unit testing world is called green circle of awesome happiness).</p>
<h3>Automated testing</h3>
<p>This is more of UI testing using tools like selenium.  This way you can automate common workflows in your application and run through them before each rollout.  These types of tests run a lot slower then unit tests, but are much better at simulating actual end user experience.  The approach where you write unit test to reproduce exception before fixing it, can also be used with Automated tests, in case unit tests are not sufficient to reproduce the issue.</p>
<h3>Manual QA</h3>
<p>In some cases it is very hard to automate a test or try to cover every possible edge case.  Like double clicking on every shiny button on the screen, all at the same time.  Basically what a normal end user does.  In this case we need manual intervention, as in actual humans doing testing.</p>
<p>For this scenario what you do is:</p>
<ol type="a">
<li>Get a couple of QA people</li>
<li>Train them that every time they find an unexpected exception they get a tasty biskit (something you can get in large volume from Costco)</li>
<li>But if they don&#8217;t find any exceptions in certain period of time &#8211; you zap them with ever increasing wattage</li>
<li>By the end of the week you will be out of Biskits and QA people</li>
</ol>
<div class="line-break"> </div>
<h1>The truth about Unhandled Exceptions</h1>
<p>You may want to seat down as it may come as a total shock to you,</p>
<blockquote><p>A program of any complexity is going to have unhandled exceptions.</p></blockquote>
<p>This is really important concept, so please to take your time to fully comprehend it.  At first you may feel a little dizzy and nauseous, but unless your are pregnant, these symptoms may go away in a couple of minutes.  In case you are pregnant though, try prune juice. I hear good things&#8230;</p>
<p>You may repeat the phrase above several times.  Maybe combine it with a bit of Buddhist chanting.  Only when you have accepted the deep meaning in it and you are at peace with yourself, you are ready to proceed.</p>
<h1>Oh &#8220;Wise Exception Guru&#8221;, how should we deal with all these unhandled exceptions?</h1>
<p>There are several ways to deal with unhandled exceptions:</p>
<ol style="list-style:upper-alpha; margin-left:20px;">
<li>
Use a 3rd party tool, like ELMAH (worst or best name evar? you decide).  These tools are usually easy to  integrate with your projects.  After integration, when exception occurs it will be handled by the 3rd party tool and will be stored in DB or another type of storage.  Afterwards you can use UI provided by the 3rd party tool to browse the exceptions.
</li>
<li>
Write your own custom implementation. Why?  Because the gods of coding gave you a rare gift of writing the most readable, most maintainable and most testable code on this planet.  Unfortunately it came with one of the biggest heads on the planet which makes it extremely difficult to get through the door.  An alternative, but much less common reason is that  you were looking for some of the features not offered by any of the 3rd party tools.
</li>
<li>
Just change a name from &#8220;unhandled exceptions&#8221; to &#8220;user errors&#8221;.   Whenever one of these &#8220;user errors&#8221; is reported, there is a scripted reply:</p>
<blockquote><p>
You must have done something wrong.<br />
* If you are using windows, please reboot your computer at least 3 times.<br />
* If you are using IPhone, try pressing THE button or combination of THE button with turn off switch.  That&#8217;s really all you can do.<br />
* If you are using Linux, use Emacs to modify config file to enable detailed logging.  If that doesn&#8217;t present you with the error of your ways, your kernel may require recompiling.
</p></blockquote>
</li>
</ol>
<h1>What do I want in my Exception Logging And Reporting Software (ELARS, because I can)?</h1>
<p>Before evaluating 3rd party solutions, I used a custom solution which worked like this:<br />
Anytime unhandled exception would occur it would trigger an email sent to a gmail account which was setup just for this purpose.  Gmail is extremely nice tool for searching and filtering. It also has some shortcomings that I wanted to address by introducing 3rd party tool or writing a custom solution specifically for handling unhandled exceptions.</p>
<p>Here is a list of features that are a MUST for exception handling software:</p>
<ul>
<li>
<b>Integration with various project types</b><br />
At minimum it should support:</p>
<ul style="margin-left:20px;">
<li>Web Project (ASP.NET, MVC)</li>
<li>Exe Project (Console, Windows Service)</li>
<li>Web Service (WCF)</li>
</ul>
</li>
<div class="line-break"></div>
<li>
<b>Log context information at the time of exception</b><br />
To fix unhandled exception you must be able to reproduce it. Regular ASP.NET exception page usually includes just an error message and stack trace.  Sometimes it is sufficient to reproduce the error, but most of the time we will require input from the end user, like what data they entered in the form, what is their username, what browser they used, etc&#8230;  </p>
<p>Instead, it is a lot more efficient for both developer and the end user, if for every unhandled exception, the application would automatically log all such information.  </p>
<p>For web application I would need:<br />
* Full Url and Query String<br />
* Session Variables<br />
* Request Form Items<br />
* Cookies</p>
<p>For WCF service at a minimum we need to log RawData of the request being passed.</p>
<p>There should also be an option to add custom fields to logged information. For example let&#8217;s say I store current CustomerID in session variable. Whenever I need to find out which customer triggered the exception, I need to run DB query to get customer name.  Instead I could just add a custom field to Exception Log called &#8220;CustomerName&#8221; and run DB query at the time when exception is logged.  Using this custom field can save you a lot of time.
</li>
<li>
  <b>UI to search exceptions</b><br />
When customer reports an unhanlded exception, the first thing I want to do is to find that exception in logs.   As long as the context information related to exception is properly logged this task is pretty trivial, given that there is a flexible UI to list and find exceptions. I would like to be able to search by error message and any other context information mentioned in previous section.
</li>
<li>
  <b>Grouping similar exceptions</b><br />
Some exceptions may occur only once or twice a month, while others may be happening 1000s of times a day.  To be able to prioritize the errors it is important to know how frequently they occur.  When you start logging exceptions in ASP.NET you may find that you are quickly overwhelmed with large number of exceptions being logged.  The solution in most cases is to stop using error log and go back to assuming that your system is working just fine and any end user reports to the contrary are just fabrications from communists.  A better approach is to allow grouping unhandled exceptions by stack trace, error message, url and maybe some other fields specific to your system.  This way instead of list of all error occurrences &#8211; you will get a list of unique errors and how many times they occurred.
</li>
<li>
<b>Integration with bug tracking software</b><br />
Everyone knows that the first step to fixing unhandled exception or any bug is creating a new entry in a bug tracking software.  This way, QA department will know what to test for the next rollout and your boss will know that you are spending most of your time fixing bugs from the last release instead of working on new features that were promised 2 months ago.  It would be great to be able to link the &#8220;Error Group&#8221; from previous bullet point to a bug in Bug Tracking software, so that whenever bug actually gets resolved it can also be udpated Exception Logging software and then we can watch for it to make sure it never (ever ever ever) occurs again.
</li>
<li><b>Reporting (nice to have)</b><br />
To intelligently judge the health of the application, reports should provide information like:<br />
* Number of errors per time period (like day, week, month, etc..). So you can see if your system is getting healthier over time or dying from untreated flu.<br />
* Regions (or namespaces) in your application where most exceptions occur.  So that the developers with least exceptions can order developers with most exceptions to go get coffee, wash their car and maybe even walk the dog.
</li>
</ul>
<div class="line-break"></div>
<h1>What Exception Logging and Reporting software is currently available?</h1>
<ul>
<li><b>Elmah</b><br />
<a href="http://code.google.com/p/elmah" target="blank">http://code.google.com/p/elmah</a><br />
- the grand daddy of them all.  Supports only Web Projects out of the box.</p>
</li>
<li>
<b>Exceptioneer</b><br />
<a href="http://www.exceptioneer.com"  target="blank">http://www.exceptioneer.com</a><br />
- Saas solution to error logging. Seems like a great fit for all the features I mentioned, except it seems like the company went out of business 2 years ago and all that is left is a zombie-site that is down half of the time.  When the site is down the error message is &#8220;Internal exception has been handled by our Excepioneer&#8221;.  Oh the Irony of it all.</p>
</li>
<li>
<b>CodeSmith Insight</b><br />
<a href="http://www.codesmithtools.com/product/insight">http://www.codesmithtools.com/product/insight</a><br />
- exception handling, reporting, bug tracking, customer communication and also makes coffee. But for a price. Plus it only makes regular coffee. Capuccino addon will cost you extra.  </p>
<p>WARNING: I would like to serve notice to CodeSmith marketing deapartment. I noticed that every blog post on the internet that talks about exception handling is usually followed by a comment from you about how your product is all that and makes coffee too. For ex. check out <a href="http://mikehadlow.blogspot.com/2010/02/in-praise-of-elmah.html" target="_blank">comments section here</a>. This is spam and not the <a href="http://en.wikipedia.org/wiki/Spam">good type</a>.</p>
</li>
<li><b>Enterprise Library Error Logger</b><br />
<a href="http://weblogs.asp.net/sukumarraju/archive/2009/10/04/microsoft-enterprise-library-4-1-exception-handling-block.aspx" target="blank">http://weblogs.asp.net/sukumarraju/archive/2009/10/04/microsoft-enterprise-library-4-1-exception-handling-block.aspx</a><br />
- built on top of logging block. Allows logging exceptions to event log, DB, email, etc.</p>
</li>
<ul>
<h1>Indepth evalutation for these tools</h1>
<p>This blog post is getting really long and majority of the people probably dosed off by this point. So I will leave it for another post.</p>
<h1>Conclusion</h1>
<p>In this article I talked about various approaches to handling unhanded exceptions.  </p>
<ul>
<li>If you are a developer you will come away empowered with knowledge that Unhanded exceptions can be handled.</li>
<li>If you are a pregnant woman you will learn of home remedies to use when you feel sick and nauseous</li>
<li>If you are a Unit test junky, you will add scathing comments to this article that will reinforce your beliefs</li>
</ul>
<div class="line-break"></div>
<p>Either way everyone will be happy.</p>
<p>In the next article of this series, we will do a full review of various products available to help with logging and reporting unhandled exceptions.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.entechsolutions.com/logging-and-reporting-unhandled-exceptions/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Stripe for Card Present (Swiped) Transactions</title>
		<link>http://www.entechsolutions.com/stripe-for-card-present-swiped-transactions?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=stripe-for-card-present-swiped-transactions</link>
		<comments>http://www.entechsolutions.com/stripe-for-card-present-swiped-transactions#comments</comments>
		<pubDate>Mon, 27 Feb 2012 04:57:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Ideas]]></category>

		<guid isPermaLink="false">http://www.entechsolutions.com/?p=723</guid>
		<description><![CDATA[There is a lot of innovation happening in Payment space led by Stripe, Square and Paypal and we&#8217;ve been thinking about building few simple APIs to process the payments for Card present transactions. We love Stripe and what they have done with the payment API. We think they have one of the best payment APIs. ...]]></description>
			<content:encoded><![CDATA[<p>There is a lot of innovation happening in Payment space led by Stripe, Square and Paypal and we&#8217;ve been thinking about building few simple APIs to process the payments for Card present transactions.</p>
<p>We love <a title="Stripe.com" href="https://stripe.com/" target="_blank">Stripe </a>and what they have done with the payment API. We think they have one of the best payment APIs.  We&#8217;ve used it on some of our client’s site and suffice it to say we found it pretty awesome. While Stripe provides an amazing API for the internet transactions (card not present), there is a room for a simple API that can process card present (swiped) transactions. As far as I know, Stripe does not yet provide &#8216;Card Present&#8217; types of transactions.</p>
<p>As developers, we help clients build Point of Sale applications where credit card are swiped in a physical terminal and these type of transactions are called &#8216;Card Present&#8217; transactions. Simply, Card Present (CP)transactions are those in which a credit card is physically present with the person and are swiped in physical terminals. Merchants are charged different levels of fees by the card transaction processors (such as Visa, MasterCard), depending on the level of fraud risk, and because the card is available for inspection, are considered less risky and therefore carry lower fees than online or phone transactions.</p>
<p>Why:<br />
It is getting quite easy to make payment terminals on the web, tablets and mobile devices and since these devices are always connected on the web, they can be much smarter and feature rich much like what Square is doing. The web and hand held terminals are much easier to deploy as it just needs browser or an installed app and internet connection and the devices to swipe the credit cards are getting cheaper and readily available, so there are many possibilities to provide innovative payment services to merchants than its current form. Also, considering the mobile handset market is poised to be the biggest market ever &#8211; providing a low-cost, easy-to-use API for any developers to hook payment system will definitely add a lot of excitement and value.</p>
<p>A simple Stipe like API that will be able to simply send the encrypted credit card data through and have all the usual methods like Charge, Void, Sale, Refund etc. would be quite exciting.</p>
<p>These are my initial thought and I will expand more in the future as we hash out more details and as we work on them. If you know of anyone doing similar API for Card Present data, we would love to know. Please leave a note on our comments section.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.entechsolutions.com/stripe-for-card-present-swiped-transactions/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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[WebHook &#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; &#160;&#160;http://wiki.webhooks.org 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 ...]]></description>
			<content:encoded><![CDATA[<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; &nbsp;&nbsp;<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:<br/>&nbsp;</span></div>
<ol style="margin-left: 40px;">
<li><strong>event_type</strong> : ex: &#8220;product_added&#8221;, &#8220;customer_created&#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>
</ol>
<div><br/> What the client does with this information is, of course, entirely up to the client.  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 a simple 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>
<style>
.syntaxhighlighter {
border:1px solid #ccc;
}
.syntaxhighlighter .line.alt2{
  background-color: #F9F9F9 !important;
}
.syntaxhighlighter .line.alt1 {
  background-color: #fff !important;
}
.syntaxhighlighter.nogutter td.code .container textarea, .syntaxhighlighter.nogutter td.code .line {
padding: 3px !important;
padding-left: 5px !important;
padding-right: 5px !important;
}</p>
</style>
<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>
<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 />
	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>
<pre class="brush: plain; title: ; notranslate">
Request URL: ws://localhost:8080/websession
Request Method: GET
Status Code: 101 Switching Protocols

Request Headers
Connection: Upgrade
Host: localhost:8080
Origin: http://localhost:53927
Sec-WebSocket-Key: vPkYt7muES+evHN2AxXasw==
Sec-WebSocket-Version: 13
Upgrade: websocket
(Key3): 00:00:00:00:00:00:00:00

Response Headers
Connection: Upgrade
Sec-WebSocket-Accept: 4+7cCQ4YGQh9jjDlnIRv6qwgVlM=
Upgrade: WebSocket
(Challenge Response): 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00
</pre>
<div><span><b>This is the JavaScript for a browser to initiate the WebSocket connection.</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.
<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>When the server wants to send a new message to the browser, it will write to the client&#8217;s stream like this:
<pre class="brush: csharp; title: ; notranslate">
stream.Write(bufferedMessage, 0, bufferedMessage .Length);
</pre>
<p>Now, a browser can respond to some event that happens on some third party system.<br />
</span></div>
<div><span></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, this example only performs an 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 really nice full implementation in C#: <a href="http://ashishware.com/websocksample.shtml"  target="_blank">http://ashishware.com/websocksample.shtml</a><br />
<br/>Also, .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/><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, but more importantly, 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 time.<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 />
<a rel="nofollow" class="external text" target="_blank" href="http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-75">hixie-75</a><br />
<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><br />
<a rel="nofollow" target="_blank"  class="external text" href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-06">hybi-06</a><br />
<a rel="nofollow" target="_blank" class="external text" href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-07">hybi-07</a><br />
<a rel="nofollow" class="external text" target="_blank" href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-09">hybi-09</a><br />
<a rel="nofollow" class="external text" target="_blank" href="http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10">hybi-10</a><br />
<a class="external mw-magiclink-rfc" target="_blank" href="http://www.entechsolutions.com//tools.ietf.org/html/rfc6455">RFC 6455</a><br />
<br/>
</li>
</ol>
<h3>Some Links</h3>
<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>
</div>
<p><br/><br />
<hr noshade>
<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 />
<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/><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.<br />
<br/>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>2</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>
	</channel>
</rss>

