<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0">
	<channel>
		<title><![CDATA[]]></title>
		<link><![CDATA[https://blog.maskalik.com]]></link>
		<description><![CDATA[Focusing on improving tiny bit every day]]></description>
		<language>en</language>
		<copyright><![CDATA[&copy; 2020 https://blog.maskalik.com. All rights reserved.]]></copyright>
		<pubDate>2020-07-26T03:39:49+00:00</pubDate>
		
	<item>
		<title><![CDATA[On Wrong Answers]]></title>
		<description>
			<![CDATA[
				<p>I love this quote from <a href="https://kellanem.com/">Kellan Elliot-McCrea</a>:</p>

<blockquote>
  <p>Your answers are wrong. Or they will be soon.</p>
</blockquote>

<p>As we learn, grow and the world around us changes, it is inevitable that our views and beliefs change as well. One area where software engineers are bound to change opinions is around languages and frameworks.</p>

<p>With time and opportunity to build projects with technologies that were once trending and exciting, we notice that even the latest technology has pros and cons, and is not a perfect utopia like we thought it would be when we were just starting out.</p>

<p>I have had my share of wrong answers. I wrote about one of them in the <a href="https://blog.maskalik.com/javascript/2014/03/17/getting-serious-about-javascript/">post about JavaScript</a> back in 2014. To understand why I wrote it in the first place, I wanted to take the trip down the memory lane, look at the evolution of JavaScript, and how it has affected my opinion over the years.</p>

<p>Back in the early days of the web, most web pages were generated on the back-end by web servers, and resulting HTML was sent to a client to be rendered by a browser. Navigation between pages or content required every page to be loaded by the browser. In the mid-2000s, GMail and Google Maps were launched using a new technology called AJAX, shorthand for Asynchronous JavaScript + XML, which allowed for pages to be dynamically updated from the web server without making a full page load. Being obsessed with computers running fast, rendering content without a full page refresh seemed to me so much quicker and almost more magical than the traditional way. I quickly became a fan of this new approach and jumped on any opportunity to implement such behavior.</p>

<p>Around the year 2006, <a href="https://en.wikipedia.org/wiki/JQuery">the jQuery</a> library came along and made it very easy to dynamically update the HTML Document Object Model. Besides providing an easy to use fluent API, jQuery also abstracted differences of JavaScript (ECMAScript) implementation of all major browsers. Finally, it made it easy to initiate AJAX requests, parse the data, and then update a portion of a web page. As a side note, very soon after, Microsoft also came out with its AJAX implementation for the ASP.NET Web Forms: ASP.NET AJAX 1.0. It provided JSON serialization features for .NET web-services and allowed developers to use 3rd party JavaScript libraries like jQuery directly to request data formatted as <a href="https://en.wikipedia.org/wiki/JSON">JSON</a> from the back-end. At the beginning of my career as a .NET developer, jQuery with ASP.NET Web Services became my favorite tool when building dynamic web applications.</p>

<p>In the early 2010s, many libraries and frameworks started popping up that allowed engineers to render entire sites with JavaScript and make them look more like native or desktop applications rather than web sites. They were called <a href="https://en.wikipedia.org/wiki/Single-page_application">single-page applications</a> or SPAs. A few of the first ones that come to mind are Backbone, Angular, Ember, and Knockout.js.</p>

<p>My first experience working on a couple of medium-sized SPAs using the Knockout.js library taught me that I could no longer get away with just a surface understanding of JavaScript, which was enough earlier when I putt together sites with jQuery. In addition to reading <a href="https://amzn.to/38bCaKe">JavaScript: The Good Parts</a> by Douglas Crockford, I also purchased and read <a href="https://amzn.to/2VolVVd">JavsScript Patterns</a> by Stoyan Stefanov. Those two books helped me to become much more comfortable with the language and make my now non-trivial JavaScript projects more maintainable.</p>

<p>As I was becoming more comfortable with writing non-trivial single-page JavaScript applications, Node.js was starting to gain popularity. It opened up a new frontier, and JavaScript developers could now not only create applications in a browser but also on the server. Node.js brought the simplicity of JavaScript to the backend. It was easy to get started, just import some packages and run one command to execute your script. Because I enjoyed the novelty and innovativeness of SPAs, I was naturally gravitating at playing around with Node.js and wanting to use it in my future projects.</p>

<p>Besides being simple to get started with, Node.js had multiple other selling points going for it. First of all, because typically all I/O in a JavaScript engine is performed via events and callbacks, asynchronous in nature and never blocks the executing thread, Node.js is very efficient at processing many requests and is very well suited for web applications. It could handle a much bigger throughput than synchronous web applications. Another selling point was using a single language to write your front end, SPA application and backend to power it. Lastly, because Node.js library came only with a basic core library that helped to write server applications, it relied on the community to write the missing pieces. Very soon, every little bit of non-trial code was published as a node package manager (NPM) package and could be imported into your project with a one line command. Almost like Apple’s trademark “There’s an App for That”, npm had a package for anything you could think of. A large number of available packages allows JavaScript developers to build apps really fast. But that speed did not come for free. Not having a standard library encouraged package developers to rely on other packages, which in turn also relied on other packages. A number of dependencies started to become a major source of frustration. The following quote is from an article that describes this problem really well:</p>

<p>In order to use these 3 methods node_modules needs 1826 files. And that’s just 4 of mentioned 976 installed packages. - <a href="https://medium.com/hackernoon/whats-really-wrong-with-node-modules-and-why-this-is-your-fault-8ac9fa893823">What’s really wrong with node_modules and why this is your fault</a></p>

<p>With a larger amount of dependencies, there is also a higher likelihood that a dependency may need to be updated and may not be compatible with existing code, therefore a large dependency graph is also more costly to maintain in the long term. Around the year 2015, it took me more than a week to put together a clean boilerplate that needed everything for a modern SPA project (React, Redux, Webpack, History, Router, Hot Reloading, etc,.) and only a year to learn that some of the dependencies were obsolete, and I if I wanted to migrate to the next version of Webpack everything had to be redone. It felt like a wasted effort. Luckily thanks to a very helpful project, <a href="https://reactjs.org/docs/create-a-new-react-app.html">Create React App</a>, I don’t have to do this again. It takes care of setting up and configuring all the tools necessary for a React SPA and makes it easier to maintain project dependencies.</p>

<p>Using Node.js on large backend projects may be quicker to build, as PayPal <a href="https://medium.com/paypal-engineering/node-js-at-paypal-4e2d1d08ce4f">reported back in</a> 2013, but due to the dynamic nature of the language, and not having a type system, I could imagine it will be more difficult to maintain it over the long term. Yes, you can write a lot of unit tests to make sure your refactoring did not break dependencies or use TypeScript to add typing. However, the former comes with a good deal of overhead, and it might be just easier to use a statically typed language in the first place rather than going with the latter.</p>

<h2 id="my-soon-to-be-wrong-opinions-today">My Soon To Be Wrong Opinions Today</h2>

<p>SPAs are a lot more expensive to build and maintain, and they come with a good deal of additional complexity. Given a lot of overhead, I think SPAs should not be a default choice for building web applications, even today. Yes, there is a place for them but you need to make a conscious decision and accept the overhead and tradeoff. Over time I’ve changed my approach and found it’s much more interesting to solve business problems rather than spending a lot of mental energy just so you can achieve an arbitrary faster and smoother user interface.</p>

<p>If you are not building a native-like UI but still need some portion of the page to be dynamically updated, the same technique we used a decade ago, making AJAX calls to the back-end and updating a page with JavaScript, is still effective, simple, and comes with very little overhead.</p>

<p>There are many valid use cases where JavaScript on the back-end is a good choice. But unless your application is taking advantage of the async I/O and event loop, it may be easier to maintain it in the long term with a language that comes with a proper standard library and is statically typed.</p>

				<p>I love this quote from <a href="https://kellanem.com/">Kellan Elliot-McCrea</a>:</p>

<blockquote>
  <p>Your answers are wrong. Or they will be soon.</p>
</blockquote>

<p>As we learn, grow and the world around us changes, it is inevitable that our views and beliefs change as well. One area where software engineers are bound to change opinions is around languages and frameworks.</p>

<p>With time and opportunity to build projects with technologies that were once trending and exciting, we notice that even the latest technology has pros and cons, and is not a perfect utopia like we thought it would be when we were just starting out.</p>

<p>I have had my share of wrong answers. I wrote about one of them in the <a href="https://blog.maskalik.com/javascript/2014/03/17/getting-serious-about-javascript/">post about JavaScript</a> back in 2014. To understand why I wrote it in the first place, I wanted to take the trip down the memory lane, look at the evolution of JavaScript, and how it has affected my opinion over the years.</p>

<p>Back in the early days of the web, most web pages were generated on the back-end by web servers, and resulting HTML was sent to a client to be rendered by a browser. Navigation between pages or content required every page to be loaded by the browser. In the mid-2000s, GMail and Google Maps were launched using a new technology called AJAX, shorthand for Asynchronous JavaScript + XML, which allowed for pages to be dynamically updated from the web server without making a full page load. Being obsessed with computers running fast, rendering content without a full page refresh seemed to me so much quicker and almost more magical than the traditional way. I quickly became a fan of this new approach and jumped on any opportunity to implement such behavior.</p>

<p>Around the year 2006, <a href="https://en.wikipedia.org/wiki/JQuery">the jQuery</a> library came along and made it very easy to dynamically update the HTML Document Object Model. Besides providing an easy to use fluent API, jQuery also abstracted differences of JavaScript (ECMAScript) implementation of all major browsers. Finally, it made it easy to initiate AJAX requests, parse the data, and then update a portion of a web page. As a side note, very soon after, Microsoft also came out with its AJAX implementation for the ASP.NET Web Forms: ASP.NET AJAX 1.0. It provided JSON serialization features for .NET web-services and allowed developers to use 3rd party JavaScript libraries like jQuery directly to request data formatted as <a href="https://en.wikipedia.org/wiki/JSON">JSON</a> from the back-end. At the beginning of my career as a .NET developer, jQuery with ASP.NET Web Services became my favorite tool when building dynamic web applications.</p>

<p>In the early 2010s, many libraries and frameworks started popping up that allowed engineers to render entire sites with JavaScript and make them look more like native or desktop applications rather than web sites. They were called <a href="https://en.wikipedia.org/wiki/Single-page_application">single-page applications</a> or SPAs. A few of the first ones that come to mind are Backbone, Angular, Ember, and Knockout.js.</p>

<p>My first experience working on a couple of medium-sized SPAs using the Knockout.js library taught me that I could no longer get away with just a surface understanding of JavaScript, which was enough earlier when I putt together sites with jQuery. In addition to reading <a href="https://amzn.to/38bCaKe">JavaScript: The Good Parts</a> by Douglas Crockford, I also purchased and read <a href="https://amzn.to/2VolVVd">JavsScript Patterns</a> by Stoyan Stefanov. Those two books helped me to become much more comfortable with the language and make my now non-trivial JavaScript projects more maintainable.</p>

<p>As I was becoming more comfortable with writing non-trivial single-page JavaScript applications, Node.js was starting to gain popularity. It opened up a new frontier, and JavaScript developers could now not only create applications in a browser but also on the server. Node.js brought the simplicity of JavaScript to the backend. It was easy to get started, just import some packages and run one command to execute your script. Because I enjoyed the novelty and innovativeness of SPAs, I was naturally gravitating at playing around with Node.js and wanting to use it in my future projects.</p>

<p>Besides being simple to get started with, Node.js had multiple other selling points going for it. First of all, because typically all I/O in a JavaScript engine is performed via events and callbacks, asynchronous in nature and never blocks the executing thread, Node.js is very efficient at processing many requests and is very well suited for web applications. It could handle a much bigger throughput than synchronous web applications. Another selling point was using a single language to write your front end, SPA application and backend to power it. Lastly, because Node.js library came only with a basic core library that helped to write server applications, it relied on the community to write the missing pieces. Very soon, every little bit of non-trial code was published as a node package manager (NPM) package and could be imported into your project with a one line command. Almost like Apple’s trademark “There’s an App for That”, npm had a package for anything you could think of. A large number of available packages allows JavaScript developers to build apps really fast. But that speed did not come for free. Not having a standard library encouraged package developers to rely on other packages, which in turn also relied on other packages. A number of dependencies started to become a major source of frustration. The following quote is from an article that describes this problem really well:</p>

<p>In order to use these 3 methods node_modules needs 1826 files. And that’s just 4 of mentioned 976 installed packages. - <a href="https://medium.com/hackernoon/whats-really-wrong-with-node-modules-and-why-this-is-your-fault-8ac9fa893823">What’s really wrong with node_modules and why this is your fault</a></p>

<p>With a larger amount of dependencies, there is also a higher likelihood that a dependency may need to be updated and may not be compatible with existing code, therefore a large dependency graph is also more costly to maintain in the long term. Around the year 2015, it took me more than a week to put together a clean boilerplate that needed everything for a modern SPA project (React, Redux, Webpack, History, Router, Hot Reloading, etc,.) and only a year to learn that some of the dependencies were obsolete, and I if I wanted to migrate to the next version of Webpack everything had to be redone. It felt like a wasted effort. Luckily thanks to a very helpful project, <a href="https://reactjs.org/docs/create-a-new-react-app.html">Create React App</a>, I don’t have to do this again. It takes care of setting up and configuring all the tools necessary for a React SPA and makes it easier to maintain project dependencies.</p>

<p>Using Node.js on large backend projects may be quicker to build, as PayPal <a href="https://medium.com/paypal-engineering/node-js-at-paypal-4e2d1d08ce4f">reported back in</a> 2013, but due to the dynamic nature of the language, and not having a type system, I could imagine it will be more difficult to maintain it over the long term. Yes, you can write a lot of unit tests to make sure your refactoring did not break dependencies or use TypeScript to add typing. However, the former comes with a good deal of overhead, and it might be just easier to use a statically typed language in the first place rather than going with the latter.</p>

<h2 id="my-soon-to-be-wrong-opinions-today">My Soon To Be Wrong Opinions Today</h2>

<p>SPAs are a lot more expensive to build and maintain, and they come with a good deal of additional complexity. Given a lot of overhead, I think SPAs should not be a default choice for building web applications, even today. Yes, there is a place for them but you need to make a conscious decision and accept the overhead and tradeoff. Over time I’ve changed my approach and found it’s much more interesting to solve business problems rather than spending a lot of mental energy just so you can achieve an arbitrary faster and smoother user interface.</p>

<p>If you are not building a native-like UI but still need some portion of the page to be dynamically updated, the same technique we used a decade ago, making AJAX calls to the back-end and updating a page with JavaScript, is still effective, simple, and comes with very little overhead.</p>

<p>There are many valid use cases where JavaScript on the back-end is a good choice. But unless your application is taking advantage of the async I/O and event loop, it may be easier to maintain it in the long term with a language that comes with a proper standard library and is statically typed.</p>

										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: thoughts</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2020/07/06/on-wrong-answers/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2020/07/06/on-wrong-answers/]]></guid>
		<pubDate>2020-07-06T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Capacity Planning at a Widget Factory]]></title>
		<description>
			<![CDATA[
				<p>Imagine you are an engineer working at a widget factory, and because the business is continuously growing, you estimate that you will soon need to support five times the current production capacity.</p>

<p>Because it’s a modern factory, the performance of every stage of the widget assembly is measured and then displayed on electronic dashboards. Based on the metrics, you can tell that the assembly line is at half capacity at the current rate of production. Therefore, to get to the target capacity without any optimizations is not possible, and you are not confident that it can even be accomplished.</p>

<p>The simple approach to increase the capacity is to add additional resources to each assembly stage based solely on the current production capacity and utilization. In other words, if one of the assembly stages is running at 50% capacity and produces 100 widgets, you figure out that you will need at least 50% * 5 = 250% more resources to produce 500 widgets. If one of those assembly stages is a physical resource like a paint station, getting to 250% would mean that you would need to buy and add two additional stations to support the 250% capacity increase.</p>

<p>This approach, however, has some flaws. It makes an assumption that your assembly line is already optimized to support the projected capacity. But in reality, there are many areas that could be improved to produce a higher throughput without additional resources. Increasing every resource across the board is inefficient, requires a lot more maintenance, and is expensive. It’s also wasteful if the expected capacity does not materialize.</p>

<p>Another alternative to increase capacity would be to try to dial up your current production assembly line to see how much it can handle. But this is dangerous because if one of the stages does go out of order, it can create downtime for the entire assembly, and your factory must be producing at all times.</p>

<p>Looking at the dashboards, you see that there are slow areas that can be optimized. But you are still not sure if the optimizations are going to make the entire assembly run quicker. In other words, are you actually discovering the bottlenecks or just optimizing blindly?</p>

<p>Luckily, your company has a new branch opening up soon that has the same assembly line installed, a perfect place for you to run some experiments.</p>

<p>So you set up your factory to mimic the production workload and systematically work to figure out what needs to be done to improve the throughput. By gradually increasing workload, you start noticing which stages are starting to break down and create bottlenecks. To resolve a bottleneck, you get to exercise your engineering skills and come up with a solution to make the steps faster. Sometimes, figuring out how to make a portion of an assembly line run faster is not an easy task, and you need to dive deep into understanding how a particular machine works and obtain valuable knowledge in the process. It’s fun and challenging at the same time.</p>

<p>In the process of pushing your assembly line to the limit, you get to learn about the physical limitations of each stage. Perhaps there are some stages that cannot be more optimized and you may have to redesign or upgrade a section of the assembly line. In order to squeeze every last bit of performance, you had to experiment with many different settings, test many different scenarios, and try out different configurations. As a result, you are now more intimately familiar with the system as a whole; there is no more guesswork needed and you are much better positioned to do the following:</p>

<ul>
  <li>Create a realistic capacity plan.</li>
  <li>Identify major performance bottlenecks in your system.</li>
  <li>Improve the ability to increase or decrease capacity.</li>
  <li>Improve reliability during increased load.</li>
  <li>Improve the performance of the assembly line.</li>
</ul>

<p>There could also be some other interesting findings. Perhaps, in the past, you thought that some areas of the assembly would start breaking down earlier than expected and had more resources allocated, but these theories were not realized. As a result, you can save the company money by getting rid of the excess capacity that would never get utilized under the current setup.</p>

<p>Finally, the most exciting outcome of performing these experiments is making your assembly line run faster and much more efficiently. Your customers are much happier that they can get widgets faster, and your business is more cost-effective as a result.</p>

<p>This was my attempt to use an analogy describing a load testing project that I was recently involved in. I understand that sometimes you may not be in a position to re-create a production-like environment, but if you are lucky enough to have an application that runs in the cloud and infrastructure specified as code, standing up a production mirror and investing a bit of time on load testing can have some profound results. As a result of load testing, at my work, we were able to increase the performance and capacity of our system by 10x using the same hardware. This will translate into a more reliable system that can handle bursts of traffic and be less expensive in general.</p>

<p>Special mention goes to the awesome load testing tool, <a href="https://locust.io/">Locust.io</a>. It was very easy to use, and it took only a couple of days to write test scripts to mimic critical path interaction with our services.</p>

				<p>Imagine you are an engineer working at a widget factory, and because the business is continuously growing, you estimate that you will soon need to support five times the current production capacity.</p>

<p>Because it’s a modern factory, the performance of every stage of the widget assembly is measured and then displayed on electronic dashboards. Based on the metrics, you can tell that the assembly line is at half capacity at the current rate of production. Therefore, to get to the target capacity without any optimizations is not possible, and you are not confident that it can even be accomplished.</p>

<p>The simple approach to increase the capacity is to add additional resources to each assembly stage based solely on the current production capacity and utilization. In other words, if one of the assembly stages is running at 50% capacity and produces 100 widgets, you figure out that you will need at least 50% * 5 = 250% more resources to produce 500 widgets. If one of those assembly stages is a physical resource like a paint station, getting to 250% would mean that you would need to buy and add two additional stations to support the 250% capacity increase.</p>

<p>This approach, however, has some flaws. It makes an assumption that your assembly line is already optimized to support the projected capacity. But in reality, there are many areas that could be improved to produce a higher throughput without additional resources. Increasing every resource across the board is inefficient, requires a lot more maintenance, and is expensive. It’s also wasteful if the expected capacity does not materialize.</p>

<p>Another alternative to increase capacity would be to try to dial up your current production assembly line to see how much it can handle. But this is dangerous because if one of the stages does go out of order, it can create downtime for the entire assembly, and your factory must be producing at all times.</p>

<p>Looking at the dashboards, you see that there are slow areas that can be optimized. But you are still not sure if the optimizations are going to make the entire assembly run quicker. In other words, are you actually discovering the bottlenecks or just optimizing blindly?</p>

<p>Luckily, your company has a new branch opening up soon that has the same assembly line installed, a perfect place for you to run some experiments.</p>

<p>So you set up your factory to mimic the production workload and systematically work to figure out what needs to be done to improve the throughput. By gradually increasing workload, you start noticing which stages are starting to break down and create bottlenecks. To resolve a bottleneck, you get to exercise your engineering skills and come up with a solution to make the steps faster. Sometimes, figuring out how to make a portion of an assembly line run faster is not an easy task, and you need to dive deep into understanding how a particular machine works and obtain valuable knowledge in the process. It’s fun and challenging at the same time.</p>

<p>In the process of pushing your assembly line to the limit, you get to learn about the physical limitations of each stage. Perhaps there are some stages that cannot be more optimized and you may have to redesign or upgrade a section of the assembly line. In order to squeeze every last bit of performance, you had to experiment with many different settings, test many different scenarios, and try out different configurations. As a result, you are now more intimately familiar with the system as a whole; there is no more guesswork needed and you are much better positioned to do the following:</p>

<ul>
  <li>Create a realistic capacity plan.</li>
  <li>Identify major performance bottlenecks in your system.</li>
  <li>Improve the ability to increase or decrease capacity.</li>
  <li>Improve reliability during increased load.</li>
  <li>Improve the performance of the assembly line.</li>
</ul>

<p>There could also be some other interesting findings. Perhaps, in the past, you thought that some areas of the assembly would start breaking down earlier than expected and had more resources allocated, but these theories were not realized. As a result, you can save the company money by getting rid of the excess capacity that would never get utilized under the current setup.</p>

<p>Finally, the most exciting outcome of performing these experiments is making your assembly line run faster and much more efficiently. Your customers are much happier that they can get widgets faster, and your business is more cost-effective as a result.</p>

<p>This was my attempt to use an analogy describing a load testing project that I was recently involved in. I understand that sometimes you may not be in a position to re-create a production-like environment, but if you are lucky enough to have an application that runs in the cloud and infrastructure specified as code, standing up a production mirror and investing a bit of time on load testing can have some profound results. As a result of load testing, at my work, we were able to increase the performance and capacity of our system by 10x using the same hardware. This will translate into a more reliable system that can handle bursts of traffic and be less expensive in general.</p>

<p>Special mention goes to the awesome load testing tool, <a href="https://locust.io/">Locust.io</a>. It was very easy to use, and it took only a couple of days to write test scripts to mimic critical path interaction with our services.</p>

										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: load-testing</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2020/06/11/capacity-planning-at-a-widget-factory/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2020/06/11/capacity-planning-at-a-widget-factory/]]></guid>
		<pubDate>2020-06-11T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[AWS RDS: You may not need Provisioned IOPS]]></title>
		<description>
			<![CDATA[
				<p>When choosing a Solid State Drive (SSD) type for your low latency, transactional Amazon Relational Database Service (RDS), Amazon Elastic Block Store (EBS) provides two options: General Storage (GP2) and Provisioned IOPS (IO1). The IO1 type is a much more expensive option, and you want to make sure that your database workload justifies that additional cost. We’ll look at reasons why you may need IO1 vs GP2.</p>

<h2 id="performance-and-performance-consistency">Performance and performance consistency</h2>

<p><a href="https://aws.amazon.com/ebs/volume-types/">EBS documentation</a> describes IO1 as “Highest-performance SSD volume for mission-critical low-latency or high-throughput workloads” and with use cases of “Critical business applications that require sustained IOPS performance, or more than 16,000 IOPS or 250 MiB/s of throughput per volume.” IOPS are defined as a unit of measure representing input/output operations per second with operations measured in Kilobytes (KiB) maxim of 256KiB for SSD volumes.</p>

<p>Mark Olsol, Senior Software Engineer on the EBS team, mentioned in one of the Amazon <a href="https://www.youtube.com/watch?v=2wKgha8CZ_w">re:Invent talks</a> that between both volume types “… the performance is very similar, it’s the performance consistency that’s different between the two. In benchmark you won’t notice, but you’ll notice it over time.”</p>

<p>Below 16,000 IOPS or 250MiB/s of data throughput both volume types can be configured to have the same amounts of IOPS and, as Mark said, have very similar performance. With the GP2 volume type, IOPS are provisioned by volume size, 3 IOPS per GB of storage with a minimum of 100 IOPS. Provisioning IOPS for the IO1 volume type is not dependent on the disk size as long as it’s <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volume-types.html#EBSVolumeTypes_piops">below 50 IOPS per 1 GB</a> rate.</p>

<p>The difference in performance consistency that Olson has mentioned, and the actual consistency numbers are specified in the documentation: “GP2 is designed to deliver the provisioned performance 99% of the time” while IO1 “…designed to deliver the provisioned performance 99.9% of the time”. Therefore, below maximum throughput,  if your system can tolerate 99% storage performance consistency and does not need 99.9%, GP2 volume type is a much more cost effective option.</p>

<h2 id="throughput">Throughput</h2>

<p>Throughput measures how much time it takes for a disk to read or write data. The throughput depends on how many IOPS are configured and how much data is read/written per I/O operation (capped at 256KiB). Maximum throughput for GP2 depends on the instance size and I/O size, with the maximum throughput of 250MiB/s achieved at 1000 IOPS x 256KiB at 334 GiB disk size.</p>

<p>If the database workload is data intensive and requires more than 250MiB/s throughput, GP2 will not be the right volume type. Transactional systems don’t usually read/write large amounts of data at once, but still it is possible to hit the 250MiB/s cap with a workload of more than 16KiB I/O size and 16,000 IOPS (5,334 GB disk size). Of course your workload may be different, and you always need to check the average I/O size for your database.</p>

<h2 id="cost-comparison">Cost comparison</h2>

<p>Given the same number of provisioned IOPS for both drives and throughput of less than 250MiB/s, the performance consistency with IO1 types does not come cheap. And because the performance is very similar, you can save a lot of money if your application doesn’t need 99.9% performance consistency. Here is a table comparing <a href="https://aws.amazon.com/ebs/pricing/">monthly cost</a> of GP2 baseline IOPS with the exact same size and provisioned IOPS of the IO1 type.</p>

<p><img src="https://github.com/mercury2269/mercury2269.github.io/raw/master/uploads/2020/20200531-iops-to-gp2-price-comparison.png" alt="" /></p>
<h2 id="choosing-a-correct-instance-type">Choosing a correct instance type</h2>

<p>Another important factor that could limit the performance of your database is an underlying virtual Amazon Elastic Compute Cloud (EC2) instance type. EBS bandwidth varies between different EC2 instance types, and it’s possible that the EC2 bandwidth is less than the maximum amount of throughput supported by your EBS volume. I’ve personally run into this issue when my application’s database instance type was configured at <code class="language-plaintext highlighter-rouge">m4.xlarge</code> with dedicated EBS performance of 750 Mbps which translated to about 93.76 MiB/s, which was less than 250MiB/s expected throughput of the storage. EC2 instance type specifications are listed <a href="https://aws.amazon.com/ec2/instance-types/">here</a>.</p>

<h2 id="summary">Summary</h2>

<p>Taking time to understand your database workload and differences between the two storage types, GP2 and IO1, can potentially reduce costs and improve the performance of your application.</p>

				<p>When choosing a Solid State Drive (SSD) type for your low latency, transactional Amazon Relational Database Service (RDS), Amazon Elastic Block Store (EBS) provides two options: General Storage (GP2) and Provisioned IOPS (IO1). The IO1 type is a much more expensive option, and you want to make sure that your database workload justifies that additional cost. We’ll look at reasons why you may need IO1 vs GP2.</p>

<h2 id="performance-and-performance-consistency">Performance and performance consistency</h2>

<p><a href="https://aws.amazon.com/ebs/volume-types/">EBS documentation</a> describes IO1 as “Highest-performance SSD volume for mission-critical low-latency or high-throughput workloads” and with use cases of “Critical business applications that require sustained IOPS performance, or more than 16,000 IOPS or 250 MiB/s of throughput per volume.” IOPS are defined as a unit of measure representing input/output operations per second with operations measured in Kilobytes (KiB) maxim of 256KiB for SSD volumes.</p>

<p>Mark Olsol, Senior Software Engineer on the EBS team, mentioned in one of the Amazon <a href="https://www.youtube.com/watch?v=2wKgha8CZ_w">re:Invent talks</a> that between both volume types “… the performance is very similar, it’s the performance consistency that’s different between the two. In benchmark you won’t notice, but you’ll notice it over time.”</p>

<p>Below 16,000 IOPS or 250MiB/s of data throughput both volume types can be configured to have the same amounts of IOPS and, as Mark said, have very similar performance. With the GP2 volume type, IOPS are provisioned by volume size, 3 IOPS per GB of storage with a minimum of 100 IOPS. Provisioning IOPS for the IO1 volume type is not dependent on the disk size as long as it’s <a href="https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ebs-volume-types.html#EBSVolumeTypes_piops">below 50 IOPS per 1 GB</a> rate.</p>

<p>The difference in performance consistency that Olson has mentioned, and the actual consistency numbers are specified in the documentation: “GP2 is designed to deliver the provisioned performance 99% of the time” while IO1 “…designed to deliver the provisioned performance 99.9% of the time”. Therefore, below maximum throughput,  if your system can tolerate 99% storage performance consistency and does not need 99.9%, GP2 volume type is a much more cost effective option.</p>

<h2 id="throughput">Throughput</h2>

<p>Throughput measures how much time it takes for a disk to read or write data. The throughput depends on how many IOPS are configured and how much data is read/written per I/O operation (capped at 256KiB). Maximum throughput for GP2 depends on the instance size and I/O size, with the maximum throughput of 250MiB/s achieved at 1000 IOPS x 256KiB at 334 GiB disk size.</p>

<p>If the database workload is data intensive and requires more than 250MiB/s throughput, GP2 will not be the right volume type. Transactional systems don’t usually read/write large amounts of data at once, but still it is possible to hit the 250MiB/s cap with a workload of more than 16KiB I/O size and 16,000 IOPS (5,334 GB disk size). Of course your workload may be different, and you always need to check the average I/O size for your database.</p>

<h2 id="cost-comparison">Cost comparison</h2>

<p>Given the same number of provisioned IOPS for both drives and throughput of less than 250MiB/s, the performance consistency with IO1 types does not come cheap. And because the performance is very similar, you can save a lot of money if your application doesn’t need 99.9% performance consistency. Here is a table comparing <a href="https://aws.amazon.com/ebs/pricing/">monthly cost</a> of GP2 baseline IOPS with the exact same size and provisioned IOPS of the IO1 type.</p>

<p><img src="https://github.com/mercury2269/mercury2269.github.io/raw/master/uploads/2020/20200531-iops-to-gp2-price-comparison.png" alt="" /></p>
<h2 id="choosing-a-correct-instance-type">Choosing a correct instance type</h2>

<p>Another important factor that could limit the performance of your database is an underlying virtual Amazon Elastic Compute Cloud (EC2) instance type. EBS bandwidth varies between different EC2 instance types, and it’s possible that the EC2 bandwidth is less than the maximum amount of throughput supported by your EBS volume. I’ve personally run into this issue when my application’s database instance type was configured at <code class="language-plaintext highlighter-rouge">m4.xlarge</code> with dedicated EBS performance of 750 Mbps which translated to about 93.76 MiB/s, which was less than 250MiB/s expected throughput of the storage. EC2 instance type specifications are listed <a href="https://aws.amazon.com/ec2/instance-types/">here</a>.</p>

<h2 id="summary">Summary</h2>

<p>Taking time to understand your database workload and differences between the two storage types, GP2 and IO1, can potentially reduce costs and improve the performance of your application.</p>

										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: aws and rds</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2020/05/31/aws-rds-you-may-not-need-provisioned-iops/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2020/05/31/aws-rds-you-may-not-need-provisioned-iops/]]></guid>
		<pubDate>2020-05-31T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Automated End-to-End Tests In Production]]></title>
		<description>
			<![CDATA[
				<p>One of the challenges for large multi-tenant systems that rely on many external services to complete a single request is ensuring that each dependency is configured correctly in production environments. In addition, if a system is geographically distributed, each instance may depend on different versions of external services.</p>


				<p>One of the challenges for large multi-tenant systems that rely on many external services to complete a single request is ensuring that each dependency is configured correctly in production environments. In addition, if a system is geographically distributed, each instance may depend on different versions of external services.</p>

<p>Even with the best intentions, humans who have to configure and maintain these types of complex systems are known to be unreliable.</p>

<blockquote>
  <p>… <a href="http://roc.cs.berkeley.edu/papers/usits03.pdf">one study</a> of large internet services found that configuration errors by operators were the leading cause of outages, where hardware faults (servers or network) play a role in only 10-25% of outages. Designing Data-Intensive Applications, Martin Kleppmann</p>
</blockquote>

<p>Due to many possible test scenarios, manual regression testing after each release is not practical, especially if your team is following a <a href="https://en.wikipedia.org/wiki/Continuous_delivery">continuous delivery</a> approach.</p>

<p>Monitoring of critical paths provides good feedback about already configured tenants and is an important tool when making production releases. However, some geographical regions may be outside of their peak hours and monitoring alone may not provide fast enough feedback about deployments to production. Also, when new tenants are brought online you still have to validate configuration and dependencies in production.</p>

<p>Traditionally automatic end-to-end tests were reserved only for pre-production environments; however, if your production environments rely on a multitude of external services to complete a single request, extending end-to-end tests to production can help to ensure that all tenant dependencies are configured properly. The goal of these production tests is not to run a full regression suite, but to only test critical paths.</p>

<p>Depending on how your end customers interact with your system, automatic end-to-end tests can run against a public facing web user interface (UI) using something like the Selenium Webdriver, or directly against public API endpoints.</p>

<p>Triggered from a Continuous Integration (CI) system, after deployments to production environments, a test suite will provide an immediate detection and warning of any underlying issues. By having clear results of what is failing, production end-to-end tests will also save time for engineers who might otherwise receive bug reports from different channels and will have to sift through the logs to figure out what went wrong. Finally, because all possible critical paths are tested in production after deploys, tests will provide additional confidence about deploys that may not be present by monitoring alone.</p>

<p>In addition to running end-to-end tests by CI, these tests can be triggered manually or automatically after configuration changes to production. Ability to run critical path tests in production on demand will also reduce manual QA overhead needed to verify that that everything is working as expected after a configuration change.</p>

<p>Unfortunately, running tests in production will create test data in production databases. I personally don’t like to delete data from production databases, even if it’s test data, because your database is a system of record, and it’s important for it to stay intact for troubleshooting. Therefore, you would need to keep track of test users/transactions and filter out test transactions from consumers of your data.</p>

<p>Finally, test results will be fed into a monitoring system and displayed on the team’s dashboard. Alerts are also configured on this data.</p>

<h2 id="putting-it-all-together">Putting it all together</h2>

<p>When dealing with a lot of external dependencies and configuration permutations in a system, we need to think outside of the box and engineer solutions that can help us to deal with additional complexity. While it’s important to ship software bug free, there are use cases when it’s much more efficient to verify that software is bug free right after it’s deployed to production.</p>

										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: thoughts and ideas</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2020/05/16/end-to-end-tests-in-production/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2020/05/16/end-to-end-tests-in-production/]]></guid>
		<pubDate>2020-05-16T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Design Systems Not Rules to Follow]]></title>
		<description>
			<![CDATA[
				<p>In the last few years, as my team grew in size, one of the problems that kept coming up during retrospective meetings was the poor turn around with code reviews. With a smaller team there was no need for an additional process to find code review volunteers; since every engineer had to pitch in and review code daily. But with a larger team, not having a clear process or rules to follow was starting to affect the team’s performance. The issues were identified as follows:</p>


				<p>In the last few years, as my team grew in size, one of the problems that kept coming up during retrospective meetings was the poor turn around with code reviews. With a smaller team there was no need for an additional process to find code review volunteers; since every engineer had to pitch in and review code daily. But with a larger team, not having a clear process or rules to follow was starting to affect the team’s performance. The issues were identified as follows:</p>

<ol>
  <li>It was difficult to find a code review volunteer.</li>
  <li>After a volunteer was found, sometimes you would still need to follow up if the review was not getting attention.</li>
  <li>Some people would volunteer less than others.</li>
  <li>When comments or replies were posted on code reviews, they were not immediately visible because email notifications from GitHub often had to wait until you checked your email. And to get the review process moving along, sometimes you had to message the reviewer directly.</li>
</ol>

<h2 id="initial-attempts-at-creating-additional-process">Initial attempts at creating additional process</h2>

<p>After multiple discussions with the team, everyone agreed to introduce a simple rule: at the start of a day, each developer will spend 15 minutes on code reviews. This, in theory, would provide more than enough engineers to complete all outstanding reviews and keep review turnaround under 24 hours. A few months later, the results of the experiment were mixed. There was still a lot of delay with getting code reviewed. Sometimes changes requested during code reviews had to be reviewed again, and if your reviewers were already done for the day, it would have to wait another day. Due to the slow feedback cycle, reviews still could take days to get completed. Finally, some engineers were not contributing every day due to being busy with other work.</p>

<p>After another brainstorming session, the team identified that one of the issues with poor turnaround was that outstanding code reviews were not easily visible. Because we work with many GitHub repositories, it is not practical to go into each one to see what code reviews (pull requests) are outstanding. The proposed solution was to use a “pin” feature in Slack, our instant messenger program, which will add a code review link to the team channel’s dashboard. When engineers finished reviewing, they would add a 👍 emoji to the pinned code review, flagging it as done. When two thumbs up appeared on a pinned request, the requestor would merge a code review and unpin the item. This was not a complicated process to follow, but there was still confusion and after another few months, outstanding reviews started to linger on the team’s channel board.</p>

<h2 id="from-volunteering-to-assignment">From volunteering to assignment</h2>

<p>In an attempt to uncover the underlying problem, one of the engineers extracted data on the number of reviews per person and noticed that reviews were not evenly distributed. Some people did a lot more than others. Asking for volunteers was not working very well and also created a fairness problem.</p>

<p>At this point, it was obvious that we needed to even out the distribution and prioritize assigning engineers with the least number of reviews. We also thought about automating this process. It was not difficult to write a script that would pull review statistics and assign people with the least amount of reviews. However, to save time we looked online to see if someone had already solved this problem, and we found a <a href="https://pullreminders.com/">Pull Reminders commercial application</a> that did exactly what we needed, plus other useful features.</p>

<p>Initially, when we decided to give Pull Reminders a try, we weren’t confident that it would solve the problem. However, after everyone was onboard, we were surprised to learn that the issue with code reviews did not come up again during retrospective meetings. We changed our process from volunteering to assignment, based on the leader-board from the Pull Reminders app. When you need a review, rather than asking or posting in the channel, you will assign two people with the least number of reviews from the leader-board. Pull reminders will take care of notifying and reminding people about outstanding code reviews. The app also improved our communication because it sent personal slack messages when a comment or reply was posted in your code review. This tremendously improved response and turnaround times.</p>

<h2 id="summary">Summary</h2>

<p>It’s been a year since we’ve started using Pull Reminders, and I haven’t noticed any confusion or disconnect about code review responsibilities. The majority of reviews are done within a day or two. And we can finally call the problem that caused a lot of discussions and inefficiencies resolved. Most importantly, the new system removed additional rules that everyone had to remember to follow. Now, the system enforces and notifies engineers when they need to review code, and it’s hard to ignore.</p>

<p>Coming up with new rules for everyone to follow is easy but sometimes ineffective. A much better approach is to create a system that makes new rules hard to ignore.</p>

										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: thoughts and ideas</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2020/05/10/design-systems-not-rules-to-follow/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2020/05/10/design-systems-not-rules-to-follow/]]></guid>
		<pubDate>2020-05-10T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Apple In-App Payments Integration Lessons Learned]]></title>
		<description>
			<![CDATA[
				<p>After having integrated in-app payments using Apple platform and processing tens of thousands of purchase receipts through the back-end, I’ve learned a few valuable lessons about issues that can only surface in production. Some of these gotchas are either not documented, hard to find in documentation or just strange behavior that only presents itself in a live environment. This is a guide that I wish I had while I was integrating; it would have saved me a few gray hairs.</p>


				<p>After having integrated in-app payments using Apple platform and processing tens of thousands of purchase receipts through the back-end, I’ve learned a few valuable lessons about issues that can only surface in production. Some of these gotchas are either not documented, hard to find in documentation or just strange behavior that only presents itself in a live environment. This is a guide that I wish I had while I was integrating; it would have saved me a few gray hairs.</p>

<h2 id="empty-in_app-transactions-array-in-successful-purchase-receipts">Empty in_app transactions array in successful purchase receipts</h2>

<p>There is a small percentage of successful purchase receipts, when verified via back-end by calling Apple’s API, that do not contain any in-app transactions. In the response received from the API, in_app array field is empty (<code class="language-plaintext highlighter-rouge">in_app:[]</code>). The latest advice I found on this issue was from Apple’s technical support engineer in this <a href="https://forums.developer.apple.com/thread/72893">forum post</a>. He clarified that <strong>when the receipt does not contain any transactions, it’s not a valid receipt and you should never call <code class="language-plaintext highlighter-rouge">finishTransaction</code></strong> for these types of receipts. There is also another, older solution to this problem that I think is no longer valid and that is asking users to refresh a purchase receipt. As another highly rated support user in that forum post pointed out, the purchase receipt is refreshed before <code class="language-plaintext highlighter-rouge">updatedTransactions</code> callback, therefore the receipt should contain updated information and refreshing it is unnecessary.</p>

<h2 id="strange-transaction-id-formats-in-purchase-receipts">Strange transaction id formats in purchase receipts</h2>

<p>Normally transaction ids are 15 digits like: <code class="language-plaintext highlighter-rouge">400000123456789</code>. But there are times when our server receives a receipt with the transaction in the following, uuid format: <code class="language-plaintext highlighter-rouge">FAB60FFD-906D-48CB-8FED-092C4B2707D6</code></p>

<p>These strange receipt formats when verified with Apple’s back-end also come back with an empty <code class="language-plaintext highlighter-rouge">in_app[]</code> array. There is no definite answer on <a href="http://stackoverflow.com">stackoverflow.com</a> or Apple’s developer forums, but it looks like it could be a hack. The best course of action is to not call <code class="language-plaintext highlighter-rouge">finishTransaction</code> on a receipt that doesn’t have transactions and is not valid.</p>

<h2 id="nil-skpaymentapplicationusername-for-some-transactions-in-production-environment">Nil SKPayment.applicationUsername for some transactions in production environment</h2>

<p>Calling a method on a <code class="language-plaintext highlighter-rouge">nil</code> reference guarantees to crash your app and will make your coworkers give you that look that you don’t know what you are doing.</p>

<p>The <code class="language-plaintext highlighter-rouge">applicationUsername</code> property of the <code class="language-plaintext highlighter-rouge">SKPayment</code> object is one of the fields that may have a value while you are developing and even pass QA. However, for a small percentage of users it will be null in production. And if you didn’t pay careful attention to documentation you are guaranteed to create a really bad experience for a small percentage of your users. In documentation, the description of this property contains an <strong>important</strong> section that calls out:</p>

<blockquote>
  <p>The <a href="https://developer.apple.com/documentation/storekit/skmutablepayment/1506088-applicationusername?language=objc">applicationUsername</a> property is not guaranteed to persist between when you add the payment transaction to the queue and when the queue updates the transaction. Do not attempt to use this property for purposes other than providing fraud detection.</p>
</blockquote>

<p>What this also is trying to tell you is that sometimes this property will be nil, and if you call a method on a nil property you will crash your user’s device. If you are not careful, after a user makes a payment, his app will crash and will continue crashing on every restart because your application will try to reprocess the payment transaction on every startup. This behavior is impossible to catch testing.</p>

<h2 id="being-careful-with-nil-fields-on-callbacks">Being careful with nil fields on callbacks</h2>

<h3 id="for-purchase-callbacks">For purchase callbacks:</h3>

<p>The following fields are only available when <code class="language-plaintext highlighter-rouge">transactionState</code> is <code class="language-plaintext highlighter-rouge">SKPaymentTransactionState.purchase</code> or <code class="language-plaintext highlighter-rouge">SKPaymentTransactionState.restored</code>.</p>

<ul>
  <li>SKPaymentTransaction.transactionDate</li>
  <li>SKPaymentTransaction.transactionIdentifier</li>
</ul>

<h3 id="for-product-callbacks">For product callbacks:</h3>

<p>If Apple rejects your app and in-app purchase products during the approval process, product data for rejected items retrieved via <code class="language-plaintext highlighter-rouge">SKProductsRequest</code> will contain some invalid information. Unfortunately, I wasn’t able to pinpoint the problem because it was happening only in production, and we didn’t have debug symbols uploaded at that time. So to be on the safe side, I opted in for checking every <a href="https://developer.apple.com/documentation/storekit/skproduct">SkProduct</a> attribute for null before reading a value or calling method on the attribute. This is more of a brute force solution, but at least your <code class="language-plaintext highlighter-rouge">SKProducts</code> callback won’t crash your app after Apple rejects in-app products.</p>

<h2 id="keep-a-strong-reference-to-skproductsrequest">Keep a strong reference to SKProductsRequest</h2>

<p>Be sure not to miss the “Note” section of the <a href="https://developer.apple.com/documentation/storekit/skproductsrequest?language=objc">SKProductRequest description</a> about keeping a strong reference to the <code class="language-plaintext highlighter-rouge">SKProductRequest</code> object.</p>

<p>If your app can receive multiple requests to retrieve products, I would add <code class="language-plaintext highlighter-rouge">SKProductRequest</code> references to a <code class="language-plaintext highlighter-rouge">NSMutableSet</code> data structure and remove them after <code class="language-plaintext highlighter-rouge">requestDidFinish</code> callback fires.</p>

<p>Here is an example for initiating get products info request.</p>

<div class="language-objectivec highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">getProducts</span><span class="p">:(</span><span class="n">NSSet</span><span class="o">*</span><span class="p">)</span><span class="nv">productIDs</span> <span class="p">{</span>
  <span class="n">NSLog</span><span class="p">(</span><span class="s">@"Requesting %lu products"</span><span class="p">,</span> <span class="p">(</span><span class="kt">unsigned</span> <span class="kt">long</span><span class="p">)[</span><span class="n">productIDs</span> <span class="nf">count</span><span class="p">]);</span>

  <span class="n">SKProductsRequest</span><span class="o">*</span> <span class="n">productsRequest</span> <span class="o">=</span> <span class="p">[[</span><span class="n">SKProductsRequest</span> <span class="nf">alloc</span><span class="p">]</span> <span class="nf">initWithProductIdentifiers</span><span class="p">:</span><span class="n">productIDs</span><span class="p">];</span>
  <span class="n">productsRequest</span><span class="p">.</span><span class="n">delegate</span> <span class="o">=</span> <span class="n">self</span><span class="p">;</span>

  <span class="k">@synchronized</span><span class="p">(</span><span class="n">_productsRequests</span><span class="p">)</span> <span class="p">{</span>
    <span class="p">[</span><span class="n">_productsRequests</span> <span class="nf">addObject</span><span class="p">:</span> <span class="n">productsRequest</span><span class="p">];</span>
  <span class="p">}</span>
  <span class="p">[</span><span class="n">productsRequest</span> <span class="nf">start</span><span class="p">];</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Example interface:</p>

<div class="language-objectivec highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">@interface</span> <span class="nc">IapAppleDelegate</span> <span class="p">:</span> <span class="nc">NSObject</span><span class="o">&lt;</span><span class="n">SKProductsRequestDelegate</span><span class="o">&gt;</span>
<span class="p">{</span>
  <span class="n">NSMutableSet</span> <span class="o">*</span><span class="n">_productsRequests</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Removing references after request has be completed.</p>

<div class="language-objectivec highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">-</span> <span class="p">(</span><span class="kt">void</span><span class="p">)</span><span class="nf">requestDidFinish</span><span class="p">:(</span><span class="n">SKRequest</span> <span class="o">*</span><span class="p">)</span><span class="nv">request</span>
<span class="p">{</span>
  <span class="k">@synchronized</span><span class="p">(</span><span class="n">_productsRequests</span><span class="p">)</span> <span class="p">{</span>
    <span class="p">[</span><span class="n">_productsRequests</span> <span class="nf">removeObject</span><span class="p">:</span><span class="n">request</span><span class="p">];</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h2 id="summary">Summary</h2>

<p>In-app purchase integration with Apple may not seem super complex but the devil lies in the details, and you want to be very thorough with documentation. It will pay dividends to read about every property that you will be using data from and following advice from the “Notes” and “Important” sections of documentation. Don’t rely on examples found on the web or in GitHub alone, as they might be incomplete and could get you in trouble.</p>

<p>Other things like empty <code class="language-plaintext highlighter-rouge">in_app</code> array or strange transaction id formats don’t get mentioned in the documentation and are left for developers to discover when the app goes live. Hopefully this post has been helpful in providing you information on how to deal with undocumented scenarios.</p>

										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: in-app-purchase, ios, storekit, and objective-c</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2020/04/21/apple-in-app-payments-integration-lessons-learned/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2020/04/21/apple-in-app-payments-integration-lessons-learned/]]></guid>
		<pubDate>2020-04-21T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Refunding Google Play In-App Purchases via API with Java]]></title>
		<description>
			<![CDATA[
				<p>This article describes how to use Google Play Developer API with the Google API Client library with Java to refund Google Play In-App Purchases. Hopefully this information and the example script provided will save someone a bit of time.</p>


				<p>This article describes how to use Google Play Developer API with the Google API Client library with Java to refund Google Play In-App Purchases. Hopefully this information and the example script provided will save someone a bit of time.</p>

<p>Unlike Apple App Store, the Google Play platform offers an ability to refund in-app purchase orders, which can be accomplished using one of the following:</p>

<ul>
  <li>Manually via the <a href="https://developer.android.com/distribute/console/">Google Play Console</a> on the web.</li>
  <li>Programmatically via a REST API</li>
</ul>

<p>If you need to refund more than a handful of orders, the REST API is a life saver. Google also provides a <a href="https://github.com/googleapis/google-api-java-client-services/tree/master/clients/google-api-services-androidpublisher/v3">library</a> that makes it very easy to get started. The only downside is there aren’t many examples and the documentation just points to the Javadoc references. Having gone through that exercise, here is my own example on how to refund orders using v3 of the client library.</p>

<h2 id="prerequisite">Prerequisite</h2>

<p>You will need a Google Service account that has permissions to manage orders.</p>

<blockquote>
  <ol>
    <li>Go to the <a href="https://play.google.com/apps/publish/#ApiAccessPlace">API Access</a> page on the Google Play Console.</li>
    <li>Under <strong>Service Accounts</strong>, click <strong>Create Service Account</strong>.</li>
    <li>Follow the instructions on the page to create your service account.</li>
    <li>Once you’ve created the service account on the Google Developers Console, click <strong>Done</strong>. The <a href="https://play.google.com/apps/publish/#ApiAccessPlace">API Access</a> page automatically refreshes, and your service account will be listed.</li>
    <li>Click <strong>Grant Access</strong> to provide the service account the rights to manage orders.</li>
  </ol>
</blockquote>

<p>If you get lost you can also try <a href="https://developers.google.com/android-publisher/getting_started#setting_up_api_access_clients">this guide</a> from Google’s docs.</p>

<h2 id="installation">Installation</h2>

<p>Add the Google API Client library to your project using your favorite build tool.</p>

<h3 id="maven">Maven</h3>

<p>Add the following lines to your <code class="language-plaintext highlighter-rouge">pom.xml</code> file:</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;project&gt;</span>
  <span class="nt">&lt;dependencies&gt;</span>
    <span class="nt">&lt;dependency&gt;</span>
      <span class="nt">&lt;groupId&gt;</span>com.google.apis<span class="nt">&lt;/groupId&gt;</span>
      <span class="nt">&lt;artifactId&gt;</span>google-api-services-androidpublisher<span class="nt">&lt;/artifactId&gt;</span>
      <span class="nt">&lt;version&gt;</span>v3-rev20200223-1.30.9<span class="nt">&lt;/version&gt;</span>
    <span class="nt">&lt;/dependency&gt;</span>
  <span class="nt">&lt;/dependencies&gt;</span>
<span class="nt">&lt;/project&gt;</span>
</code></pre></div></div>

<h3 id="gradle">Gradle</h3>

<div class="language-groovy highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">repositories</span> <span class="o">{</span>
  <span class="n">mavenCentral</span><span class="o">()</span>
<span class="o">}</span>
<span class="n">dependencies</span> <span class="o">{</span>
  <span class="n">compile</span> <span class="s1">'com.google.apis:google-api-services-androidpublisher:v3-rev20200223-1.30.9'</span>
<span class="o">}</span>
</code></pre></div></div>

<h2 id="example-script">Example Script</h2>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">com.google.api.client.googleapis.auth.oauth2.GoogleCredential</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">com.google.api.client.http.HttpTransport</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">com.google.api.client.http.javanet.NetHttpTransport</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">com.google.api.client.json.jackson2.JacksonFactory</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">com.google.api.services.androidpublisher.AndroidPublisher</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">com.google.api.services.androidpublisher.AndroidPublisherScopes</span><span class="o">;</span>

<span class="kn">import</span> <span class="nn">java.io.ByteArrayInputStream</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.io.IOException</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.Collections</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.Set</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.logging.Handler</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.logging.Level</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.logging.LogRecord</span><span class="o">;</span>
<span class="kn">import</span> <span class="nn">java.util.logging.Logger</span><span class="o">;</span>

<span class="kd">class</span> <span class="nc">Scratch</span> <span class="o">{</span>
    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">main</span><span class="o">(</span><span class="nc">String</span><span class="o">[]</span> <span class="n">args</span><span class="o">)</span> <span class="o">{</span>
        <span class="n">enableLogging</span><span class="o">();</span>

        <span class="nc">Set</span><span class="o">&lt;</span><span class="nc">String</span><span class="o">&gt;</span> <span class="no">SCOPES</span> <span class="o">=</span> <span class="nc">Collections</span><span class="o">.</span><span class="na">singleton</span><span class="o">(</span><span class="nc">AndroidPublisherScopes</span><span class="o">.</span><span class="na">ANDROIDPUBLISHER</span><span class="o">);</span>
        <span class="nc">JacksonFactory</span> <span class="n">jsonFactory</span> <span class="o">=</span> <span class="nc">JacksonFactory</span><span class="o">.</span><span class="na">getDefaultInstance</span><span class="o">();</span>
        <span class="nc">NetHttpTransport</span> <span class="n">httpTransport</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">NetHttpTransport</span><span class="o">();</span>
        <span class="nc">GoogleCredential</span> <span class="n">credential</span> <span class="o">=</span> <span class="n">getGoogleCredentials</span><span class="o">(</span><span class="s">"private service key goes here"</span><span class="o">)</span>
                                        <span class="o">.</span><span class="na">createScoped</span><span class="o">(</span><span class="no">SCOPES</span><span class="o">);</span>
        <span class="nc">AndroidPublisher</span> <span class="n">androidPublisher</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">AndroidPublisher</span>
                <span class="o">.</span><span class="na">Builder</span><span class="o">(</span><span class="n">httpTransport</span><span class="o">,</span> <span class="n">jsonFactory</span><span class="o">,</span> <span class="n">credential</span><span class="o">)</span>
                <span class="o">.</span><span class="na">setApplicationName</span><span class="o">(</span><span class="s">"com.yourname.app"</span><span class="o">)</span>
                <span class="o">.</span><span class="na">build</span><span class="o">();</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="n">androidPublisher</span><span class="o">.</span><span class="na">orders</span><span class="o">()</span>
              <span class="o">.</span><span class="na">refund</span><span class="o">(</span><span class="s">"com.yourname.app"</span><span class="o">,</span><span class="s">"GPA.3333-7777-6666-44444"</span><span class="o">)</span>
              <span class="o">.</span><span class="na">execute</span><span class="o">();</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">e</span><span class="o">.</span><span class="na">getMessage</span><span class="o">());</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="kd">private</span> <span class="kd">static</span> <span class="nc">GoogleCredential</span> <span class="nf">getGoogleCredentials</span><span class="o">(</span><span class="nc">String</span> <span class="n">privateKey</span><span class="o">)</span> <span class="o">{</span>
        <span class="k">try</span> <span class="o">{</span>
            <span class="k">return</span> <span class="nc">GoogleCredential</span><span class="o">.</span><span class="na">fromStream</span><span class="o">(</span>
              <span class="k">new</span> <span class="nf">ByteArrayInputStream</span><span class="o">(</span><span class="n">privateKey</span><span class="o">.</span><span class="na">getBytes</span><span class="o">()));</span>
        <span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nf">IllegalArgumentException</span><span class="o">(</span><span class="s">"Private key for Google Pay is invalid"</span><span class="o">,</span> <span class="n">e</span><span class="o">);</span>
        <span class="o">}</span>
    <span class="o">}</span>

    <span class="kd">public</span> <span class="kd">static</span> <span class="kt">void</span> <span class="nf">enableLogging</span><span class="o">()</span> <span class="o">{</span>
        <span class="nc">Logger</span> <span class="n">logger</span> <span class="o">=</span> <span class="nc">Logger</span><span class="o">.</span><span class="na">getLogger</span><span class="o">(</span><span class="nc">HttpTransport</span><span class="o">.</span><span class="na">class</span><span class="o">.</span><span class="na">getName</span><span class="o">());</span>
        <span class="n">logger</span><span class="o">.</span><span class="na">setLevel</span><span class="o">(</span><span class="nc">Level</span><span class="o">.</span><span class="na">CONFIG</span><span class="o">);</span>
        <span class="n">logger</span><span class="o">.</span><span class="na">addHandler</span><span class="o">(</span><span class="k">new</span> <span class="nc">Handler</span><span class="o">()</span> <span class="o">{</span>
            <span class="nd">@Override</span>
            <span class="kd">public</span> <span class="kt">void</span> <span class="nf">close</span><span class="o">()</span> <span class="kd">throws</span> <span class="nc">SecurityException</span> <span class="o">{</span>
            <span class="o">}</span>
            <span class="nd">@Override</span>
            <span class="kd">public</span> <span class="kt">void</span> <span class="nf">flush</span><span class="o">()</span> <span class="o">{</span>
            <span class="o">}</span>
            <span class="nd">@Override</span>
            <span class="kd">public</span> <span class="kt">void</span> <span class="nf">publish</span><span class="o">(</span><span class="nc">LogRecord</span> <span class="n">record</span><span class="o">)</span> <span class="o">{</span>
                <span class="c1">// Default ConsoleHandler will print &gt;= INFO to System.err.</span>
                <span class="k">if</span> <span class="o">(</span><span class="n">record</span><span class="o">.</span><span class="na">getLevel</span><span class="o">().</span><span class="na">intValue</span><span class="o">()</span> <span class="o">&lt;</span> <span class="nc">Level</span><span class="o">.</span><span class="na">INFO</span><span class="o">.</span><span class="na">intValue</span><span class="o">())</span> <span class="o">{</span>
                    <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">record</span><span class="o">.</span><span class="na">getMessage</span><span class="o">());</span>
                <span class="o">}</span>
            <span class="o">}</span>
        <span class="o">});</span>
    <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p>In the above script:</p>

<ul>
  <li>Refund API returns 204 HTTP Status Code (No content) if a refund was successful.</li>
  <li>Additional logging is enabled by calling enableLogging() . This provides debug logging of NetHttpTransport request/response.</li>
</ul>

<p>Hopefully this example script will save someone a bit of time.</p>

										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: in-app-purchase, android, and java</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2020/04/01/refunding-google-play-iap-with-java.md/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2020/04/01/refunding-google-play-iap-with-java.md/]]></guid>
		<pubDate>2020-04-01T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Cross-Platform In-App Purchases in iOS]]></title>
		<description>
			<![CDATA[
				<p>Implementing cross-platform purchases in iOS is not very well documented and can cause some anxiety before submitting your app for Apple’s approval. In this post I’m hoping to provide some basic guidance and explanation about which type of in-app products are best suited for that task.</p>

<p>The use case I’m describing is when a user’s purchased inventory is tied to an organizational (non-apple) user account and is tracked by an external service. For example, when a user buys a song from your mobile app on iOS or Android device, and then logs in to a web version of your app, the song should be instantly available to play in his/her collection. It also works the other way around, where you can buy something on the web, and it should be available on a mobile device. The purchased inventory and the list of available products is independent of the mobile platform. The bottom line: , it will be the responsibility of your inventory service to make sure that items which were already purchased can only be purchased once and not be displayed to the users.</p>

<p>One of the in-app purchase types that is not compatible with cross-platform payments is the App Store’s <code class="language-plaintext highlighter-rouge">non-consumable</code> type. Apple developer documentation defines it as:</p>

<blockquote>
  <p>Non-consumables are purchased once and do not expire, such as additional filters in a photo app.</p>
</blockquote>

<p>This type also comes with a an important requirement:</p>

<blockquote>
  <p>If your app sells non-consumable, auto-renewable subscription or
non-renewing subscription products, you must provide users with the
ability to restore them.”</p>
</blockquote>

<p>If you want to sell a cross-platform product that can only be purchased once, after reading the Apple definition, you may think that <code class="language-plaintext highlighter-rouge">non-consumable</code> type is the answer, but the additional requirement may confuse you.</p>

<p>There is also one place (<a href="https://developer.apple.com/app-store/review/guidelines/#business">App Store Review Guidelines</a>) where documentation mentions multi platform services, but it doesn’t say anything about <code class="language-plaintext highlighter-rouge">non-consumable</code> types.</p>

<blockquote>
  <p>3.1.3(b) Multiplatform Services: Apps that operate across multiple platforms may allow users to access content, subscriptions, or
features they have acquired in your app on other platforms or your web
site, including consumable items in multiplatform games, provided
those items are also available as in-app purchases within the app.</p>
</blockquote>

<p>One of the features of App Store’s StoreKit is the ability to manage inventory of purchased items, meaning it will be responsible for filtering out items that were already purchased. This is handy if a user has lost or bought a new iOS device because it offers the ability to restore purchased items. However, when you let Apple manage your inventory, the purchased inventory will be tied to a user’s iTunes account and not your cross-platform user account. It’s also problematic if a user purchases an item outside of Apple’s platform; Apple would not be able to restore it.</p>

<p>When the inventory is managed by an external service there is no need for the second purchase management system (apple). The inventory travels with your organizational user account, available after login, and does not need to be restored to the device. Therefore, even though Apple does not mention it, <strong>non-consumable types are not compatible with the multiplatform purchase inventory.</strong></p>

<p>This is why <strong>you can only use a <code class="language-plaintext highlighter-rouge">consumable</code> purchase type when you have an external purchased inventory</strong>. As soon as a user makes a purchase you top up his/her organizational account with content and consume the item. This inventory service is also used to filter out items that were already purchased because Apple is not a system of record anymore.</p>

<p>Making all your in-app purchase products consumables, even for items that can only be consumed once, might make you nervous, especially if you haven’t gone through the apple approval process before. But logically there is no other way. So hopefully this post save you some anxiety.</p>

				<p>Implementing cross-platform purchases in iOS is not very well documented and can cause some anxiety before submitting your app for Apple’s approval. In this post I’m hoping to provide some basic guidance and explanation about which type of in-app products are best suited for that task.</p>

<p>The use case I’m describing is when a user’s purchased inventory is tied to an organizational (non-apple) user account and is tracked by an external service. For example, when a user buys a song from your mobile app on iOS or Android device, and then logs in to a web version of your app, the song should be instantly available to play in his/her collection. It also works the other way around, where you can buy something on the web, and it should be available on a mobile device. The purchased inventory and the list of available products is independent of the mobile platform. The bottom line: , it will be the responsibility of your inventory service to make sure that items which were already purchased can only be purchased once and not be displayed to the users.</p>

<p>One of the in-app purchase types that is not compatible with cross-platform payments is the App Store’s <code class="language-plaintext highlighter-rouge">non-consumable</code> type. Apple developer documentation defines it as:</p>

<blockquote>
  <p>Non-consumables are purchased once and do not expire, such as additional filters in a photo app.</p>
</blockquote>

<p>This type also comes with a an important requirement:</p>

<blockquote>
  <p>If your app sells non-consumable, auto-renewable subscription or
non-renewing subscription products, you must provide users with the
ability to restore them.”</p>
</blockquote>

<p>If you want to sell a cross-platform product that can only be purchased once, after reading the Apple definition, you may think that <code class="language-plaintext highlighter-rouge">non-consumable</code> type is the answer, but the additional requirement may confuse you.</p>

<p>There is also one place (<a href="https://developer.apple.com/app-store/review/guidelines/#business">App Store Review Guidelines</a>) where documentation mentions multi platform services, but it doesn’t say anything about <code class="language-plaintext highlighter-rouge">non-consumable</code> types.</p>

<blockquote>
  <p>3.1.3(b) Multiplatform Services: Apps that operate across multiple platforms may allow users to access content, subscriptions, or
features they have acquired in your app on other platforms or your web
site, including consumable items in multiplatform games, provided
those items are also available as in-app purchases within the app.</p>
</blockquote>

<p>One of the features of App Store’s StoreKit is the ability to manage inventory of purchased items, meaning it will be responsible for filtering out items that were already purchased. This is handy if a user has lost or bought a new iOS device because it offers the ability to restore purchased items. However, when you let Apple manage your inventory, the purchased inventory will be tied to a user’s iTunes account and not your cross-platform user account. It’s also problematic if a user purchases an item outside of Apple’s platform; Apple would not be able to restore it.</p>

<p>When the inventory is managed by an external service there is no need for the second purchase management system (apple). The inventory travels with your organizational user account, available after login, and does not need to be restored to the device. Therefore, even though Apple does not mention it, <strong>non-consumable types are not compatible with the multiplatform purchase inventory.</strong></p>

<p>This is why <strong>you can only use a <code class="language-plaintext highlighter-rouge">consumable</code> purchase type when you have an external purchased inventory</strong>. As soon as a user makes a purchase you top up his/her organizational account with content and consume the item. This inventory service is also used to filter out items that were already purchased because Apple is not a system of record anymore.</p>

<p>Making all your in-app purchase products consumables, even for items that can only be consumed once, might make you nervous, especially if you haven’t gone through the apple approval process before. But logically there is no other way. So hopefully this post save you some anxiety.</p>

										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: in-app-purchase, ios, and cross-platform</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2020/03/19/cross-platform-in-app-purchases-in-ios/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2020/03/19/cross-platform-in-app-purchases-in-ios/]]></guid>
		<pubDate>2020-03-19T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[The Aggregation of Marginal Gains]]></title>
		<description>
			<![CDATA[
				<p>In his book, <a href="https://amzn.to/2UnRpLy">Atomic Habits</a>, author James Clear tells a story about a struggling British cycling team that for over a hundred years won only one gold Olympic medal and did not win a single Tour de France, cycling’s biggest race . After the team hired a new performance director, he brought with him a new philosophy, referred to as “the aggregation of marginal gains,” which focused on tiny improvements in every thing that you do. Together with his team, the new director introduced over a hundred small improvements, including redesigning a bicycle seat, testing different fabrics for air dynamics, and rubbing alcohol on the tires to make them grip better. He even brought in a surgeon to teach riders how to wash their hands better so they would not get sick.</p>

<p>All these minor improvements had an incredible impact. Within five years after the new performance director took over, the team won 60% of the gold medals for the cycling events at the 2008 Olympic Games in Beijing.</p>

<p>If we apply the same philosophy to the software engineering teams, what type of tiny improvements could have a big impact in the long run? Here are a few that I think can be a good start.</p>

<h2 id="incremental-refactoring">Incremental Refactoring</h2>

<p>By creating a good habit of leaving the code base better than it was before, chances are that our projects would be easier to maintain in the long run. Besides making the code more expressive, easier to read and modify, engineers can also add missing unit tests, cleaning up legacy comments, or format code. I think the trick is to have a balance and sprinkle improvements a little bit over time. Nobody wants to review a huge refactoring for correctness when it’s unrelated to the task assigned. As a bonus if you could separate refactoring in a separate pull request, your reviewers will thank you. Finally, if you are looking to learn more about refactoring, I highly recommend the book, <a href="https://amzn.to/2UmVpvK">Refactoring: Improving the Design of Existing Code</a>.</p>

<h2 id="small-bug-fixes-without-tickets">Small Bug Fixes Without Tickets</h2>

<p>Not every bug fix needs to go through a process of writing up a ticket, getting it estimated, prioritized and planned. If the bug fix is small enough and the engineer has the context around it, it is worth fixing it along with the primary task. The cost of the bug fix at that moment will be significantly lower and will not require a context switch for another engineer or yourself a few months later. Finally, customers will appreciate quick fixes if it affects them.</p>

<h2 id="document-root-cause-analysis-for-major-incidents">Document Root Cause Analysis for Major Incidents</h2>

<p>Every failure is a great opportunity to learn from mistakes. Before we can do that, we must first gather all available information about the incident, ask five whys, and create an action plan on how it can be prevented in the future. It’s also valuable to share this information with the stakeholders and team, because they might have a different perspective and offer valuable insights that might not be obvious to the author. In addition to improving processes, documenting incidents is also valuable for tracking purposes; it helps to determine if the team is improving over the long term.</p>

<h2 id="reviewing-logs-after-deployments">Reviewing Logs After Deployments</h2>

<p>Reviewing error logs after each deployment can help identify issues caused by newly released code and get them resolved right away. It’s much cheaper to fix bugs when the context is fresh in the author’s mind. And it could help to save a lot of time and frustration for customers, support and the engineering team. Some bugs could require a data back-fill or other escalation, and if left unchecked, can create a lot of unnecessary work.</p>

<h2 id="quick-responses-to-questions-and-requests">Quick Responses to Questions and Requests</h2>

<blockquote>
  <p>When researchers compiled a huge database of the digital habits of <a href="https://medium.com/@duncanjwatts/the-organizational-spectroscope-7f9f239a897c">teams at Microsoft</a>, they found that the clearest warning sign of an ineffective manager was being slow to answer emails. Responding in a timely manner shows that you are conscientious — organized, dependable and hardworking. And that matters. In a <a href="http://psycnet.apa.org/record/2000-16508-004?casa_token=gqkQhZM9qwIAAAAA:QEr6Zmq76aqx63hGeqSf3FNhv02-J5XhnIKNTAouwMA-Cdl_X4_cDQhuSFaGv7EdRKcSbikV4qdxFcOquu4Xxw">comprehensive analysis</a> of people in hundreds of occupations, conscientiousness was the single best personality predictor of job performance.
- Adam Grant <a href="https://www.nytimes.com/2019/02/15/opinion/sunday/email-etiquette.html">No, You Can’t Ignore Email. It’s Rude.</a></p>
</blockquote>

<p>According to Adam Grant, an organizational psychologist, quick responses are the best predictor of job performance. Because our customers and peers are our top priority, it makes sense to try to get a little bit quicker at responding to emails or messages. I can vouch for this myself. I certainly appreciate when someone on my team reviews my code review request right away; it prevents me from switching off to a different task and allows me to get more stuff done.</p>

<h2 id="readme-files">README Files</h2>

<p>Putting together a README file for projects will save time when someone else, or yourself in the future, has to get started on the project. You can find suggestions on how to make good README files <a href="https://www.makeareadme.com/#suggestions-for-a-good-readme">here</a>. Small investments into better documentation will pay off in the future.</p>

<h2 id="do-not-stop-here">Do Not Stop Here</h2>

<p>This was not meant to be an exhaustive list, just a starting sample of things that may or may not work for your projects. Most important are not the improvements by themselves, but the willingness to adopt a philosophy of continuous aggregation of improvements that will make a difference in the long run.</p>

				<p>In his book, <a href="https://amzn.to/2UnRpLy">Atomic Habits</a>, author James Clear tells a story about a struggling British cycling team that for over a hundred years won only one gold Olympic medal and did not win a single Tour de France, cycling’s biggest race . After the team hired a new performance director, he brought with him a new philosophy, referred to as “the aggregation of marginal gains,” which focused on tiny improvements in every thing that you do. Together with his team, the new director introduced over a hundred small improvements, including redesigning a bicycle seat, testing different fabrics for air dynamics, and rubbing alcohol on the tires to make them grip better. He even brought in a surgeon to teach riders how to wash their hands better so they would not get sick.</p>

<p>All these minor improvements had an incredible impact. Within five years after the new performance director took over, the team won 60% of the gold medals for the cycling events at the 2008 Olympic Games in Beijing.</p>

<p>If we apply the same philosophy to the software engineering teams, what type of tiny improvements could have a big impact in the long run? Here are a few that I think can be a good start.</p>

<h2 id="incremental-refactoring">Incremental Refactoring</h2>

<p>By creating a good habit of leaving the code base better than it was before, chances are that our projects would be easier to maintain in the long run. Besides making the code more expressive, easier to read and modify, engineers can also add missing unit tests, cleaning up legacy comments, or format code. I think the trick is to have a balance and sprinkle improvements a little bit over time. Nobody wants to review a huge refactoring for correctness when it’s unrelated to the task assigned. As a bonus if you could separate refactoring in a separate pull request, your reviewers will thank you. Finally, if you are looking to learn more about refactoring, I highly recommend the book, <a href="https://amzn.to/2UmVpvK">Refactoring: Improving the Design of Existing Code</a>.</p>

<h2 id="small-bug-fixes-without-tickets">Small Bug Fixes Without Tickets</h2>

<p>Not every bug fix needs to go through a process of writing up a ticket, getting it estimated, prioritized and planned. If the bug fix is small enough and the engineer has the context around it, it is worth fixing it along with the primary task. The cost of the bug fix at that moment will be significantly lower and will not require a context switch for another engineer or yourself a few months later. Finally, customers will appreciate quick fixes if it affects them.</p>

<h2 id="document-root-cause-analysis-for-major-incidents">Document Root Cause Analysis for Major Incidents</h2>

<p>Every failure is a great opportunity to learn from mistakes. Before we can do that, we must first gather all available information about the incident, ask five whys, and create an action plan on how it can be prevented in the future. It’s also valuable to share this information with the stakeholders and team, because they might have a different perspective and offer valuable insights that might not be obvious to the author. In addition to improving processes, documenting incidents is also valuable for tracking purposes; it helps to determine if the team is improving over the long term.</p>

<h2 id="reviewing-logs-after-deployments">Reviewing Logs After Deployments</h2>

<p>Reviewing error logs after each deployment can help identify issues caused by newly released code and get them resolved right away. It’s much cheaper to fix bugs when the context is fresh in the author’s mind. And it could help to save a lot of time and frustration for customers, support and the engineering team. Some bugs could require a data back-fill or other escalation, and if left unchecked, can create a lot of unnecessary work.</p>

<h2 id="quick-responses-to-questions-and-requests">Quick Responses to Questions and Requests</h2>

<blockquote>
  <p>When researchers compiled a huge database of the digital habits of <a href="https://medium.com/@duncanjwatts/the-organizational-spectroscope-7f9f239a897c">teams at Microsoft</a>, they found that the clearest warning sign of an ineffective manager was being slow to answer emails. Responding in a timely manner shows that you are conscientious — organized, dependable and hardworking. And that matters. In a <a href="http://psycnet.apa.org/record/2000-16508-004?casa_token=gqkQhZM9qwIAAAAA:QEr6Zmq76aqx63hGeqSf3FNhv02-J5XhnIKNTAouwMA-Cdl_X4_cDQhuSFaGv7EdRKcSbikV4qdxFcOquu4Xxw">comprehensive analysis</a> of people in hundreds of occupations, conscientiousness was the single best personality predictor of job performance.
- Adam Grant <a href="https://www.nytimes.com/2019/02/15/opinion/sunday/email-etiquette.html">No, You Can’t Ignore Email. It’s Rude.</a></p>
</blockquote>

<p>According to Adam Grant, an organizational psychologist, quick responses are the best predictor of job performance. Because our customers and peers are our top priority, it makes sense to try to get a little bit quicker at responding to emails or messages. I can vouch for this myself. I certainly appreciate when someone on my team reviews my code review request right away; it prevents me from switching off to a different task and allows me to get more stuff done.</p>

<h2 id="readme-files">README Files</h2>

<p>Putting together a README file for projects will save time when someone else, or yourself in the future, has to get started on the project. You can find suggestions on how to make good README files <a href="https://www.makeareadme.com/#suggestions-for-a-good-readme">here</a>. Small investments into better documentation will pay off in the future.</p>

<h2 id="do-not-stop-here">Do Not Stop Here</h2>

<p>This was not meant to be an exhaustive list, just a starting sample of things that may or may not work for your projects. Most important are not the improvements by themselves, but the willingness to adopt a philosophy of continuous aggregation of improvements that will make a difference in the long run.</p>

										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: software-engineering</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2020/02/05/the-aggregation-of-marginal-gains/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2020/02/05/the-aggregation-of-marginal-gains/]]></guid>
		<pubDate>2020-02-05T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[My 2019 Year In Review]]></title>
		<description>
			<![CDATA[
				<p>This is my first attempt at reviewing my yearly progress. Inspired by <a href="https://jamesclear.com/2019-annual-review">James Clear’s yearly reviews</a>, and similar to a <a href="https://www.scrum.org/resources/what-is-a-sprint-retrospective">sprint retrospective</a> in Scrum methodology, it’s an opportunity to look back and see what things worked that I should continue doing or where I can improve. In addition, because I have a hard time remembering things I did in prior years, having a point of reference will be valuable for my future self.</p>

<p>The idea is to answer the following three simple questions:</p>

<ol>
  <li>What went well this year?</li>
  <li>What didn’t go so well this year?</li>
  <li>What did I learn?</li>
</ol>

<h2 id="what-went-well-this-year">What went well this year?</h2>

<p><strong>Reading.</strong> Last year stumbled upon a great book on reading itself, <a href="https://amzn.to/384X9NQ">How to Read a Book</a>. Prior to reading it, my reading was at the elementary level. With the new knowledge acquired from this book and with practice, hopefully I can progress into analytical reading and beyond. Finally, this book also inspired me to look into books with topics outside of my current interest and difficulty and provided techniques on how to approach hard subjects.</p>

<p>On a different note, I picked an excellent tip from one of the interviews with <a href="https://sivers.org/book">Derek Sivers</a> on how to retain information. In order to remember ideas from the books that he reads, he takes his notes and publishes them on his <a href="https://sivers.org/book">website</a>. This gives him the ability to access his notes from anywhere. Finally, he has a habit of reviewing his notes for a random book every morning. After struggling with remembering information from books for a long time, I’m eager to try his approach and have already published a few <a href="https://books.maskalik.com/">book notes</a> myself.</p>

<p>This year I read: <a href="https://amzn.to/2RhoYvg">The Three-Body Problem</a>, <a href="https://amzn.to/382fM4U">Joyful Wisdom: Embracing Change and Finding Freedom</a>, <a href="https://amzn.to/382v2yB">Awareness</a>, <a href="https://amzn.to/2u18XBJ">Stillness Is the Key</a>, <a href="https://amzn.to/2FYTTaR">A Guide to the Good Life</a>, <a href="https://amzn.to/3a99MZS">Atomic Habits</a>, <a href="https://amzn.to/36SQohL">C++ Crash Course</a>, <a href="https://amzn.to/384X9NQ">How to Read a Book</a>.</p>

<p>Overall it wasn’t a stellar year in terms of volume, but rather it’s my approach to reading, improving depth and retention that I am most excited about.</p>

<p><strong>Traveling.</strong> I had a great time in Hawaii on the island of Maui with my wife and daughter. It was great to spend a couple of weeks at the beach and swim in the warm waters. One of the highlights was when we took a side trip to the Big Island and went snorkeling in the crystal clear waters with beautiful fish and corals. My wife and I were amazed to see my daughter, almost two years old, fearlessly jumping into the water from the boat and swimming in the deep water with her floating device.</p>

<p><strong>Exercise.</strong> Besides having many bouts of back spasms and getting sick more than usual, I was able to come back to my workout routine and be more or less consistent. When we traveled I wasn’t able to exercise and actually experienced craving, which was very encouraging.</p>

<p>Workouts per month in 2019</p>

<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Workouts</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>8</td>
    </tr>
    <tr>
      <td>February</td>
      <td>16</td>
    </tr>
    <tr>
      <td>March</td>
      <td>19</td>
    </tr>
    <tr>
      <td>April</td>
      <td>12 (sick)</td>
    </tr>
    <tr>
      <td>May</td>
      <td>2 (travel)</td>
    </tr>
    <tr>
      <td>June</td>
      <td>4 (sick)</td>
    </tr>
    <tr>
      <td>July</td>
      <td>7</td>
    </tr>
    <tr>
      <td>August</td>
      <td>13</td>
    </tr>
    <tr>
      <td>September</td>
      <td>8 (back)</td>
    </tr>
    <tr>
      <td>October</td>
      <td>12</td>
    </tr>
    <tr>
      <td>November</td>
      <td>3 (sick)</td>
    </tr>
    <tr>
      <td>December</td>
      <td>7 (sick)</td>
    </tr>
    <tr>
      <td>Total</td>
      <td>111</td>
    </tr>
  </tbody>
</table>

<h2 id="what-didnt-go-so-well-this-year">What didn’t go so well this year?</h2>

<p><strong>Health.</strong> I was sick more than usual this year. Perhaps my immune system is not strong enough, so when my daughter gets sick there is no way I can avoid the germs. Also my sleep has been a bit broken because I tend to wake up many times. I have been experimenting with different things. The latest sleep improvement approach I’m trying at the moment is to keep the temperature down using a sleep system, which hopefully can help me stay asleep. This past year was also stressful at work, so that could have also contributed.</p>

<p>In addition, I’ve been plagued with multiple instances of back spasms. I found a promising book, <em><a href="https://amzn.to/2u3My6N">Pain Free</a></em>, that I’m in the process of implementing. Finally, Peter Attia M.D. has a set of videos on <a href="https://peterattiamd.com/move-defines-live/">proper movement</a>, which I’m also planning to practice this year.</p>

<p><strong>Writing.</strong> I didn’t publish a single blog post last year. I urgently need to improve my written communication and strongly believe that the only way to do it is through practice. This year’s main goal is to build a writing habit (Q1), and then scale up my writing slowly to two articles per week.</p>

<p><strong>Products.</strong> While I’m very fortunate to work at a great company and enjoy what I do, the downside of it is that I don’t build equity, and at the end of the day, I don’t own anything that I build. These past two years, I was solely focused on my day job, so this year I want to change that. I want to start out small and build a small mobile application for fun and to get into a habit of working on side projects.</p>

<h2 id="what-did-i-learn">What did I learn?</h2>

<p><strong>Focusing on systems rather than goals.</strong> Goals are great but they alone don’t help if you don’t have a system on how to implement them. I think that was my biggest failure point in the past. I would focus on pure willpower and motivation, work extra hard on a new goal, and then eventually burn out and stop. I think designing a system where I can focus on building a habit first, slowly, one day at a time, and then eventually scaling out effort should help me be consistent over the long term. Finally, the most important point of the system is to make it easier to work even when you are not motivated, or you don’t feel like it.</p>

<p>This also somewhat aligns with what I learned from Stoic’s teachings. You want to set internal goals, or goals that you can achieve, rather than external goals, something that is outside of your control. For example, building a successful business is an external goal because there are a lot of things that are outside of your control, and if you set a goal like that you most likely set yourself up for disappointment or frustration. On the other hand, setting aside thirty minutes a day and working on something to the best of your ability is something that is totally up to you and is achievable.</p>

<p><strong>Writing things down is important.</strong> If I want to retain ideas from books, I have to write them down and review them periodically. It is a shame that this year I bought a book and could not tell if I had read it before or not. It had only been four years since I bought it. I think I can get an exponential amount of benefit if I can retain this information, otherwise I’m only getting a small amount of benefit. The same goes for podcasts and audio-books. I enjoy consuming the content, and there are many great insights, but all those wash away very fast if I don’t write down the ideas and action steps.</p>

<p><strong>Financial independence.</strong> One way to achieve financial independence is to save 25x of your yearly expenses. The choices we make in regards to our lifestyle get us either further or closer to independence. A closet full of clothes would definitely give you something new and exciting to wear every day, but it may cost you six months of your life. That luxury car may cost you years of sitting in the office at a desk and doing something that you don’t enjoy. Every purchase we make is trade. We trade our time, a non-renewable resource, for things that we don’t need. For myself, I would rather spend this time on something that I can enjoy, like spending more time with my family or working on things that interest me.</p>

<p><strong>Sleep.</strong> Quality sleep is super important for many aspects of our wellbeing, including recovery, cognitive performance, and immune function. I’ve been tracking my sleep over the past year with an <a href="https://ouraring.com/">Oura ring</a> device and it made me aware of the following things that impact my sleep:</p>

<ul>
  <li>
    <p>Alcohol. This one is pretty obvious, but I didn’t realize that having a few drinks before bed elevates your heart rate for the entire night, similar to a light walk. Having your heart work overtime through the night when it should be resting is probably not doing a lot of good. It also negatively impacts very important deep and REM sleep.</p>
  </li>
  <li>
    <p>Big dinner or dinner with lots of carbohydrates within three hours of bedtime. Having pasta for dinner will keep my heart rate elevated for the first half of the night, affect my deep sleep and cause me to wake up in the middle of the night.</p>
  </li>
  <li>
    <p>Caffeine in the afternoon or evening. This affects heart rate variability and REM sleep.</p>
  </li>
  <li>
    <p>Late screen time. This affects deep sleep and overall quality of sleep. When I was younger I used to play a lot of video games late into the night; little did I know that this was really bad for my health and athletic performance.</p>
  </li>
  <li>
    <p>Sporadic bed time. Going to sleep later than usual will significantly decrease sleep quality by reducing deep sleep.</p>
  </li>
  <li>
    <p>Movement. Consistent exercise will decrease the resting heart rate and improve overall quality of sleep. This is pretty obvious but good feedback.</p>
  </li>
</ul>

<p>The bottom line. I learned a lot of good things last year which will hopefully help me to grow in the future. This year, I’m planning to implement what I’ve learned and make it a year of building new good habits.</p>

<p>Thanks for reading and happy new year!</p>

				<p>This is my first attempt at reviewing my yearly progress. Inspired by <a href="https://jamesclear.com/2019-annual-review">James Clear’s yearly reviews</a>, and similar to a <a href="https://www.scrum.org/resources/what-is-a-sprint-retrospective">sprint retrospective</a> in Scrum methodology, it’s an opportunity to look back and see what things worked that I should continue doing or where I can improve. In addition, because I have a hard time remembering things I did in prior years, having a point of reference will be valuable for my future self.</p>

<p>The idea is to answer the following three simple questions:</p>

<ol>
  <li>What went well this year?</li>
  <li>What didn’t go so well this year?</li>
  <li>What did I learn?</li>
</ol>

<h2 id="what-went-well-this-year">What went well this year?</h2>

<p><strong>Reading.</strong> Last year stumbled upon a great book on reading itself, <a href="https://amzn.to/384X9NQ">How to Read a Book</a>. Prior to reading it, my reading was at the elementary level. With the new knowledge acquired from this book and with practice, hopefully I can progress into analytical reading and beyond. Finally, this book also inspired me to look into books with topics outside of my current interest and difficulty and provided techniques on how to approach hard subjects.</p>

<p>On a different note, I picked an excellent tip from one of the interviews with <a href="https://sivers.org/book">Derek Sivers</a> on how to retain information. In order to remember ideas from the books that he reads, he takes his notes and publishes them on his <a href="https://sivers.org/book">website</a>. This gives him the ability to access his notes from anywhere. Finally, he has a habit of reviewing his notes for a random book every morning. After struggling with remembering information from books for a long time, I’m eager to try his approach and have already published a few <a href="https://books.maskalik.com/">book notes</a> myself.</p>

<p>This year I read: <a href="https://amzn.to/2RhoYvg">The Three-Body Problem</a>, <a href="https://amzn.to/382fM4U">Joyful Wisdom: Embracing Change and Finding Freedom</a>, <a href="https://amzn.to/382v2yB">Awareness</a>, <a href="https://amzn.to/2u18XBJ">Stillness Is the Key</a>, <a href="https://amzn.to/2FYTTaR">A Guide to the Good Life</a>, <a href="https://amzn.to/3a99MZS">Atomic Habits</a>, <a href="https://amzn.to/36SQohL">C++ Crash Course</a>, <a href="https://amzn.to/384X9NQ">How to Read a Book</a>.</p>

<p>Overall it wasn’t a stellar year in terms of volume, but rather it’s my approach to reading, improving depth and retention that I am most excited about.</p>

<p><strong>Traveling.</strong> I had a great time in Hawaii on the island of Maui with my wife and daughter. It was great to spend a couple of weeks at the beach and swim in the warm waters. One of the highlights was when we took a side trip to the Big Island and went snorkeling in the crystal clear waters with beautiful fish and corals. My wife and I were amazed to see my daughter, almost two years old, fearlessly jumping into the water from the boat and swimming in the deep water with her floating device.</p>

<p><strong>Exercise.</strong> Besides having many bouts of back spasms and getting sick more than usual, I was able to come back to my workout routine and be more or less consistent. When we traveled I wasn’t able to exercise and actually experienced craving, which was very encouraging.</p>

<p>Workouts per month in 2019</p>

<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Workouts</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>8</td>
    </tr>
    <tr>
      <td>February</td>
      <td>16</td>
    </tr>
    <tr>
      <td>March</td>
      <td>19</td>
    </tr>
    <tr>
      <td>April</td>
      <td>12 (sick)</td>
    </tr>
    <tr>
      <td>May</td>
      <td>2 (travel)</td>
    </tr>
    <tr>
      <td>June</td>
      <td>4 (sick)</td>
    </tr>
    <tr>
      <td>July</td>
      <td>7</td>
    </tr>
    <tr>
      <td>August</td>
      <td>13</td>
    </tr>
    <tr>
      <td>September</td>
      <td>8 (back)</td>
    </tr>
    <tr>
      <td>October</td>
      <td>12</td>
    </tr>
    <tr>
      <td>November</td>
      <td>3 (sick)</td>
    </tr>
    <tr>
      <td>December</td>
      <td>7 (sick)</td>
    </tr>
    <tr>
      <td>Total</td>
      <td>111</td>
    </tr>
  </tbody>
</table>

<h2 id="what-didnt-go-so-well-this-year">What didn’t go so well this year?</h2>

<p><strong>Health.</strong> I was sick more than usual this year. Perhaps my immune system is not strong enough, so when my daughter gets sick there is no way I can avoid the germs. Also my sleep has been a bit broken because I tend to wake up many times. I have been experimenting with different things. The latest sleep improvement approach I’m trying at the moment is to keep the temperature down using a sleep system, which hopefully can help me stay asleep. This past year was also stressful at work, so that could have also contributed.</p>

<p>In addition, I’ve been plagued with multiple instances of back spasms. I found a promising book, <em><a href="https://amzn.to/2u3My6N">Pain Free</a></em>, that I’m in the process of implementing. Finally, Peter Attia M.D. has a set of videos on <a href="https://peterattiamd.com/move-defines-live/">proper movement</a>, which I’m also planning to practice this year.</p>

<p><strong>Writing.</strong> I didn’t publish a single blog post last year. I urgently need to improve my written communication and strongly believe that the only way to do it is through practice. This year’s main goal is to build a writing habit (Q1), and then scale up my writing slowly to two articles per week.</p>

<p><strong>Products.</strong> While I’m very fortunate to work at a great company and enjoy what I do, the downside of it is that I don’t build equity, and at the end of the day, I don’t own anything that I build. These past two years, I was solely focused on my day job, so this year I want to change that. I want to start out small and build a small mobile application for fun and to get into a habit of working on side projects.</p>

<h2 id="what-did-i-learn">What did I learn?</h2>

<p><strong>Focusing on systems rather than goals.</strong> Goals are great but they alone don’t help if you don’t have a system on how to implement them. I think that was my biggest failure point in the past. I would focus on pure willpower and motivation, work extra hard on a new goal, and then eventually burn out and stop. I think designing a system where I can focus on building a habit first, slowly, one day at a time, and then eventually scaling out effort should help me be consistent over the long term. Finally, the most important point of the system is to make it easier to work even when you are not motivated, or you don’t feel like it.</p>

<p>This also somewhat aligns with what I learned from Stoic’s teachings. You want to set internal goals, or goals that you can achieve, rather than external goals, something that is outside of your control. For example, building a successful business is an external goal because there are a lot of things that are outside of your control, and if you set a goal like that you most likely set yourself up for disappointment or frustration. On the other hand, setting aside thirty minutes a day and working on something to the best of your ability is something that is totally up to you and is achievable.</p>

<p><strong>Writing things down is important.</strong> If I want to retain ideas from books, I have to write them down and review them periodically. It is a shame that this year I bought a book and could not tell if I had read it before or not. It had only been four years since I bought it. I think I can get an exponential amount of benefit if I can retain this information, otherwise I’m only getting a small amount of benefit. The same goes for podcasts and audio-books. I enjoy consuming the content, and there are many great insights, but all those wash away very fast if I don’t write down the ideas and action steps.</p>

<p><strong>Financial independence.</strong> One way to achieve financial independence is to save 25x of your yearly expenses. The choices we make in regards to our lifestyle get us either further or closer to independence. A closet full of clothes would definitely give you something new and exciting to wear every day, but it may cost you six months of your life. That luxury car may cost you years of sitting in the office at a desk and doing something that you don’t enjoy. Every purchase we make is trade. We trade our time, a non-renewable resource, for things that we don’t need. For myself, I would rather spend this time on something that I can enjoy, like spending more time with my family or working on things that interest me.</p>

<p><strong>Sleep.</strong> Quality sleep is super important for many aspects of our wellbeing, including recovery, cognitive performance, and immune function. I’ve been tracking my sleep over the past year with an <a href="https://ouraring.com/">Oura ring</a> device and it made me aware of the following things that impact my sleep:</p>

<ul>
  <li>
    <p>Alcohol. This one is pretty obvious, but I didn’t realize that having a few drinks before bed elevates your heart rate for the entire night, similar to a light walk. Having your heart work overtime through the night when it should be resting is probably not doing a lot of good. It also negatively impacts very important deep and REM sleep.</p>
  </li>
  <li>
    <p>Big dinner or dinner with lots of carbohydrates within three hours of bedtime. Having pasta for dinner will keep my heart rate elevated for the first half of the night, affect my deep sleep and cause me to wake up in the middle of the night.</p>
  </li>
  <li>
    <p>Caffeine in the afternoon or evening. This affects heart rate variability and REM sleep.</p>
  </li>
  <li>
    <p>Late screen time. This affects deep sleep and overall quality of sleep. When I was younger I used to play a lot of video games late into the night; little did I know that this was really bad for my health and athletic performance.</p>
  </li>
  <li>
    <p>Sporadic bed time. Going to sleep later than usual will significantly decrease sleep quality by reducing deep sleep.</p>
  </li>
  <li>
    <p>Movement. Consistent exercise will decrease the resting heart rate and improve overall quality of sleep. This is pretty obvious but good feedback.</p>
  </li>
</ul>

<p>The bottom line. I learned a lot of good things last year which will hopefully help me to grow in the future. This year, I’m planning to implement what I’ve learned and make it a year of building new good habits.</p>

<p>Thanks for reading and happy new year!</p>

										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: yearly-review</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2020/01/27/my-2019-year-in-review/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2020/01/27/my-2019-year-in-review/]]></guid>
		<pubDate>2020-01-27T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Favorite Books of 2019]]></title>
		<description>
			<![CDATA[
				<h3 id="atomic-habits"><em><a href="https://amzn.to/35nnp4l">Atomic Habits</a></em></h3>
<p>I really enjoyed this book, and I would highly recommend it to anyone who is trying to work on something that requires a lot of effort. By establishing tiny, incremental improvements in our lives, the benefits will accumulate and grow, like a financial investment. Eventually the investment will reach a critical point, and you will see a massive change. The author, James Clear has an interesting solution on how to form a habit, you want to make a daily task super easy. For example, if you are trying to be a  more consistent writer, your initial goal would be just sitting down to write for two minutes every day until you’ve established a habit. Only after you’ve made it your habit to write a little bit daily, can you progress to increase the difficulty of the task..</p>


				<h3 id="atomic-habits"><em><a href="https://amzn.to/35nnp4l">Atomic Habits</a></em></h3>
<p>I really enjoyed this book, and I would highly recommend it to anyone who is trying to work on something that requires a lot of effort. By establishing tiny, incremental improvements in our lives, the benefits will accumulate and grow, like a financial investment. Eventually the investment will reach a critical point, and you will see a massive change. The author, James Clear has an interesting solution on how to form a habit, you want to make a daily task super easy. For example, if you are trying to be a  more consistent writer, your initial goal would be just sitting down to write for two minutes every day until you’ve established a habit. Only after you’ve made it your habit to write a little bit daily, can you progress to increase the difficulty of the task..</p>

<p>The entire book is full of many other great techniques and stories. After implementing the author’s suggestions in my own life over the last month, I can already tell that  they work better than pure motivation. There were many days when I didn’t feel like performing the task at all, but by just telling myself that it’s super easy and it would take just a few minutes, I was able to complete it. I’m looking forward to continuing to work on building my habits, and if my writing habit works, I will report on the progress.</p>

<h3 id="a-guide-to-the-good-life-the-ancient-art-of-stoic-joy"><em><a href="https://amzn.to/2MNUZde">A Guide to the Good Life: The Ancient Art of Stoic Joy</a></em></h3>
<p>This book was highly recommended by Tim Ferriss on his podcast, and it quickly became one of my favorites. Stoic philosophy provides ancient wisdom that is still relevant today. It explains that without a coherent philosophy of life, humans are more likely to default to pleasure maximization and distractions that will lead to squandering time, or worse, pursuing something that would not fulfill us in the end. Because Stoic philosophy is based on logic, a lot of it makes sense and does not require you to believe in something abstract or intangible.</p>

<p>Stoics believed that the key to happiness is to prevent ourselves from taking for granted things that we already have. Because a lot of human unhappiness comes from a desire to have more, if we practice appreciation for all the things we worked so hard to get, we can trade desire for enjoyment. In addition to being grateful, another technique would be to imagine losing the things that we already have. This would also make us appreciate our existing situation and not take things, relationships or our health for granted.</p>

<p>Another great piece of wisdom that I really enjoyed was the importance of setting achievable goals. Achievable goals mean, if I play a tennis match, winning the match would be outside of my control, and therefore would not be an achievable goal. Why? Because I cannot control my opponent or the environment; for example how good of a player she is, or if the sun is in my face. Rather than focusing on winning the match, my goal should be to play at the best of my ability, whichis something I could certainly achieve. By setting achievable goals, we prevent ourselves from getting disappointed and as a consequence discouraged and frustrated. In Stoic philosophy achievable goals are also called internal goals, versus external goals something that I don’t have control over.</p>

<p>I hope you enjoy this book as much as I did and that your life will be more joyful and fulfilling.</p>

<h3 id="c-crash-course"><em><a href="https://amzn.to/35evA2J">C++ Crash Course</a></em></h3>
<p>After more than a decade of working with managed, high level languages, I needed to work on a cross platform project written in C++. I quickly discovered that it was hard to find a good reference on modern C++ without it being too overly complex or having to learn previous versions first. This book filled the gap that I had, and I would highly recommend it to any experienced programmer picking up C++ for the first time.</p>

<h3 id="flour-water-salt-yeast-the-fundamentals-of-artisan-bread-and-pizza"><em><a href="https://amzn.to/2Tee9Nj">Flour Water Salt Yeast: The Fundamentals of Artisan Bread and Pizza</a></em></h3>
<p>I give this book honorable mention because after reading it, I was able to consistently bake great tasting and looking bread. I love my carbs and a lot of times bread bought from the store does not satisfy me. If you’ve never baked bread, it is a great exercise where you can step out of your comfort zone and practice your beginner’s mind. It was also fun learning about the fundamentals of bread baking, with its different flower types, fermentation, and hydration.</p>

<p><img src="https://github.com/mercury2269/mercury2269.github.io/raw/master/uploads/2020/bread_pic.jpg" alt="bread picture" title="Bread picture" /></p>


										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: books</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2020/01/19/favorite-books-of-2019/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2020/01/19/favorite-books-of-2019/]]></guid>
		<pubDate>2020-01-19T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Best way to move AWS SQS messages between queues]]></title>
		<description>
			<![CDATA[
				<p>I’ve recently updated a tiny utility script (<a href="https://github.com/mercury2269/sqsmover">sqsmover</a>) that I wrote when I was learning Go Lang that moves AWS SQS messages between queues. After three years, it is still a userful tool when I need to move messages between queues. I feel like it could be useful to others who use SQS and deadletter queues because at one point something is going to fail and your messages will end up in the deadletter.</p>


				<p>I’ve recently updated a tiny utility script (<a href="https://github.com/mercury2269/sqsmover">sqsmover</a>) that I wrote when I was learning Go Lang that moves AWS SQS messages between queues. After three years, it is still a userful tool when I need to move messages between queues. I feel like it could be useful to others who use SQS and deadletter queues because at one point something is going to fail and your messages will end up in the deadletter.</p>

<p>In order to polish it, I’ve included the following features:</p>

<h3 id="help-menu">Help menu</h3>
<p><img src="https://github.com/mercury2269/mercury2269.github.io/raw/master/uploads/2018/sqsmover_help.png" alt="sqs mover help menu" title="SQS Mover help menu" /></p>

<h3 id="region-flag">Region flag</h3>
<p>Original version had region hardcoded in the code and needed a code change if you used a different region, oops. I’ve modified to allow region to be overwritten as a command line flag and default to <code class="language-plaintext highlighter-rouge">us-west-2</code>.</p>

<h3 id="fifo-queues-support">FIFO queues support</h3>
<p>When sending messages to FIFO queues MessageGroupId is a required field, and because it is not part of the message you have to explicitly copy it from the original message to the destination. Finally every message in the FIFO queue has a deduplication id. It’s either explicitly set by the caller or automatically hashed based on the message content. Because I want to support all FIFO queues, deduplication id is also copied when moving messages.</p>

<h3 id="installation">Installation</h3>
<p>Updated installation options with homebrew tap install <code class="language-plaintext highlighter-rouge">brew install mercury2269/homebrew-tap/sqsmover</code> for macOS, shell script for macOS, Linux, or OpenBSD. And compiled binary for Windows. No longer in order to install the app you have to have Go Lang installed locally and issue a <code class="language-plaintext highlighter-rouge">go get ...</code> command. This was pretty easy to do with awesome <a href="https://github.com/goreleaser/goreleaser">goreleaser</a> project and companion <a href="https://github.com/goreleaser/godownloader">godownloader</a>. GoReleaser automatically creates binary releases and publishes it to github while GoDownloader will create a bash script for one line installation.</p>

<h3 id="intuitive-error-messaging">Intuitive error messaging</h3>
<p>It sucked when your script fails and you don’t know what went wrong, so I’ve included a lot more user friendly error messages that should help users with figuring out what needs to be done.</p>

<p><img src="https://github.com/mercury2269/mercury2269.github.io/raw/master/uploads/2018/sqsmover_error.png" alt="error" title="SQS Mover errors" /></p>

<h3 id="progress-indicator">Progress indicator</h3>
<p>For the first version app I used to just output every message moved to the screen. This is not very useful if you have thousands of messages. A better user experience is to include a progress indicator.</p>

<p><img src="https://github.com/mercury2269/mercury2269.github.io/raw/master/uploads/2018/sqsmover_progress.gif" alt="progress indicator" title="SQS Mover progress indicator" /></p>

<h2 id="future-work">Future work</h2>
<p>At the moment the utility is using a batch download and upload which moves about 10 messages at a time. It’s pretty fast if you need to move few thousand of messages but if you have a million stuck in the deadletter queue I could imagine it could take a while. To speed up, I’m thinking to introduce multiple receiver and consumer threads and allow users to specify how many threads to use.</p>

<p>That’s it let me know if you come accross any issues using github, thanks!</p>


										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: amazon-sqs</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2018/11/19/moving-aws-sqs-messages-between-queues/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2018/11/19/moving-aws-sqs-messages-between-queues/]]></guid>
		<pubDate>2018-11-19T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Best Practices for Exceptions in Java]]></title>
		<description>
			<![CDATA[
				<blockquote>
  <p>When used to best advantage, exceptions can improve a program’s readability, reliability, and maintainability. When used improperly, they can have the opposite effect. - Joshua Block</p>
</blockquote>


				<blockquote>
  <p>When used to best advantage, exceptions can improve a program’s readability, reliability, and maintainability. When used improperly, they can have the opposite effect. - Joshua Block</p>
</blockquote>

<p>Most of this wisdom comes from Joshua Bloch’s <a href="https://amzn.to/2xamghn">Effective Java</a> book, see the book for the complete discussion on the exceptions.</p>

<h2 id="use-exceptions-only-for-exceptions-conditions">Use exceptions only for exceptions conditions</h2>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Horrible abuse of exceptions. Don't ever do this!</span>
<span class="k">try</span> <span class="o">{</span>
  <span class="kt">int</span> <span class="n">i</span> <span class="o">=</span> <span class="mi">0</span><span class="o">;</span>
  <span class="k">while</span><span class="o">(</span><span class="kc">true</span><span class="o">)</span>
    <span class="n">range</span><span class="o">[</span><span class="n">i</span><span class="o">++].</span><span class="na">climb</span><span class="o">();</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">ArrayIndexOutOfBoundsException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
	<span class="o">...</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Better idiom for looping through array is: <code class="language-plaintext highlighter-rouge">for (Mountain m : range) m.climb();</code></p>

<ul>
  <li>Because exceptions are designed for exceptional circumstances, there is little incentive for JVM implementors to make them fast as explicit tests.</li>
  <li>Placing code inside a try-catch block inhibits certain optimizations that modern JVM implementation might otherwise perform.</li>
  <li>Exception based idiom is much slower than state checking.</li>
</ul>

<p><strong>A well-designed API must not force its clients to use exceptions for ordinary control flow</strong></p>

<h2 id="throw-exceptions-appropriate-to-the-abstraction">Throw exceptions appropriate to the abstraction</h2>

<p>Problems when a method throwing an exception that has not apparent connection to the task it performs, usually propagates by lower level abstraction.</p>

<ul>
  <li>Pollutes API of the higher level with implementation details</li>
  <li>If implementation of the higher layer changes, the exceptions that it throws will change too, potentially breaking clients.</li>
</ul>

<p>Higher layers should catch lower-level exceptions and, in their place, throw exceptions that can be explained in terms of the higher-level abstraction. This idiom is know as exception translation.</p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Exception translation</span>
<span class="k">try</span> <span class="o">{</span>
   <span class="n">httpClient</span><span class="o">.</span><span class="na">execute</span><span class="o">(...)</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IOException</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
   <span class="kd">throws</span> <span class="nf">PspApiException</span><span class="o">(...);</span>
<span class="o">}</span>
</code></pre></div></div>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Exception chaining (special form of translation)</span>
<span class="k">try</span> <span class="o">{</span>
   <span class="n">httpClient</span><span class="o">.</span><span class="na">execute</span><span class="o">(...)</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">IOException</span> <span class="n">cause</span><span class="o">)</span> <span class="o">{</span>
   <span class="kd">throws</span> <span class="nf">PspApiException</span><span class="o">(</span><span class="n">cause</span><span class="o">);</span>
<span class="o">}</span>

<span class="kd">class</span> <span class="nc">PspApiException</span> <span class="kd">extends</span> <span class="nc">Exception</span> <span class="o">{</span>
   <span class="nc">PspApiException</span><span class="o">(</span><span class="nc">Throwable</span> <span class="n">cause</span><span class="o">)</span> <span class="o">{</span>
      <span class="kd">super</span><span class="o">(</span><span class="n">cause</span><span class="o">);</span>
   <span class="o">}</span>
<span class="o">}</span>
</code></pre></div></div>

<p><strong>While exception translation is superior to mindless propagation of exceptions from lower layers, it should not be overused.</strong></p>

<ul>
  <li>Use validate params</li>
  <li>Deal with exceptions on lower level</li>
</ul>

<h2 id="use-checked-exceptions-for-recoverable-conditions-and-runtime-exceptions-for-programming-errors">Use checked exceptions for recoverable conditions and runtime exceptions for programming errors.</h2>

<p>The cardinal rule in deciding whether to use a check or an unchecked exception is this: <strong>use checked exceptions for conditions from which the caller can reasonably be expected to recover.</strong></p>

<p><strong>Use runtime exceptions to indicate programming errors.</strong> Great majority is precondition violation, a failure of the client to adhere to the contract established by the API specification.</p>

<p>Because checked exceptions generally indicate recoverable conditions, it’s especially important for such exceptions to provide methods that furnish information that could help the caller to recover. For example, redemption of the card has failed because there is no money left, that information could be relayed back to player.</p>

<p><a href="https://stackoverflow.com/questions/27578/when-to-choose-checked-and-unchecked-exceptions/19061110#19061110">More on where to use checked vs unchecked.</a></p>

<h2 id="avoid-unnecessary-use-of-checked-exceptions">Avoid unnecessary use of checked exceptions</h2>

<p>Overuse of checked exceptions can make an API far less pleasant to use. Forces caller to handle the exception.</p>

<p>Burden is justified if the exceptional condition cannot be prevented by the proper use of the API and the programmer using the API can take some useful action once confronted with the exception. Unless both of these conditions hold, an unchecked exception is more appropriate.</p>

<h2 id="favor-the-use-of-standard-exceptions">Favor the use of standard exceptions</h2>

<p><code class="language-plaintext highlighter-rouge">IllegalArgumentException</code> (Non-null parameter value is inappropriate) <code class="language-plaintext highlighter-rouge">IllegalStateException</code> (Object state is inappropriate for method invocation) <code class="language-plaintext highlighter-rouge">NullPointerException</code> (Parameter value is null where prohibited) <code class="language-plaintext highlighter-rouge">IndexOutOfBoundsException</code>, <code class="language-plaintext highlighter-rouge">ConcurrentModificationException</code>, <code class="language-plaintext highlighter-rouge">UnsupportedOperationException</code></p>

<h2 id="document-all-exceptions-thrown-by-each-method">Document all exceptions thrown by each method</h2>

<p>To use a method properly you need to know about exceptions that it throws, therefore, it is critically important that you take the time to carefully document all of the exceptions thrown by each method.</p>

<p><strong>Always declare checked exceptions individually, and document precisely the conditions under which each one is thrown using the Javadoc @throws tag</strong></p>

<p>Unchecked exceptions represent programming errors so it is wise to document them so programmers get familiar with all the errors so they can avoid it.</p>

<p><strong>If an exception is thrown by many methods in a class for the same reason, it is acceptable to document the exception in the class’s documentation comment.</strong></p>

<h2 id="include-failure-capture-information-in-detail-messages">Include failure-capture information in detail messages</h2>

<p><strong>To capture the failure, the detail message of an exception should contain values of all parameter and fields that “contributed” to the exception.</strong></p>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">public</span> <span class="nf">IndexOutOfBoundsException</span><span class="o">(</span><span class="kt">int</span> <span class="n">lowerBound</span><span class="o">,</span> <span class="kt">int</span> <span class="n">upperBound</span><span class="o">,</span> <span class="kt">int</span> <span class="n">index</span><span class="o">)</span> <span class="o">{</span>
  <span class="c1">// Generate a detailed message that captures the failure</span>
  <span class="kd">super</span><span class="o">(</span><span class="s">"Lower bound: "</span> <span class="o">+</span> <span class="n">lowerBound</span> <span class="o">+</span> <span class="s">", Upper bound: "</span> <span class="o">+</span> <span class="n">upperBound</span> <span class="o">+</span> <span class="s">", Index: "</span> <span class="o">+</span> <span class="n">index</span><span class="o">);</span>

  <span class="c1">// Save failure information for programmatic access</span>
  <span class="k">this</span><span class="o">.</span><span class="na">lowerBound</span> <span class="o">=</span> <span class="n">lowerBound</span><span class="o">;</span>
  <span class="k">this</span><span class="o">.</span><span class="na">upperBound</span> <span class="o">=</span> <span class="n">upperBound</span><span class="o">;</span>
  <span class="k">this</span><span class="o">.</span><span class="na">index</span> <span class="o">=</span> <span class="n">index</span><span class="o">;</span>
<span class="o">}</span>
</code></pre></div></div>

<h2 id="dont-ignore-exceptions">Don’t ignore Exceptions</h2>

<p><strong>An empty catch block defeats the purpose of exception.</strong></p>

<h2 id="exceptions-code-smells">Exceptions code smells</h2>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">try</span> <span class="o">{</span>
   <span class="c1">// 100 lines of code</span>
  <span class="o">...</span>
<span class="o">}</span> <span class="k">catch</span> <span class="o">(</span><span class="nc">Exception</span> <span class="n">e</span><span class="o">)</span> <span class="o">{</span>
  <span class="c1">//Something failed.. not sure what or where, is it important or is it a bug, who knows ¯\_(ツ)_/¯</span>
<span class="o">}</span>
</code></pre></div></div>

<p>Ideally try catch around the line where exception is expected or a few lines to make the code more readable.</p>

<h2 id="catch-all-unhandled-exceptions-in-the-global-error-handler-and-log">Catch all unhandled exceptions in the global error handler and log</h2>

<p>Unhandled exceptions indicate programming errors, most likely the API was not used correctly and that’s a bug that could be fixed</p>

										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: java and exceptions</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2018/09/12/best-practices-for-exceptions-in-java/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2018/09/12/best-practices-for-exceptions-in-java/]]></guid>
		<pubDate>2018-09-12T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Expressjs Http Request Parsing with Log4js and Logstash]]></title>
		<description>
			<![CDATA[
				<p>I found it straight forward to configure expressjs to send http requests to logs and to setup log parsing. If you use log4js, there is a <a href="https://github.com/nomiddlename/log4js-node/wiki/Connect-Logger">connectlogger</a> that can capture expressjs/connect http requests. Finally, to make sense of logs I prefer to use ELK Stack with Logstash parsing the incoming logs, Elastic Search indexing, and Kibana for functional dashboards.</p>


				<p>I found it straight forward to configure expressjs to send http requests to logs and to setup log parsing. If you use log4js, there is a <a href="https://github.com/nomiddlename/log4js-node/wiki/Connect-Logger">connectlogger</a> that can capture expressjs/connect http requests. Finally, to make sense of logs I prefer to use ELK Stack with Logstash parsing the incoming logs, Elastic Search indexing, and Kibana for functional dashboards.</p>

<p>I always like to include the response times of http requests. It helps with troubleshooting performance issues down the line. Below is the slightly modified default format with response time appended to the end.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">httpLogFormat</span> <span class="o">=</span>
  <span class="dl">'</span><span class="s1">:remote-addr - - [:date] ":method :url </span><span class="dl">'</span> <span class="o">+</span>
  <span class="dl">'</span><span class="s1">HTTP/:http-version" :status :res[content-length] </span><span class="dl">'</span> <span class="o">+</span>
  <span class="dl">'</span><span class="s1">":referrer" ":user-agent" :response-time</span><span class="dl">'</span><span class="p">;</span>
<span class="nx">app</span><span class="p">.</span><span class="nx">use</span><span class="p">(</span>
  <span class="nx">log4js</span><span class="p">.</span><span class="nx">connectLogger</span><span class="p">(</span><span class="nx">log4js</span><span class="p">.</span><span class="nx">getLogger</span><span class="p">(</span><span class="dl">"</span><span class="s2">http</span><span class="dl">"</span><span class="p">),</span> <span class="p">{</span>
    <span class="na">level</span><span class="p">:</span> <span class="dl">"</span><span class="s2">auto</span><span class="dl">"</span><span class="p">,</span>
    <span class="na">format</span><span class="p">:</span> <span class="nx">httpLogFormat</span><span class="p">,</span>
  <span class="p">})</span>
<span class="p">);</span>
</code></pre></div></div>

<p>Example log output: <code class="language-plaintext highlighter-rouge">10.201.44.200 - - [Tue, 29 Sep 2015 04:52:53 GMT] "GET / HTTP/1.1" 302 66 "" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36" 2</code></p>

<h3 id="logstash-log4js-appender">Logstash Log4js appender</h3>

<p>Using <a href="https://github.com/gembly/log4js-logstash">log4js-logstash</a> appender, I specify the following in the log4js config.</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"appenders"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
    </span><span class="p">{</span><span class="w">
      </span><span class="nl">"type"</span><span class="p">:</span><span class="w"> </span><span class="s2">"log4js-logstash"</span><span class="p">,</span><span class="w">
      </span><span class="nl">"host"</span><span class="p">:</span><span class="w"> </span><span class="s2">"10.0.0.10"</span><span class="p">,</span><span class="w">
      </span><span class="nl">"port"</span><span class="p">:</span><span class="w"> </span><span class="mi">5959</span><span class="p">,</span><span class="w">
      </span><span class="nl">"fields"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
        </span><span class="nl">"app"</span><span class="p">:</span><span class="w"> </span><span class="s2">"my-app"</span><span class="p">,</span><span class="w">
        </span><span class="nl">"env"</span><span class="p">:</span><span class="w"> </span><span class="s2">"dev"</span><span class="w">
      </span><span class="p">}</span><span class="w">
    </span><span class="p">}</span><span class="w">
  </span><span class="p">],</span><span class="w">
  </span><span class="nl">"replaceConsole"</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>Fields are nice to have if you want to tag your logs with application name or environment, so you can tell where the logs are coming from.</p>

<h3 id="logstash-parsing">Logstash parsing</h3>

<p>In order to parse our custom log we need create a logstash pattern, and place it into the <code class="language-plaintext highlighter-rouge">/etc/logstash/patterns</code> folder.</p>

<p>Here is the pattern for parsing the log format above: <code class="language-plaintext highlighter-rouge">EXPRESSHTTP %{IP:clientip} - - \[%{DATA:timestamp}\] \"%{WORD:verb} %{URIPATHPARAM:request} HTTP/%{NUMBER:httpversion}\" %{NUMBER:response} (?:%{NUMBER:bytes}|undefined) \"%{URI:referrer}?\" \"%{DATA:agent}\" %{NUMBER:response_time}</code></p>

<h3 id="logstash-input-and-filter">Logstash input and filter</h3>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="w">    </span><span class="err">input</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="err">tcp</span><span class="w"> </span><span class="p">{</span><span class="w">
    	</span><span class="err">codec</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="s2">"json"</span><span class="w">
    	</span><span class="err">port</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="mi">5959</span><span class="w">
    	</span><span class="err">type</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="s2">"my-app"</span><span class="w">
      </span><span class="p">}</span><span class="w">
    </span><span class="p">}</span><span class="w">
    </span><span class="err">filter</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="err">if</span><span class="w"> </span><span class="p">[</span><span class="err">type</span><span class="p">]</span><span class="w"> </span><span class="err">==</span><span class="w"> </span><span class="s2">"my-app"</span><span class="w"> </span><span class="p">{</span><span class="w">
    	</span><span class="err">mutate</span><span class="w"> </span><span class="p">{</span><span class="w">
    	  </span><span class="err">rename</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="s2">"[@fields][app]"</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="s2">"app"</span><span class="w"> </span><span class="p">}</span><span class="w">
    	  </span><span class="err">rename</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="s2">"[@fields][category]"</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="s2">"category"</span><span class="w"> </span><span class="p">}</span><span class="w">
    	  </span><span class="err">rename</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="s2">"[@fields][env]"</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="s2">"env"</span><span class="w"> </span><span class="p">}</span><span class="w">
    	  </span><span class="err">rename</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="s2">"[@fields][level]"</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="s2">"priority"</span><span class="w"> </span><span class="p">}</span><span class="w">
    	  </span><span class="err">rename</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="s2">"category"</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="s2">"logger_name"</span><span class="w"> </span><span class="p">}</span><span class="w">
    	  </span><span class="err">rename</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="s2">"@message"</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="s2">"message"</span><span class="w"> </span><span class="p">}</span><span class="w">
    	</span><span class="p">}</span><span class="w">
      </span><span class="p">}</span><span class="w">
      </span><span class="err">if</span><span class="w"> </span><span class="p">[</span><span class="err">type</span><span class="p">]</span><span class="w"> </span><span class="err">==</span><span class="w"> </span><span class="s2">"my-app"</span><span class="w"> </span><span class="err">and</span><span class="w"> </span><span class="p">[</span><span class="err">logger_name</span><span class="p">]</span><span class="w"> </span><span class="err">==</span><span class="w"> </span><span class="s2">"http"</span><span class="w"> </span><span class="p">{</span><span class="w">
    	</span><span class="err">grok</span><span class="w"> </span><span class="p">{</span><span class="w">
    	  </span><span class="err">patterns_dir</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="s2">"/etc/logstash/patterns"</span><span class="w">
    	  </span><span class="err">match</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="s2">"message"</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="s2">"%{EXPRESSHTTP}"</span><span class="w"> </span><span class="p">}</span><span class="w">
    	  </span><span class="err">add_field</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="p">[</span><span class="s2">"received_at"</span><span class="p">,</span><span class="w"> </span><span class="s2">"%{@timestamp}"</span><span class="p">]</span><span class="w">
    	  </span><span class="err">remove_field</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="p">[</span><span class="s2">"message"</span><span class="p">]</span><span class="w">
    	</span><span class="p">}</span><span class="w">
    	</span><span class="err">date</span><span class="w"> </span><span class="p">{</span><span class="w">
    	  </span><span class="err">match</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="p">[</span><span class="s2">"timestamp"</span><span class="p">,</span><span class="w"> </span><span class="s2">"EEE, dd MMM YYYY HH:mm:ss zzz"</span><span class="p">]</span><span class="w">
    	  </span><span class="err">remove_field</span><span class="w"> </span><span class="err">=&gt;</span><span class="w"> </span><span class="s2">"timestamp"</span><span class="w">
    	</span><span class="p">}</span><span class="w">
      </span><span class="p">}</span><span class="w">
    </span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>In the above config, I perform a number of renames on the nested fields so it can have short and clear names. And in the final if clause, I checks if the logger_name is marked with “http” and then perform a grok parsing of the logs. It’s also good to add received time and then parse the actual log time as in the above date filter.</p>

						
				
					<p>Tagged with: logstash</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/2015/10/01/log4js-http-request-parsing-with-logstash/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/2015/10/01/log4js-http-request-parsing-with-logstash/]]></guid>
		<pubDate>2015-10-01T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[7 Reasons to Hire a Coach]]></title>
		<description>
			<![CDATA[
				<p>I’m a big believer in continuous improvement and personal growth. But how do you know if you are actually making progress in your life and becoming better? Are you moving towards your goals or are you full of self-delusion that keeps you at bay?</p>


				<p>I’m a big believer in continuous improvement and personal growth. But how do you know if you are actually making progress in your life and becoming better? Are you moving towards your goals or are you full of self-delusion that keeps you at bay?</p>

<p>I can tell you from personal experience, that we can be dishonest with ourselves. It may seem like you are actually moving forward by reading books, talking to your friends about your goals, and making up strange tasks that you need to do before you actually do what you need to do. You might tell yourself, I “If I knew this or that, or had this amazing experience, then I would be ready and able to do it. But there is never going to be a perfect moment! It’s always going to be a moving target and we need to start acting toward, and working on, our goals.
Bottom line – we need more doing, something that will actually move us towards the goal.</p>

<p>We need to make mistakes in order to learn. But we cannot fail by being safe and not putting ourselves out there. Hence we grow by doing and learning from being foolish.</p>

<p>At this moment I feel like I need to make mistakes and learn from them. I want to challenge myself and accomplish my goals. That is why I’ve decided to try personal coaching. Here are a few things that a good coach should be able to help you with:</p>

<h3 id="outside-opinion">Outside Opinion</h3>
<p>Your coach is not your friend, she doesn’t know who you are and she is not going to accept  your excuses or be nice to you. She will only look at the results that are being produced rather than excuses, and keep you accountable. In addition, she can provide an unbiased opinion about how honest you are being with yourself.</p>

<h3 id="keep-you-accountable">Keep you accountable</h3>
<p>It’s one thing to make a promise to yourself that you are not going to keep, but making a commitment about your goals to another person who you respect, will make you work harder.</p>

<h3 id="your-best-interests">Your best interests</h3>
<p>Your coach’s motivation is to help you succeed with your goals. Her interests are aligned with your best interests. She is there to support you and move you along the path to your goals. We all want the best for ourselves, but we are also very easy on ourselves at times, which does not produce results.</p>

<h3 id="work-out-psychological-issues">Work out psychological issues</h3>
<p>A lot of times the problems that we experience are only in our heads, and fear of failure stops us before we can continue to grow. An experienced coach should be very good at helping you to work out those issues.</p>

<h3 id="deliberate-practice">Deliberate practice</h3>
<p>Just like in sports, a coach will make you do drills that will help you when it’s show time. In addition, she will help you measure your performance.</p>

<h3 id="getting-clear-on-your-goals">Getting clear on your goals</h3>
<p>Starting from the end result, a coach should be able to help you work out what  the most important thing in your life is. Are you chasing someone else’s dreams, or is this something you truly want for yourself?</p>

<h3 id="enjoy-your-life-now">Enjoy your life now</h3>
<p>Goals are great, but if you are not enjoying what you are doing, what is the point of living? A coach can, at times, also remind you to have fun and live in the present if she notices that you are getting burned out.</p>

<p>I’m looking forward to working with a coach and putting myself in a higher gear on the road of greater fulfillment and personal growth.</p>

										
					<p>Posted in: blog</p>
						
				
					<p>Tagged with: better-programmer</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/blog/2015/04/12/getting-a-coach-and-keeping-yourself-honest/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/blog/2015/04/12/getting-a-coach-and-keeping-yourself-honest/]]></guid>
		<pubDate>2015-04-12T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[How to Estimate Software]]></title>
		<description>
			<![CDATA[
				<p>One of the first questions non-technical entrepreneurs who have an idea ask me is,   “How much would it cost me to build an application and how soon can you build it?” And for someone, who is not familiar with software development, it could be very difficult and even frustrating to get a realistic estimate with a timeframe. You might be surprised to learn that <strong>a lot of  developers and  managers don’t understand how to estimate software</strong> either!  I’ve personally been a part of large scale development efforts, with ballpark estimates, coming from management, where projects never met the deadlines  and were delivered way over budget.  Hopefully after reading this post you will have a better understanding of what it takes to get a good estimate.</p>

<h3 id="software-estimation-story">Software Estimation Story</h3>
<p>Building software is much like building a house. Imagine you want to build a house and have a friend who is an architect, so you ask him if it’s possible to build a three bedroom house for around $100,000. He thinks about it and says yes, but it depends on the type of  house and what’s going to be in it. In your friend’s mind he imagines a simple house, with no thrills, that he could design and build for that amount. But you might have some other ideas. You want to have a nice swimming pool, a playground, a three car garage, bamboo floors, granite everywhere, a sauna, gold plated mirrors, high ceilings, and etc. You also might want a house on a hill with a view. At this point the house might cost ten  times the original amount.</p>

<p>There may also be many times during the project when you forgot to mention or thought of some other important feature, like an entertainment room, that you feel you must have! But your friend has already started working on the house and built the frame. And you might have to redo the entire design and knock down walls to accommodate, it which will make the project off budget, and add a lot of additional time.</p>

<p>It’s not always necessary to know everything up front, but it is important to anticipate large features so that your friend can design a plan that will accommodate changes later.</p>

<p>Steve McConnel, in his great book “<a href="http://www.amazon.com/gp/product/1556159005/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1556159005&amp;linkCode=as2&amp;tag=sermassblo-20&amp;linkId=W44AZRHKZEOBSTMU">Rapid Development</a>”, gives a great summary of the software estimation story that all customers and managers must understand:</p>

<blockquote>
  <p>The basic software-estimation story is that software development is a process of gradual refinement. You begin with a fuzzy picture of what you want to build and then spend the rest of the project trying to bring that picture into clearer focus. Because the picture of the software you are trying to build is fuzzy, the estimate of the time and effort needed to build it is fuzzy, too. The estimate can come into focus only along with the software itself, which means that software-project estimation is also a process of gradual refinement.</p>
</blockquote>

<p>In other words, <strong>it’s impossible for a programmer to estimate the project until he has a detailed understanding of what the customer wants</strong>. Until a specific feature is understood in detail, the rough estimate could be a factor of sixteen  differences for that feature.</p>

<p>Another difficult part is that unless you’ve previously built the same house, you probably won’t have all the details, hence you have a fuzzy picture. Software development is a process of discovery and gradual refinement. Developers work with customers to unearth intricate business rules, features, and capabilities. One way you can bring a picture into the focus is by going through the process of defining a product, thinking through the requirements, and creating a design. Let’s go through what we need to have to better understand what we are trying to build.</p>

<h3 id="defining-a-product">Defining a product</h3>
<p>Detailed understanding means that a developer can take the product definition and create a model of it in code. Most likely a developer is not a domain expert of the business and he needs a lot of help from the customer to understand it. Imagine that you get a job at an unfamiliar organization, where you had to learn how the business works before you can be productive. You will need a lot of time to get up to speed, and so will a developer in order to build your product. It’s also much cheaper to be make mistakes and have invalid assumptions at this stage, because no code is written and it doesn’t cost anything to correct it.</p>

<p>For the product owner at this stage, a  good place to start  is to define a clear problem/solution statement, along with user stories, tasks, and <a href="http://www.boost.co.nz/blog/2012/01/use-cases-or-user-stories/">use cases</a>. User stories is a simple description of a feature told in the following way:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>As a &lt;type of user&gt;, I want &lt;some goal&gt; so that &lt;some reason&gt;.
</code></pre></div></div>

<p>For example, it may look like this: As an incentive compensation specialist I would be able to set up compensation wrappers so that I can create goals for payees. Does this story make a lot of sense to you? If you are not working in the incentive compensation business, I don’t think it will. Stories like these are an invitation for conversations between developer and business experts. During the conversation the developer will identify terms used, a vocabulary for that business domain, and know <a href="http://martinfowler.com/bliki/UbiquitousLanguage.html">ubiquitous language</a> in <a href="http://en.wikipedia.org/wiki/Domain-driven_design">Domain Driven Design</a>. It will also lead to a  better understanding of a product, elements, subsystems and entities.</p>

<p>At this stage any additional information that a business expert can present would be helpful. Examples are screenshots of similar application, high level flowcharts, wireframes, onboarding manuals,  etc. A developer can write a documentation summary about the problem/solution domain identifying all the entities, business vocabularies, definitions, subsystems, interactions and actors.</p>

<h3 id="requirements-specification">Requirements Specification</h3>
<p>After defining the product and learning about the business, we can see a better picture, but it’s still not perfect;  at this moment there could be a factor of eight  differences between the high and low estimate. The  next step is to zoom in even closer and define a list of requirements. The amount of features  software can have has a tremendous impact on the design, time, and cost of the application. Even if you practice agile methodologies, you still need to gather a minimal set of requirements so you can  plan for the future. Just like in the definition stage,  it’s much easier, and cheaper, to make changes during requirements rather than realizing you’ve missed an important feature down the line, and have it take months to redesign the application. (Knock down walls).</p>

<p>Input at this stage from the business side should be a list of important features that this project must have. While a developer’s job is to understand how these features fit together and to create a plan that will accommodate future expansions.</p>

<h3 id="product-design">Product Design</h3>
<p>We are getting much closer to a better estimate at this point; the difference might be a factor of three  between high and low estimates. Over my career I’ve learned that nothing brings software into a picture like creating a high level and detailed design. This is the stage where a developer takes everything learned about the product, and starts modeling the domain. During this stage she will make a lot of mistakes and flush out incorrect assumptions. Again, much cheaper to make mistakes here than during coding. Starting with a high level design of the major subsystems and defining a clear communication between them, then modeling your domain and define major objects and abstractions. (For a more detailed analysis on how to model a domain, see Eric Evan’s book, “<a href="http://www.amazon.com/gp/product/0321125215/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0321125215&amp;linkCode=as2&amp;tag=sermassblo-20&amp;linkId=QVOCKKAXHGSP2WOC">Domain Driven Design</a>”).</p>

<h3 id="what-if-i-dont-know-what-i-want">What if I don’t know what I want?</h3>
<p>I think the best way to approach this problem is to hire a User Experience (UX) designer who can take vague ideas and  create throw away sketches of the product. Each sketch  can then be reviewed, refined, or redrawn. This process will flush out the requirements that will crystalize in an initial prototype, and can be tested on users before you start the expensive software development. A good UX designer in this situation will save you a lot of money because she will bring the requirements and prototype into focus, for the fraction of the cost of building software!  By sketching, creating multiple prototypes, and then testing it on users, you know exactly what works and there is no chance of building something that your customers can’t use.</p>

<p>I see a tremendous amount of benefit of hiring a UX designer early in any software project. There is a lot of power in sketching, defining, and user testing multiple prototypes without actually building anything. It’s costly to experiment by building software and I don’t think anyone can get the user experience right the first time.</p>

<h3 id="getting-an-estimate">Getting an estimate</h3>

<p>After the picture is more clear, a developer will create a list of low level details with a range estimate for how many man-hours it would take to complete each task. You must get estimates on low levels of details, this way you get a more accurate estimate and you can gauge how the project is progressing. A good developer will also provide additional information about the costs that are associated with each task and other alternatives that could be more cost effective. Like a good contractor who would present and educate you about different counter tops, their benefits, and costs, you want your developer to do the same for you when providing a list of estimates.</p>

<p>It’s also very important not to overlook other important tasks that are not coding, but have a significant impact on schedule and budget, like QA, documentation, deployments, setting up dev/production servers/databases, configuration, integration, holidays, training, and sick days. In addition there should be allowance with working with new languages, working with unfamiliar technologies, and frameworks. There is always a learning curve when  doing something new and this should be accounted for.</p>

<p>Make estimation part of your plan
Estimation  should be part of your plan and you need to spend a significant amount of time on it; don’t rush it.</p>

<h3 id="word-on-agile-software-development">Word on Agile Software Development</h3>
<p>I am a big believer in iterative development, rapid delivery, minimal planning, and many other principles Agile Manifesto stands for. Unfortunately, I’ve noticed some developers use Agile as an excuse to have no planning, design, or requirements analysis at all, which results in the costliest approach of them all: code-like-hell. It’s common, and <strong>you want to be wary of ballpark estimates with use of an Agile as an excuse to not do to any planning or design</strong>.</p>

				<p>One of the first questions non-technical entrepreneurs who have an idea ask me is,   “How much would it cost me to build an application and how soon can you build it?” And for someone, who is not familiar with software development, it could be very difficult and even frustrating to get a realistic estimate with a timeframe. You might be surprised to learn that <strong>a lot of  developers and  managers don’t understand how to estimate software</strong> either!  I’ve personally been a part of large scale development efforts, with ballpark estimates, coming from management, where projects never met the deadlines  and were delivered way over budget.  Hopefully after reading this post you will have a better understanding of what it takes to get a good estimate.</p>

<h3 id="software-estimation-story">Software Estimation Story</h3>
<p>Building software is much like building a house. Imagine you want to build a house and have a friend who is an architect, so you ask him if it’s possible to build a three bedroom house for around $100,000. He thinks about it and says yes, but it depends on the type of  house and what’s going to be in it. In your friend’s mind he imagines a simple house, with no thrills, that he could design and build for that amount. But you might have some other ideas. You want to have a nice swimming pool, a playground, a three car garage, bamboo floors, granite everywhere, a sauna, gold plated mirrors, high ceilings, and etc. You also might want a house on a hill with a view. At this point the house might cost ten  times the original amount.</p>

<p>There may also be many times during the project when you forgot to mention or thought of some other important feature, like an entertainment room, that you feel you must have! But your friend has already started working on the house and built the frame. And you might have to redo the entire design and knock down walls to accommodate, it which will make the project off budget, and add a lot of additional time.</p>

<p>It’s not always necessary to know everything up front, but it is important to anticipate large features so that your friend can design a plan that will accommodate changes later.</p>

<p>Steve McConnel, in his great book “<a href="http://www.amazon.com/gp/product/1556159005/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1556159005&amp;linkCode=as2&amp;tag=sermassblo-20&amp;linkId=W44AZRHKZEOBSTMU">Rapid Development</a>”, gives a great summary of the software estimation story that all customers and managers must understand:</p>

<blockquote>
  <p>The basic software-estimation story is that software development is a process of gradual refinement. You begin with a fuzzy picture of what you want to build and then spend the rest of the project trying to bring that picture into clearer focus. Because the picture of the software you are trying to build is fuzzy, the estimate of the time and effort needed to build it is fuzzy, too. The estimate can come into focus only along with the software itself, which means that software-project estimation is also a process of gradual refinement.</p>
</blockquote>

<p>In other words, <strong>it’s impossible for a programmer to estimate the project until he has a detailed understanding of what the customer wants</strong>. Until a specific feature is understood in detail, the rough estimate could be a factor of sixteen  differences for that feature.</p>

<p>Another difficult part is that unless you’ve previously built the same house, you probably won’t have all the details, hence you have a fuzzy picture. Software development is a process of discovery and gradual refinement. Developers work with customers to unearth intricate business rules, features, and capabilities. One way you can bring a picture into the focus is by going through the process of defining a product, thinking through the requirements, and creating a design. Let’s go through what we need to have to better understand what we are trying to build.</p>

<h3 id="defining-a-product">Defining a product</h3>
<p>Detailed understanding means that a developer can take the product definition and create a model of it in code. Most likely a developer is not a domain expert of the business and he needs a lot of help from the customer to understand it. Imagine that you get a job at an unfamiliar organization, where you had to learn how the business works before you can be productive. You will need a lot of time to get up to speed, and so will a developer in order to build your product. It’s also much cheaper to be make mistakes and have invalid assumptions at this stage, because no code is written and it doesn’t cost anything to correct it.</p>

<p>For the product owner at this stage, a  good place to start  is to define a clear problem/solution statement, along with user stories, tasks, and <a href="http://www.boost.co.nz/blog/2012/01/use-cases-or-user-stories/">use cases</a>. User stories is a simple description of a feature told in the following way:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>As a &lt;type of user&gt;, I want &lt;some goal&gt; so that &lt;some reason&gt;.
</code></pre></div></div>

<p>For example, it may look like this: As an incentive compensation specialist I would be able to set up compensation wrappers so that I can create goals for payees. Does this story make a lot of sense to you? If you are not working in the incentive compensation business, I don’t think it will. Stories like these are an invitation for conversations between developer and business experts. During the conversation the developer will identify terms used, a vocabulary for that business domain, and know <a href="http://martinfowler.com/bliki/UbiquitousLanguage.html">ubiquitous language</a> in <a href="http://en.wikipedia.org/wiki/Domain-driven_design">Domain Driven Design</a>. It will also lead to a  better understanding of a product, elements, subsystems and entities.</p>

<p>At this stage any additional information that a business expert can present would be helpful. Examples are screenshots of similar application, high level flowcharts, wireframes, onboarding manuals,  etc. A developer can write a documentation summary about the problem/solution domain identifying all the entities, business vocabularies, definitions, subsystems, interactions and actors.</p>

<h3 id="requirements-specification">Requirements Specification</h3>
<p>After defining the product and learning about the business, we can see a better picture, but it’s still not perfect;  at this moment there could be a factor of eight  differences between the high and low estimate. The  next step is to zoom in even closer and define a list of requirements. The amount of features  software can have has a tremendous impact on the design, time, and cost of the application. Even if you practice agile methodologies, you still need to gather a minimal set of requirements so you can  plan for the future. Just like in the definition stage,  it’s much easier, and cheaper, to make changes during requirements rather than realizing you’ve missed an important feature down the line, and have it take months to redesign the application. (Knock down walls).</p>

<p>Input at this stage from the business side should be a list of important features that this project must have. While a developer’s job is to understand how these features fit together and to create a plan that will accommodate future expansions.</p>

<h3 id="product-design">Product Design</h3>
<p>We are getting much closer to a better estimate at this point; the difference might be a factor of three  between high and low estimates. Over my career I’ve learned that nothing brings software into a picture like creating a high level and detailed design. This is the stage where a developer takes everything learned about the product, and starts modeling the domain. During this stage she will make a lot of mistakes and flush out incorrect assumptions. Again, much cheaper to make mistakes here than during coding. Starting with a high level design of the major subsystems and defining a clear communication between them, then modeling your domain and define major objects and abstractions. (For a more detailed analysis on how to model a domain, see Eric Evan’s book, “<a href="http://www.amazon.com/gp/product/0321125215/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0321125215&amp;linkCode=as2&amp;tag=sermassblo-20&amp;linkId=QVOCKKAXHGSP2WOC">Domain Driven Design</a>”).</p>

<h3 id="what-if-i-dont-know-what-i-want">What if I don’t know what I want?</h3>
<p>I think the best way to approach this problem is to hire a User Experience (UX) designer who can take vague ideas and  create throw away sketches of the product. Each sketch  can then be reviewed, refined, or redrawn. This process will flush out the requirements that will crystalize in an initial prototype, and can be tested on users before you start the expensive software development. A good UX designer in this situation will save you a lot of money because she will bring the requirements and prototype into focus, for the fraction of the cost of building software!  By sketching, creating multiple prototypes, and then testing it on users, you know exactly what works and there is no chance of building something that your customers can’t use.</p>

<p>I see a tremendous amount of benefit of hiring a UX designer early in any software project. There is a lot of power in sketching, defining, and user testing multiple prototypes without actually building anything. It’s costly to experiment by building software and I don’t think anyone can get the user experience right the first time.</p>

<h3 id="getting-an-estimate">Getting an estimate</h3>

<p>After the picture is more clear, a developer will create a list of low level details with a range estimate for how many man-hours it would take to complete each task. You must get estimates on low levels of details, this way you get a more accurate estimate and you can gauge how the project is progressing. A good developer will also provide additional information about the costs that are associated with each task and other alternatives that could be more cost effective. Like a good contractor who would present and educate you about different counter tops, their benefits, and costs, you want your developer to do the same for you when providing a list of estimates.</p>

<p>It’s also very important not to overlook other important tasks that are not coding, but have a significant impact on schedule and budget, like QA, documentation, deployments, setting up dev/production servers/databases, configuration, integration, holidays, training, and sick days. In addition there should be allowance with working with new languages, working with unfamiliar technologies, and frameworks. There is always a learning curve when  doing something new and this should be accounted for.</p>

<p>Make estimation part of your plan
Estimation  should be part of your plan and you need to spend a significant amount of time on it; don’t rush it.</p>

<h3 id="word-on-agile-software-development">Word on Agile Software Development</h3>
<p>I am a big believer in iterative development, rapid delivery, minimal planning, and many other principles Agile Manifesto stands for. Unfortunately, I’ve noticed some developers use Agile as an excuse to have no planning, design, or requirements analysis at all, which results in the costliest approach of them all: code-like-hell. It’s common, and <strong>you want to be wary of ballpark estimates with use of an Agile as an excuse to not do to any planning or design</strong>.</p>

										
					<p>Posted in: development practice</p>
						
				
					<p>Tagged with: estimation</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/development%20practice/2014/12/29/how-to-estimate-software/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/development%20practice/2014/12/29/how-to-estimate-software/]]></guid>
		<pubDate>2014-12-29T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Amazon SQS Message Processor]]></title>
		<description>
			<![CDATA[
				<p>There are mission critical pieces in any business application that might call external services via some sort of an external API over the local network or Internet. The problem with delivering messages over the network is that networks sometime have a tendency to drop messages and cause timeouts. There is a <a href="http://aphyr.com/posts/288-the-network-is-reliable">great paper</a> on Kyle Kingsbury’s blog where him and <a href="https://twitter.com/pbailis/">Peter Bailis</a> provide a list of evidence that failures can happen in many levels of the network or operation system. And it’s not only network that can fail, the receiving 3rd party applications might also be down, under load and slow to respond.</p>


				<p>There are mission critical pieces in any business application that might call external services via some sort of an external API over the local network or Internet. The problem with delivering messages over the network is that networks sometime have a tendency to drop messages and cause timeouts. There is a <a href="http://aphyr.com/posts/288-the-network-is-reliable">great paper</a> on Kyle Kingsbury’s blog where him and <a href="https://twitter.com/pbailis/">Peter Bailis</a> provide a list of evidence that failures can happen in many levels of the network or operation system. And it’s not only network that can fail, the receiving 3rd party applications might also be down, under load and slow to respond.</p>

<blockquote>
  <p>Processes, servers, NICs, switches, local and wide area networks can all fail, and the resulting economic consequences are real. … The consequences of these outages range from increased latency and temporary unavailability to inconsistency, corruption, and data loss.</p>
</blockquote>

<p>Therefore, if we want to have a reliable communication with external services we need to implement some kind of a retry mechanism that can redeliver messages and recover from faults.</p>

<h3 id="solving-guaranteed-delivery">Solving Guaranteed Delivery</h3>

<p>Message Queue is one of the solutions that can address this problem and guarantee delivery. Rather than calling an external API within the application process, like a web request, you place a message into the reliable and durable message queue that guarantees that your message will be delivered to the consumer at least once. Since putting a message on the queue is usually a fast operation, it also speeds up your application performance. Most message queues guarantee delivery by providing some sort of a mechanism of acknowledging if message has been received by the consumer. And if consumer doesn’t respond after a period of time the message gets returned into the queue so it can get processed again. This basically guarantees that a message will get delivered or retried for a certain pre-configured number of times.</p>

<p>There are numerous <a href="http://queues.io/">alternative</a> Message Queue solutions with each addressing certain problems in it’s own way. Since the main specification for calling critical services is guaranteed delivery and we are not building something like a high throughput trading application, the Amazon SQS provides the best alternative to the self-hosted MQs. One of the benefits is that you don’t have to administer message queue servers and spend a lot of time figuring out how to setup redundant clusters for reliability and worry about network partitions. Of course you loose on speed of placing a message into the queue. But a 20ms average put call to SQS is also good enough for this problem.</p>

<p>Until you figure out if you actually need something faster and spend all the time to learn and setting up the MQ cluster, I think Amazon SQS provides the best bang for your time. It’s easy to understand, has a great SDK and it’s ready to go. It’s also not very expensive. A million calls costs $1. Yes you do have to poll the queue, but you can also use the <a href="http://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-long-polling.html">long polling</a> and that will reduce the number of calls of one consumer to 1 call every 20 seconds (if no activity), which is about 120k calls per month, or about 12 cents.</p>

<p>Putting a message into the queue is <a href="http://docs.aws.amazon.com/AWSSdkDocsNET/latest/DeveloperGuide/send-sqs-message.html">trivial</a> and doesn’t need more explanation. What is not trivial is creating a reliable application with workers to process the messages. We also want the ability to start multiple workers so they can process messages from the queue in parallel rather than one at a time. Since many workers can be started on one node and run in parallel we need our service efficiently use the CPU resources meaning not blocking threads while waiting for I/O.</p>

<p>I wasn’t able to find an open source application that can always listen to the queue and process messages as they come in. So I needed to write my own. A good candidate for this task is a Win32 Service, since it provides a platform for always running service that can also self restart itself on fault and boot up with windows automatically.</p>

<h3 id="creating-message-processor-win32-service">Creating Message Processor Win32 Service</h3>

<p>The windows service must always be running, meaning that each worker will have a main while loop that will continue indefinitely. Also you need to start multiple workers so you have to use some sort of multi threaded solution.
My initial version was to new up multiple Threads that invoke an asynchronous method. Like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">protected</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">OnStart</span><span class="p">(</span><span class="kt">string</span><span class="p">[]</span> <span class="n">args</span><span class="p">)</span>
<span class="p">{</span>
      <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">_workers</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span>
    <span class="p">{</span>
      <span class="k">new</span> <span class="nf">Thread</span><span class="p">(</span><span class="n">RunWorker</span><span class="p">).</span><span class="nf">Start</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">public</span> <span class="k">async</span> <span class="k">void</span> <span class="nf">RunWorker</span><span class="p">()</span>
<span class="p">{</span>
  <span class="k">while</span><span class="p">(</span><span class="k">true</span><span class="p">)</span>
  <span class="p">{</span>
    <span class="c1">// .. get message from amazon sqs sync.. about 20ms</span>
    <span class="kt">var</span> <span class="n">message</span> <span class="p">=</span> <span class="n">sqsClient</span><span class="p">.</span><span class="nf">ReceiveMessage</span><span class="p">();</span>

    <span class="k">try</span>
    <span class="p">{</span>
        <span class="k">await</span> <span class="nf">PerformWebRequestAsync</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
        <span class="k">await</span> <span class="nf">InsertIntoDbAsync</span><span class="p">(</span><span class="n">message</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">catch</span><span class="p">(</span><span class="n">SomeExeception</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">// ... log</span>
        <span class="c1">//continue to retry</span>
        <span class="k">continue</span><span class="p">;</span>
    <span class="p">}</span>
    <span class="n">sqsClient</span><span class="p">.</span><span class="nf">DeleteMessage</span><span class="p">();</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And it was working fine, however there is a problem with this code. The initial threads that were created would exit once the first execution of the method would hit first await. So there was really no point of creating those threads. In addition, I wasn’t passing a cancellation token to threads so I could not signal it to shut down whenever I wanted to gracefully exit the service. Thanks to <a href="http://nozillium.com/">Andrew Nosenko</a> who pointed out <a href="http://stackoverflow.com/questions/25001764/always-running-threads-on-windows-service#answer-25009215">a better and cleaner way</a> of accomplishing the same goal using tasks.</p>

<p>Rather than starting threads manually you start each task and add it to the List<Task> collection. This way the threadpool is efficiently managing your threadpool threads and schedules it according to the system resources.</Task></p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">List</span><span class="p">&lt;</span><span class="n">Task</span><span class="p">&gt;</span> <span class="n">_workers</span> <span class="p">=</span> <span class="k">new</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">Task</span><span class="p">&gt;();</span>
<span class="n">CancellationTokenSource</span> <span class="n">_cts</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">CancellationTokenSource</span><span class="p">();</span>

<span class="k">protected</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">OnStart</span><span class="p">(</span><span class="kt">string</span><span class="p">[]</span> <span class="n">args</span><span class="p">)</span>
<span class="p">{</span>
  <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">_workers</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span>
  <span class="p">{</span>
    <span class="n">_workers</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="nf">RunWorkerAsync</span><span class="p">(</span><span class="n">_cts</span><span class="p">.</span><span class="n">Token</span><span class="p">));</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And inside of the RunWorkerAsync’s while loop you call <code class="language-plaintext highlighter-rouge">token.ThrowIfCancellationRequested();</code> that will throw OperationCancelException and exit the thread when the cancel is requested.</p>

<p>With windows service when you start a service the main Win32 Service thread gives you some time to start your processes and it must return quickly, meaning not to get blocked. So your OnStop method is where you have to call your <code class="language-plaintext highlighter-rouge">Task.WaitAll(_workers)</code> which blocks the current thread until all workers have completed their tasks. So once the OnStop method begins you signal the cancellation token to cancel the tasks, and then you call Task.WaitAll and wait until all tasks run to completion. If all tasks have been completed prior to calling WaitAll it would just continue so there is no risk that it could finish faster. The OnStop method looks like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">_cts</span><span class="p">.</span><span class="nf">Cancel</span><span class="p">();</span>
<span class="k">try</span>
<span class="p">{</span>
    <span class="n">Task</span><span class="p">.</span><span class="nf">WaitAll</span><span class="p">(</span><span class="n">_workers</span><span class="p">.</span><span class="nf">ToArray</span><span class="p">());</span>
<span class="p">}</span>
<span class="k">catch</span> <span class="p">(</span><span class="n">AggregateException</span> <span class="n">ex</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">ex</span><span class="p">.</span><span class="nf">Handle</span><span class="p">(</span><span class="n">inner</span> <span class="p">=&gt;</span> <span class="n">inner</span> <span class="k">is</span> <span class="n">OperationCanceledException</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>It uses an AggregateException.Handle method which will throw any unhandled exceptions after it finished running. And since we are only expecting OpearationCanceledException it will just return.</p>

<h3 id="polishing-it-up">Polishing it up</h3>

<p>One problem with windows service application is that it’s hard debug, you cannot just attach the debugger to the running win32 service. To work around this problem we will use a <a href="http://topshelf-project.com/">topshelf project</a>. Topshelf allows you to run your windows service just like you would run a console application with the ability to debug and step through the code. It also make it easier to configure, install and uninstall the service.</p>

<p>Here is a quick sample code that will make a message processor console application into a Win32 service.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">MessageProcessor</span>
<span class="p">{</span>
    <span class="n">List</span><span class="p">&lt;</span><span class="n">Task</span><span class="p">&gt;</span> <span class="n">_workers</span><span class="p">;</span>
    <span class="n">CancellationTokenSource</span> <span class="n">_cts</span><span class="p">;</span>
    <span class="k">public</span> <span class="nf">MessageProcessor</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="n">_workers</span> <span class="p">=</span> <span class="k">new</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">Task</span><span class="p">&gt;();</span>
        <span class="n">_cts</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">CancellationTokenSource</span><span class="p">();</span>
    <span class="p">}</span>
    <span class="k">public</span> <span class="k">void</span> <span class="nf">Start</span><span class="p">()</span> <span class="p">{</span>  <span class="c1">//.. same as above }</span>
    <span class="k">public</span> <span class="k">void</span> <span class="nf">Stop</span><span class="p">()</span> <span class="p">{</span> <span class="c1">//.. same as above }</span>
<span class="p">}</span>

<span class="k">public</span> <span class="k">class</span> <span class="nc">Program</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">Main</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="n">HostFactory</span><span class="p">.</span><span class="nf">Run</span><span class="p">(</span><span class="n">x</span> <span class="p">=&gt;</span>
        <span class="p">{</span>
            <span class="n">x</span><span class="p">.</span><span class="n">Service</span><span class="p">&lt;</span><span class="n">MessageProcessor</span><span class="p">&gt;(</span><span class="n">s</span> <span class="p">=&gt;</span>
            <span class="p">{</span>
                <span class="n">s</span><span class="p">.</span><span class="nf">ConstructUsing</span><span class="p">(</span><span class="n">name</span><span class="p">=&gt;</span> <span class="k">new</span> <span class="nf">MessageProcessor</span><span class="p">());</span>
                <span class="n">s</span><span class="p">.</span><span class="nf">WhenStarted</span><span class="p">(</span><span class="n">tc</span> <span class="p">=&gt;</span> <span class="n">tc</span><span class="p">.</span><span class="nf">Start</span><span class="p">());</span>
                <span class="n">s</span><span class="p">.</span><span class="nf">WhenStopped</span><span class="p">(</span><span class="n">tc</span> <span class="p">=&gt;</span> <span class="n">tc</span><span class="p">.</span><span class="nf">Stop</span><span class="p">());</span>
            <span class="p">});</span>
            <span class="n">x</span><span class="p">.</span><span class="nf">RunAsLocalSystem</span><span class="p">();</span>

            <span class="n">x</span><span class="p">.</span><span class="nf">SetDescription</span><span class="p">(</span><span class="s">"Amazon SQS Message Processor"</span><span class="p">);</span>
            <span class="n">x</span><span class="p">.</span><span class="nf">SetDisplayName</span><span class="p">(</span><span class="s">"AmazonSQSMessageProcessor"</span><span class="p">);</span>
            <span class="n">x</span><span class="p">.</span><span class="nf">SetServiceName</span><span class="p">(</span><span class="s">"AmazonSQSMessageProcessor"</span><span class="p">);</span>
        <span class="p">});</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Once you build an executable, you can run <code class="language-plaintext highlighter-rouge">MessageProcessor.exe install</code> from command line and the service will get installed, additional -help will show you all the commands that you can do.</p>

<h3 id="summary">Summary</h3>

<p>Incorporating queues in your application architecture can help with guaranteed delivery of the business critical messages. It can also speed up your application process since it will offload the work to the external process. On the downside, your application becomes dependent on another application running in a separate process and it’s more code to maintain and deploy. To ensure you message processor doesn’t become a single point of failure, you will also need to have at least 2 nodes running this windows service for redundancy. However, if your business requires guaranteed delivery for the mission critical API calls, the overhead of maintaining message queue solution is worth it’s weight.</p>


										
					<p>Posted in: message-queue</p>
						
				
					<p>Tagged with: windows-service, message-queue, and amazon-sqs</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/message-queue/2014/08/11/amazon-sqs-message-processor/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/message-queue/2014/08/11/amazon-sqs-message-processor/]]></guid>
		<pubDate>2014-08-11T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[How to Sell And Feel Good]]></title>
		<description>
			<![CDATA[
				<p>The problem is that most software engineers suck at sales. I personally felt like it was never my job, and never bothered to learn it. Only to discover later that if I ever wanted to grow a successful business I would have to eventually take the bull by the horns and do it. And it’s not only business, being a great salesman can help to build a successful career as well.</p>

<p>Having lack of knowledge and experience in selling, it was very important for me to hear a real story from a person in software industry, who was actually successful at selling his or her consulting services. Luckily, I came across this great interview on <a href="http://eventualmillionaire.com/ian-altman/">The Eventual Millionare podcast</a> where I learned about Ian Altman . He built and sold software consulting businesses before, and he has coined his own method of selling that actually made a lot of sense to me.</p>

<p>I’ve always had this bias about salespeople being sleazy and dishonest, but what Ian found out is that it doesn’t have to be that way. He explains that if you focus on FIT (Finding Impact Together) you actually become a problem solver <strong>who works together with the client rather than against him</strong>. You focus on results and impact, and if your service doesn’t bring value to the client you walk away.</p>

<h3 id="enter-same-side-selling">Enter “Same Side Selling”</h3>

<p>I was eager to learn more about his approach and I picked up Ian’s book right away. Since I never closed a sale before, I found <a href="http://www.amazon.com/gp/product/1940858062/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1940858062&amp;linkCode=as2&amp;tag=sermassblo-20&amp;linkId=WHVTWBK2EXC2APFL">Same Side Selling book</a> very informative. Further, I learned that rather than explaining all the things that you offer, if you focus on actual problems, your client would not need to translate it into his own language. And if what you are describing is an actual problem that his business is having, he will be much more likely interested in what you have to say.</p>

<p>The book is full of wisdom on how to sit down with a customer to identify the problem, and figure out if it’s worth solving. Author brings up analogy of puzzle pieces where you need ask a series of well formulated questions to learn about the pieces that your customer has and see if yours fit. Unless you actually get to the underlying issue you won’t know for sure that your solution will bring the results.</p>

<p>Honesty and focusing on the outcome rather than a sale is the best way to get on the same side with a client, and it’s much more likely to benefit both parties in the long run.</p>

<p>This approach of problem solving fits my personality very well, and I will definitely practice it in the near future.</p>

<p>I will have to read this book over again, especially before a meeting with a client, so I can refresh and tune in on the same side selling method. I will let you know how it goes.</p>

<h3 id="honest-solution">Honest Solution</h3>

<p>This book has opened my eyes that selling doesn’t have to be adversarial. That figuring out a problem with a client and getting his business should be mutually beneficial. Honest selling helps building reputation and gets repeat business.</p>


				<p>The problem is that most software engineers suck at sales. I personally felt like it was never my job, and never bothered to learn it. Only to discover later that if I ever wanted to grow a successful business I would have to eventually take the bull by the horns and do it. And it’s not only business, being a great salesman can help to build a successful career as well.</p>

<p>Having lack of knowledge and experience in selling, it was very important for me to hear a real story from a person in software industry, who was actually successful at selling his or her consulting services. Luckily, I came across this great interview on <a href="http://eventualmillionaire.com/ian-altman/">The Eventual Millionare podcast</a> where I learned about Ian Altman . He built and sold software consulting businesses before, and he has coined his own method of selling that actually made a lot of sense to me.</p>

<p>I’ve always had this bias about salespeople being sleazy and dishonest, but what Ian found out is that it doesn’t have to be that way. He explains that if you focus on FIT (Finding Impact Together) you actually become a problem solver <strong>who works together with the client rather than against him</strong>. You focus on results and impact, and if your service doesn’t bring value to the client you walk away.</p>

<h3 id="enter-same-side-selling">Enter “Same Side Selling”</h3>

<p>I was eager to learn more about his approach and I picked up Ian’s book right away. Since I never closed a sale before, I found <a href="http://www.amazon.com/gp/product/1940858062/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1940858062&amp;linkCode=as2&amp;tag=sermassblo-20&amp;linkId=WHVTWBK2EXC2APFL">Same Side Selling book</a> very informative. Further, I learned that rather than explaining all the things that you offer, if you focus on actual problems, your client would not need to translate it into his own language. And if what you are describing is an actual problem that his business is having, he will be much more likely interested in what you have to say.</p>

<p>The book is full of wisdom on how to sit down with a customer to identify the problem, and figure out if it’s worth solving. Author brings up analogy of puzzle pieces where you need ask a series of well formulated questions to learn about the pieces that your customer has and see if yours fit. Unless you actually get to the underlying issue you won’t know for sure that your solution will bring the results.</p>

<p>Honesty and focusing on the outcome rather than a sale is the best way to get on the same side with a client, and it’s much more likely to benefit both parties in the long run.</p>

<p>This approach of problem solving fits my personality very well, and I will definitely practice it in the near future.</p>

<p>I will have to read this book over again, especially before a meeting with a client, so I can refresh and tune in on the same side selling method. I will let you know how it goes.</p>

<h3 id="honest-solution">Honest Solution</h3>

<p>This book has opened my eyes that selling doesn’t have to be adversarial. That figuring out a problem with a client and getting his business should be mutually beneficial. Honest selling helps building reputation and gets repeat business.</p>


										
					<p>Posted in: business</p>
						
				
					<p>Tagged with: business and sales</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/business/2014/06/30/same-side-selling/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/business/2014/06/30/same-side-selling/]]></guid>
		<pubDate>2014-06-30T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[A Successful SQL Database Migration Model]]></title>
		<description>
			<![CDATA[
				<p><img src="/uploads/2014/04/database-migration.png" style="float:right; margin-right:30px; width:229px !important;" /></p>


				<p><img src="/uploads/2014/04/database-migration.png" style="float:right; margin-right:30px; width:229px !important;" /></p>

<p>Here is a simple database migration model that I recently adopted at work. It worked out really well. With little effort, we are now able to create new or upgrade existing database to any specific commit in the source control. And now since production SQL changes are migrated with an automatic batch process, it has streamlined our deploys as well.</p>

<h3 id="start-with-a-baseline-script">Start with a Baseline Script</h3>
<p>Baseline script is necessary for creating database from scratch. It’s used for setting new environments or even daily development work where you want to make sure to start with a clean slate.</p>

<p>If you already have an existing database you will need to start by creating a baseline script. The best time to do that is after a fresh deploy to production. That way you know your development version of database should be the same as production, and you now have a clear starting point or baseline. Here are the steps I took.</p>

<ul>
  <li><a href="http://blog.sqlauthority.com/2011/05/07/sql-server-2008-2008-r2-create-script-to-copy-database-schema-and-all-the-objects-data-schema-stored-procedure-functions-triggers-tables-views-constraints-and-all-other-database-objects/">Script entire database</a> schema with objects</li>
  <li>Clean up schema if necessary. (I had to remove replication directives, and creation of  production users since those are production only settings.)</li>
  <li>Add any necessary seed data for testing purposes. When you rebuild a database it will most likely be used for development or QA, therefore most likely you will need some starting data.</li>
</ul>

<h3 id="add-migration-scripts">Add Migration scripts</h3>
<p>Migration scripts get applied in order in which they are created and only migrate database up. This model does not involve downgrading, simply because we haven’t found a need for it (production database is never downgraded, and local/test version can always be recreated from scratch).</p>

<p>When a developer is working on a feature or a bug that needs database changes, he creates a new migration file with a next sequential number in the file name. For example: if the last migration file is Script-0048.sql next a new migration script will be Script-0049.sql.</p>
<blockquote>
  <p>They have to be sequential because that’s how we can make sure that migrations are applied in order they were created, and can guarantee consistency between environments.</p>
</blockquote>

<h3 id="version-control-your-sql-scripts">Version Control your SQL scripts</h3>

<p>Next important piece is to version control your scripts. It plays the following roles:</p>

<ul>
  <li>Source control becomes a mediator, so multiple developers cannot check-in script with the same name. In addition, if there is a conflict with names developers are forced to get latest and change their script name.</li>
  <li>Each branch has it’s own list of migration scripts, and <strong>there is no doubt of what your database should look like to match the code base in any branch or individual commit</strong>. It simply must have all migration scripts applied to the baseline.</li>
  <li>It keeps track of changes and we want to make sure there are no changes once a migration script is in source control. (more on that in the Rules section)</li>
</ul>

<h3 id="keeping-track-of-migrations">Keeping track of migrations</h3>

<p>How do we know what migrations scripts were applied to the database? Simple, we create a table that keeps track of executed script.  That way it’s easy to compare what’s already executed and what scripts need to be applied to get to a specific point in time. A simple table like this will do.</p>

<p><img src="/uploads/2014/04/AppliedScriptsTable.png" alt="" /></p>

<p>Finally, your migration application takes care of figuring out which scripts are missing, executing missing scripts, and recording applied scripts in the log table.</p>

<h3 id="two-easy-rules-for-stress-free-migrations">Two Easy Rules for Stress Free Migrations</h3>

<ul>
  <li><strong>Once a SQL migration script is committed and pushed to the source control it must never change.</strong> We do that to eliminate potential inconsistencies between environments, because once a script is out in the wild you can assume it was already applied somewhere and if script changes that environment will never get updated.</li>
  <li><strong>Automate database migrations completely</strong>. There is absolutely no reason why you need to manually run the update scripts, it’s frustrating, error prone, and it’s waste of time. You can quickly write a batch process that will execute each script and add a record into the journal table, or you can use existing open source projects like <a href="http://dbup.github.io/">DbUp</a> for that. We’ve opted in for DbUp since it already does exactly that and has other nice features like wrapping all migration scripts in a transaction.</li>
</ul>

<h3 id="rebuild-or-migrate-your-database-with-one-click">Rebuild or Migrate Your Database With One Click</h3>

<p>We’ve created two Powershell scripts that will either create or upgrade local database with all migration scripts in the current source control tree. Rebuild will execute baseline script + migrations. Upgrade will only apply missing migrations and it’s the same script that’s used in production. There is no more need to use shared database, developer can migrate or re-create his version of the database in few seconds. I’ve also had an idea to include a module that will check on application start if the database is out of date and apply needed scripts, I wouldn’t run it in production but it’s perfect for development.</p>

<p>After setting up automatic migrations it was very easy to setup test environments for functional end to end testing with Selenium. Continuous integration server will pull latest from the code base, run database upgrade script, build and publish site, and execute functional tests.</p>

<h3 id="conclusion-a-lot-of-impact-for-a-little-effort">Conclusion: A lot of impact for a little effort</h3>

<p>I’ve been part of many overnight deployments that gone wrong due to some missing stored procedure, and felt the agony of chasing down errors at 2AM in the morning. It really doesn’t take long to apply this model, even less so if you choose to use existing open source libraries like <a href="http://dbup.github.io/">DbUp</a>. While there is nothing radical about this practice, I know a lot of companies are still manually deploying their SQL scripts. It’s a small change with big impact that will streamline your development and make production database migration smooth with guaranteed correctness. It worked out great for my company. How do you manage your database migrations?</p>


										
					<p>Posted in: sql</p>
						
				
					<p>Tagged with: database-migration</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/sql/2014/04/14/successful-sql-database-migration-model/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/sql/2014/04/14/successful-sql-database-migration-model/]]></guid>
		<pubDate>2014-04-14T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[10 Deploys A Day]]></title>
		<description>
			<![CDATA[
				<p>This post was inspired by <a href="http://www.realgenekim.me/">Gene Kim</a>’s talk on continuous delivery and his eye opening book <a href="http://www.amazon.com/gp/product/0988262592/ref=as_li_ss_tl?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0988262592&amp;linkCode=as2&amp;tag=sermassblo-20">The Phoenix Project</a>.</p>


				<p>This post was inspired by <a href="http://www.realgenekim.me/">Gene Kim</a>’s talk on continuous delivery and his eye opening book <a href="http://www.amazon.com/gp/product/0988262592/ref=as_li_ss_tl?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0988262592&amp;linkCode=as2&amp;tag=sermassblo-20">The Phoenix Project</a>.</p>

<p>What is a continuous delivery? It’s a methodology that allows you to get new features and capabilities to market quickly and reliably. It’s a practice that shortens work in progress and allows for rapid feedback on your new features or improvements. It’s automation of many parts including testing, creation of environments, and one button push deployments. It’s a magical unicorn that allows companies to deploy 10 times a day without much effort or risk of breaking stuff!</p>

<p>The reason why his story strikes a chord with me is because I strongly believe that automation can streamline the software development, make employees happy, and help organizations to become high performers. And automation is a big part of continuous delivery methodology. Throughout my career, I’ve participated in many painful deployments that lasted more than a day and usually were throughout the weekend. And I believe nobody should be a part of that because there is a better way that’s within reach of many companies. As a result, developers can focus on doing stuff that matters, companies can deliver new features much more rapidly, and stake holders can see their ideas spring to life very quickly.</p>

<h3 id="average-horse">Average Horse</h3>
<p>First, let’s dive deeper into the normal software delivery practice of an average company.</p>

<ul>
  <li>Product managers will come up with arbitrary due dates without doing technical capacity planning, making promises that we cannot keep. And in result, when a due date comes, product is rushed with many shortcuts taken, which results in lower quality and more fragile applications, which means more technical debt and <em>unplanned</em> worked later.</li>
  <li>Security is not even in the picture because new features are not getting to market quickly enough.</li>
  <li>Technical debt continues to get stock piled and is rarely paid off. Like financial interest, it grows over time until most of the time is spent on just paying off the interest in the form of unplanned work.</li>
  <li>Deployments are not automated and it takes long time to manually deploy. Therefore deployments are a lot less frequent, that means a huge number of features are being deployed at once. That means finished work does not make it into production for months, sometimes years (scary), and that means no rapid feedback on performance, adoption, or business value. Comparing that to the manufacturing plant, where at the bottleneck station you have a stock pile of work, and you have to stop everything just to catch up. At that point you cannot give any feedback because other stations already finished their work, and it’s very costly to change already made stuff (unplanned work) and the solution is lower quality product (technical debt).</li>
  <li>Due to lack of automated testing, companies have to deploy even more infrequent since it takes an army of QA engineers to regression test the entire application, and it becomes even longer as more features are deployed.</li>
  <li>Failed features don’t get pruned, but rather just left to rot and accumulate more security, technical, and maintance debt.</li>
</ul>

<blockquote>
  <p>Unplanned work is not free, it’s actually really expensive. Another
side affect is when you spend all your time firefighting, no time or
energy left for planning. When all you do is react, there’s not enough
time to do the hard mental work of figuring out whether you can accept
new work. Which means more shortcuts, more multitasking. - The Phoenix Project</p>
</blockquote>

<h3 id="how-unicorns-work">How Unicorns Work</h3>

<p>The main idea behind continuous delivery is to reduce work in progress (WIP) that would allow for quicker feedback of what goes into production. For example, if you work on a 9 month long project it will take you longer than 9 months to see your code in production, and if something has a problem it will be very expensive to go back and change some design decisions. Therefore, there is a good possibility that a fix will just be a hack rather than a proper solution, meaning more technical debt accumulating, more problems later. And not to forget that after 9 months of projects it will take the whole weekend and huge amount of agony to release it.</p>

<p>Gene’s term for WIP in IT terms is a “Lead Time” which measures how long it takes to go from code committed to code successfully running in production. And until code is in production is has absolutely no value because it’s just sitting there. Focusing on fast flow will improve quality, customer satisfaction, return on investment, and employee happiness.</p>

<p>But you think it must be crazy to release so much a day, isn’t it dangerous to make all those changes? It’s actually a lot less risky to deploy small changes incrementally because you get rapid feedback. And even if there is a problem it’s much easier to fix small problem sooner rather than later where you are forced to take shortcuts.</p>

<p>To get there, you have to “improve at bottlenecks”, and any improvements that are not done at the bottlenecks are a waist of time. If your deployment process is a bottleneck, you have to automate it, until it becomes one button push deployment. There is absolutely no good reason why a developer cannot push a button which will create a QA environment that exactly matches production with code deployed, and if it passes automated functional tests it can be put into production with another push of the button. If the regression testing is a bottleneck then you need to pay off that debt by writing automated functional tests or end to end system tests.</p>

<blockquote>
  <p>“Automated tests transform fear into boredom.” –Eran Messeri, Google</p>
</blockquote>

<p>To become high performer, you will also need to add monitoring hooks to your applications, so that any developer can add his or her metrics at will. So when you release often, you can get rapid feedback on the performance, adoption, and value. That way you can make an inform decisions and rollback if necessary. It should be extremely easy for developer to add any kind of monitoring metrics to code and data must be accessible from production.</p>

<p>Gene proposed to spend 20% of the time to work on non-functional improvements, or non feature work, and I think if any organization adopted that they would be on their way of becoming a high performing unicorn. I honestly don’t think it’s much to invest comparing to opportunity cost of features not making out for long periods of time and where only 10% of features are successful. How can you test something when you can only release couple times a year?</p>

<p>Finally, you should be deploying to production with your features turned off that way your releases are not at the same time as deployments and turning features on and off is a simple button click.</p>

<blockquote>
  <p>It’s not art, it’s production.
If you can’t out-experiment and beat your competitors in time to
market and agility, you are sunk! Features are always a gamble. If you
are lucky, ten percent will get the desired benefits. So the faster
you get those features to market and test them, the better you will
be. - The Phoenix Project</p>
</blockquote>

<p>And if you think 10 deploys a day is crazy take for example Amazon with a mean time between deployments of 11.6 seconds (insane). And it’s not just them, companies like Intuit, Target, Google, Etsy, Flikr, Kansas State University and many others have embraced continuous delivery.</p>

<h3 id="it-does-not-have-to-be-radical-small-steps-are-just-fine">It Does Not Have To Be Radical. Small Steps Are Just Fine.</h3>
<p>In a perfect world, a company with problems would stop everything to fix the production line and pay off the technical debt. And some companies like EBay had to do that to escape the vicious cycle. I don’t think it has to be so drastic for an average company. I believe if you accept the culture of continuous improvement, and first focus on all the bottlenecks, you can soon get there. For example, you can make small changes that will bring a lot of improvement. For example, if you deployment is a manual process focus on automatically creating packages and create a script that will automatically deploy. If it requires database changes, add scripts to the package and your deployment script will deploy database changes automatically. There is no reason why a DBA has to compile and execute scripts by hand when it can be automated. If your need many QA engineers to regression test the site, why not spend some of their time to write automated tests, I’m sure they would be happier to find new bugs rather then doing senseless testing of the same stuff.</p>

<h3 id="final-thoughts">Final Thoughts</h3>
<p>Gene urges us to create a culture of genuine learning and experimentation and that’s how best companies get even better. In additional here a great quote if you think it’s not relevant to you</p>

<blockquote>
  <p>Most of the money spent are on IT Projects these days and even if
companies say it’s not their core competency it’s not true. Everyone
must learn or you risk irrelevance in 10 years. - Gene Kim</p>
</blockquote>

<p>Good luck and see you in the world of unicorns! :)</p>


										
					<p>Posted in: continuous-delivery</p>
						
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/continuous-delivery/2014/03/30/10-deploys-a-day/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/continuous-delivery/2014/03/30/10-deploys-a-day/]]></guid>
		<pubDate>2014-03-30T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Getting Serious About JavaScript]]></title>
		<description>
			<![CDATA[
				<h3 id="why-should-i-care-about-javascript">Why Should I Care About JavaScript?</h3>
<p>If you want to build next generation platforms or web applications you have to get serious about JavaScript. Rich user interfaces, or Single Page Applications, provide a much better user experience and give products an edge over competition. Many new applications like DropBox, Trello, Windows Azure and many others are a great example of amazing user experience. In addition, JavaScript is already very widely used on the server side as well. It’s incredably fast, asynchronous out of the box, and is a perfect backend for your single page applications. Finally, it has a huge ecosystem with almost as <a href="http://modulecounts.com/">many NPM</a> packages than the largest platform, and catching up really fast. As we’ve seen before where community goes that’s where the next most widely used platform will be.</p>


				<h3 id="why-should-i-care-about-javascript">Why Should I Care About JavaScript?</h3>
<p>If you want to build next generation platforms or web applications you have to get serious about JavaScript. Rich user interfaces, or Single Page Applications, provide a much better user experience and give products an edge over competition. Many new applications like DropBox, Trello, Windows Azure and many others are a great example of amazing user experience. In addition, JavaScript is already very widely used on the server side as well. It’s incredably fast, asynchronous out of the box, and is a perfect backend for your single page applications. Finally, it has a huge ecosystem with almost as <a href="http://modulecounts.com/">many NPM</a> packages than the largest platform, and catching up really fast. As we’ve seen before where community goes that’s where the next most widely used platform will be.</p>

<p>And it’s not only startups that choose Node.js, recently a company like PayPal <a href="https://medium.com/paypal-engineering/node-js-at-paypal-4e2d1d08ce4f">announced</a> that they chose Node.js to be an application platform of choice. And some great benefits they reported so far:</p>

<blockquote>
  <p>Built almost twice as fast with fewer people <br />
Written in 33% fewer lines of code <br />
Constructed with 40% fewer files</p>
</blockquote>

<p>From my personal experience I can also say that development JavaScript is real fun, it’s very fast and I enjoy learning functional nature of it. <a href="http://paulgraham.com/avg.html">Paul Graham</a> chose Lisp because it allowed them at ViaWeb to ship code faster than competition. I feel like JavaScript has that advantage now as well. It’s also functionals and it has a large number of open source project that you can pick and choose, so you don’t have to reinvent the wheel. So why wouldn’t you use it if you had to choose a platform?</p>

<h3 id="its-time-to-get-serious-about-learning-javascript">It’s time to get serious about learning JavaScript</h3>

<p>Writing large application will require developers to actually pick up few books and finally learn the language. You can no longer get away with hacking together bunch of spaghetti code with global variables. Good news is that now there are a lot more good resources than there was few years ago. Couple great books that I had a pleasure of reding provide invaluable deep knowledge of the language. Another super resource for learning JavaScript is to read existing open source libraries. You can extract a large amount of knowledge for free if you are willing to roll up your sleeves and get uncomfortable. Finally, like any serious developers we want to write our components with help of unit tests. I’ve also found that testability of Javascript is extremely important, browser debugging is somewhat not efficient and you have to jump through different places due to Javascrit’s asynchronous <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/EventLoop">event loop</a> nature. It’s easier to test components individually then debug entire application.</p>

<p>So here are the books that I’ve really enjoyed and will get you up to speed if you are a seasoned pro in other languages like C# or Java.</p>
<h3 id="great-books">Great Books</h3>

<p><a href="https://amzn.to/2Vfuz8b"><img src="https://user-images.githubusercontent.com/159128/85763052-301b5200-b6c9-11ea-85d3-fd44ae2c407f.jpg" alt="javascript_patterns" /></a></p>

<p><strong>JavaScript Patters</strong>: I found this very helpful with breaking down different patterns of object creations, function types, and overall best practices. It packs a lot great stuff in about 200 pages and will give you a quick intro without going too deep into language itself. After I read this book, I was finally able to understand different object creation patterns and why you would use one over another. If you don’t want to get too deep into language but want to actually write clean code and to be able to read existing librarires I think you can get away with this book. Because this book was written in 2010, most of the examples covered are following EcmaScript 3 standard, so it’s great if you want to support old browsers.</p>

<p><a href="https://amzn.to/2Z8NDpR"><img src="https://user-images.githubusercontent.com/159128/85763047-2f82bb80-b6c9-11ea-9d48-3c800a13f1c2.jpg" alt="async_javascript" /></a></p>

<p><strong>Async JavaScript</strong> This is an awesome book to pick up next. It explains very well asynchronous functions, async error handling and event loop. This knowledge is a must for any serious JavaScript programmer. Every page of this book 80 page book is densely packed with information and you want to read it slow and enjoy every bit of it. It also dives into of how to make your callbacks cleaner with promises and deferreds. Finally it takes a look at existing async libraries that can make your life a lot more easier when dealing with multiple asynchronous functions. The biggest “aha” moment when I read this book was an understanding of how event loop queue works and why some libraries execute functions with setTimeout.</p>

<p><a href="https://amzn.to/31jOo26"><img src="https://user-images.githubusercontent.com/159128/85763051-301b5200-b6c9-11ea-88e7-aebd6bc4ffa6.jpg" alt="Effective JavaScript" /></a></p>

<p><strong>Effective JavaScript</strong> From the legendary Effective series, this book is lives up to it’s standard. It goes deep into the language in a series of 68 topics. It’s very good at breaking down and explaining topics and contains a wealth of knowledge. It actually explains intricate details about JavaScript semicolon insertion, implicit coercions, and a lot of other goodness like implicit binding of “this”.  A lot of subjects are already covered in other books, but this book actually explains them in more detail and why things the way they are. It’s not overly complex but it is very dense with information and joy to read. This is a must read for any serious developer who wants a deeper understanding of the JavaScript language.</p>

<h3 id="great-javascript-libraries-to-read">Great JavaScript Libraries To Read</h3>
<p><a href="https://github.com/tryghost/Ghost">Ghost</a> is a new, simple bloging platform that’s build on top of Node.js with Express on backend and Backbone on the client. If you are looking to build a full stack applications with JavaScript this project will get you going. I found it a great way to get up to speed on how configuration, modules, and data access setup. Among other things you can learn about authentication, middleware, and see extensive use of deferreds.</p>

<p><a href="https://github.com/jashkenas/backbone">Backbone</a> What I like about backbone is that it has extensive suite of Unit Tests, the library itself is about 1700 lines of code, and it has very good comments. It’s pretty incredible that such small library is the most widely used SPA library out there. I start with reading unit tests to understand the specifications. After I have general knowledge I would dive in to pieces that I find most interesting.</p>

<p><a href="https://github.com/visionmedia/express">Express</a> Whether you are looking to build a Restful API or a traditional web application, express is great a minimalist framework on top of Node.js for that. It’s pretty simple and genius and also has a pretty small code base.</p>

<p>What others JavaScript libraries or books did you enjoy? Send me a line <a href="https://twitter.com/mercury2269">@mercury2269</a>.</p>


										
					<p>Posted in: javascript</p>
						
				
					<p>Tagged with: javascript, learning, and book-recommendations</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/javascript/2014/03/17/getting-serious-about-javascript/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/javascript/2014/03/17/getting-serious-about-javascript/]]></guid>
		<pubDate>2014-03-17T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Changes In MSBuild with Visual Studio 2013]]></title>
		<description>
			<![CDATA[
				<p>After I uninstalled Visual Studio 2012, the deployment package creation script that builds and publishes a project using MSBuild started throwing a lovely exception:</p>


				<p>After I uninstalled Visual Studio 2012, the deployment package creation script that builds and publishes a project using MSBuild started throwing a lovely exception:</p>

<blockquote>
  <p>.csproj(795,3): error MSB4019: The imported project “C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v11.0\We bApplications\Microsoft.WebApplication.targets” was not found. Confirm that the path in the <Import> declaration is correct, and that the file exists on disk.</Import></p>
</blockquote>

<p>From the error, I can tell that MSBuild is using the wrong Visual Studio version. My first thought was to to tell MSBuild to use v12 to build target by adding a VisualStudioVersion environment variable /p:VisualStudioVersion=12.0 but that resulted in a new error that was a little more confusing:</p>

<blockquote>
  <p>C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v12.0\Web\Transform\Microsoft.Web.Publishing.AspNetCompileMerge.targets(132,5): error : Can’t find the valid AspnetMergePath</p>
</blockquote>

<p>I guess something has changed, and indeed, after searching I found that that yes MSBuild <a href="http://blogs.msdn.com/b/visualstudio/archive/2013/07/24/msbuild-is-now-part-of-visual-studio.aspx">now ships as a part of Visual Stuido</a>.</p>

<p>So rather than having MSBuild shipped as a component of a .NET framework, it is now a stand alone package that comes with Visual Studio and each version corresponds to the Visual Studio version with it’s own toolsets. So the new MSBuild will be under:</p>

<blockquote>
  <p>On 32-bit machines they can be found in: C:\Program
Files\MSBuild\12.0\bin</p>

  <p>On 64-bit machines the 32-bit tools will be under: C:\Program Files
(x86)\MSBuild\12.0\bin</p>
</blockquote>

<p>So if you are building you project using C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe, without Visual Studio 2012 installed, it will no longer work, and you will need to switch your build tool to use a new msbuild 12.0 in C:\Program Files (x86)\MSBuild\12.0\Bin\MSBuild.exe.</p>

<p>That’s it, hopefully this post will save someone some time.</p>


										
					<p>Posted in: msbuild</p>
						
				
					<p>Tagged with: visual-studio-2013 and msbuild</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/msbuild/2014/03/04/changes-in-msbuild-with-visual-studio-2013/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/msbuild/2014/03/04/changes-in-msbuild-with-visual-studio-2013/]]></guid>
		<pubDate>2014-03-04T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Working With Entity Framework Detached Objects]]></title>
		<description>
			<![CDATA[
				<p>Detached objects, or objects that are created outside of Entity Framework(EF), don’t have automatic tracking enabled, and updating database from detached objects is not hard, but requires extra knowledge of EF. With this post I’d like to spell out different ways of doing it.</p>

<p>Before doing anything else, we must first check the state of an entity. If you are using Code First, an entity would be your POCO class that is mapped to the database table.</p>

<p>To get information about an entity in question, and it’s relation to the current DbContext, you call a <code class="language-plaintext highlighter-rouge">DbContext.Entry&lt;TEntity&gt;</code> method. It will return a <code class="language-plaintext highlighter-rouge">DbEntityEntry&lt;TEntity&gt;</code> object which can be used to check the state and perform additional actions on the entity.</p>

<p>When you create a new instance of a class outside of EF, it will have a detached state because context is not tracking that object.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">customer</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">Customer</span><span class="p">();</span>
<span class="kt">var</span> <span class="n">customerEntry</span> <span class="p">=</span> <span class="n">_context</span><span class="p">.</span><span class="n">Entry</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="n">customer</span><span class="p">);</span>
<span class="n">Debug</span><span class="p">.</span><span class="nf">Write</span><span class="p">(</span><span class="n">customerEntry</span><span class="p">.</span><span class="n">State</span><span class="p">)</span> <span class="c1">// EntityState.Detached</span>
</code></pre></div></div>

<p>If your object is in any state other than <code class="language-plaintext highlighter-rouge">EntityState.Detached</code>, that means EF knows about it and tracks it, so you don’t need to do anything else, <code class="language-plaintext highlighter-rouge">DbContext.SaveChanges()</code> would take care of persisting differences into the database.</p>

<p>When at first I was trying to update database from a detached object I thought that I can simply attach it and set it to be modified.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">Update</span><span class="p">(</span><span class="n">T</span> <span class="n">entity</span><span class="p">)</span>
<span class="p">{</span>
	<span class="kt">var</span> <span class="n">entry</span> <span class="p">=</span> <span class="n">_context</span><span class="p">.</span><span class="n">Entry</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="n">entity</span><span class="p">);</span>

	<span class="k">if</span> <span class="p">(</span><span class="n">entry</span><span class="p">.</span><span class="n">State</span> <span class="p">==</span> <span class="n">EntityState</span><span class="p">.</span><span class="n">Detached</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">_context</span><span class="p">.</span><span class="n">Set</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;().</span><span class="nf">Attach</span><span class="p">(</span><span class="n">entity</span><span class="p">);</span>
		<span class="n">entry</span><span class="p">.</span><span class="n">State</span> <span class="p">=</span> <span class="n">EntityState</span><span class="p">.</span><span class="n">Modified</span><span class="p">;</span>
	<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And that would work, but only if the object with the same key is not already present in the context. And if it does exist, you get a nice error:</p>

<blockquote>
  <p>An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.</p>
</blockquote>

<p>So what do you do when an object is already being tracked by EF and you have a detached object, how do you merge them together?</p>

<p>Fortunately, EF does provide a way to update an existing object from a detached object. There are couple different ways you can do it, and it all depends on the context, and what you know about your object.</p>

<p>Here is the first way you can do it:</p>

<h3 id="querying-database-first-and-updating-tracked-object">Querying Database First And Updating Tracked Object</h3>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">using</span><span class="p">(</span><span class="kt">var</span> <span class="n">db</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">StoreDbContext</span><span class="p">())</span>
<span class="p">{</span>
	<span class="kt">var</span> <span class="n">existingCart</span> <span class="p">=</span> <span class="n">db</span><span class="p">.</span><span class="n">Carts</span><span class="p">.</span><span class="nf">Find</span><span class="p">(</span><span class="n">cartId</span><span class="p">);</span>
	<span class="k">if</span><span class="p">(</span><span class="n">existingCart</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="c1">//entity is already in the context</span>
		<span class="kt">var</span> <span class="n">attachedEntry</span> <span class="p">=</span> <span class="n">db</span><span class="p">.</span><span class="nf">Entry</span><span class="p">(</span><span class="n">existingCart</span><span class="p">);</span>
		<span class="n">attachedEntry</span><span class="p">.</span><span class="n">CurrentValues</span><span class="p">.</span><span class="nf">SetValues</span><span class="p">(</span><span class="n">newCart</span><span class="p">);</span>
	<span class="p">}</span>
	<span class="k">else</span>
	<span class="p">{</span>
		<span class="c1">//Since we don't have it in db, this is a simple add.</span>
		<span class="n">db</span><span class="p">.</span><span class="n">Cart</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">newCart</span><span class="p">);</span>
	<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>After querying a database and finding a record, we know that EF is already tracking the existing object. We then get an entry object of the tracked entity and call attachedEntry.<code class="language-plaintext highlighter-rouge">CurrentValues.SetValues</code> to update it with new values. This method works like an auto mapper and updates scalar properties from the passed in object. Also if the property values is different from the original, it sets the property state to be modified.</p>

<p>That works, but requires an extra database call to get an existing record. There is also a way to do that without an extra query.</p>

<h3 id="not-performing-an-extra-database-call-and-checking-local-context">Not Performing An Extra Database Call And Checking Local Context</h3>

<p>There are times when you know for fact an entity is already in the database. An example would be when a database generated id of your object is not set to zero or default. In that situation you can save an extra call by querying the local context first. If an entity does exist in the local context you perform a similar update with attachedEntry.<code class="language-plaintext highlighter-rouge">CurrentValues.SetValues</code>, and if it does not exist, you can modify a state of your detached object to modified, which would attach the object and update the database.</p>

<p>For example, when I know that the cart id is not zero, that means it already exists in the database:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span><span class="p">(</span><span class="n">newCart</span><span class="p">.</span><span class="n">Id</span> <span class="p">&gt;</span> <span class="m">0</span><span class="p">)</span> <span class="c1">// Id already assigned, need to update.</span>
<span class="p">{</span>
	<span class="c1">//We query local context first to see if it's there.</span>
	<span class="kt">var</span> <span class="n">attachedEntity</span> <span class="p">=</span> <span class="n">db</span><span class="p">.</span><span class="n">Carts</span><span class="p">.</span><span class="n">Local</span><span class="p">.</span><span class="nf">Find</span><span class="p">(</span><span class="n">newCart</span><span class="p">.</span><span class="n">Id</span><span class="p">);</span>

	<span class="c1">//We have it in the context, need to update.</span>
	<span class="k">if</span> <span class="p">(</span><span class="n">attachedEntity</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
		<span class="kt">var</span> <span class="n">attachedEntry</span> <span class="p">=</span> <span class="n">_context</span><span class="p">.</span><span class="nf">Entry</span><span class="p">(</span><span class="n">attachedEntity</span><span class="p">);</span>
		<span class="n">attachedEntry</span><span class="p">.</span><span class="n">CurrentValues</span><span class="p">.</span><span class="nf">SetValues</span><span class="p">(</span><span class="n">newCart</span><span class="p">);</span>
	<span class="p">}</span>
	<span class="k">else</span>
	<span class="p">{</span>
		<span class="c1">//If it's not found locally, we can attach it by setting state to modified.</span>
		<span class="c1">//This would result in a SQL update statement for all fields</span>
		<span class="c1">//when SaveChanges is called.</span>
		<span class="kt">var</span> <span class="n">entry</span> <span class="p">=</span> <span class="n">db</span><span class="p">.</span><span class="nf">Entry</span><span class="p">(</span><span class="n">newCart</span><span class="p">);</span>
		<span class="n">entry</span><span class="p">.</span><span class="n">State</span> <span class="p">=</span> <span class="n">EntityState</span><span class="p">.</span><span class="n">Modified</span><span class="p">;</span>
	<span class="p">}</span>
<span class="p">}</span>
<span class="k">else</span>
<span class="p">{</span>
	<span class="c1">//This is a simple add since we don't have it in db.</span>
	<span class="n">db</span><span class="p">.</span><span class="n">Cart</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">newCart</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>There is a small difference when you query the database first. EF knows which values have been modified an only those specific value. On the other hand, when you are blindly attaching modified entity, EF doesn’t know what fields have changes and performs an update on all fields.</p>

<h3 id="it-works-but-not-fully">It Works, But Not Fully…</h3>

<p>When you call <code class="language-plaintext highlighter-rouge">CurrentValues.SetValues(newCart)</code> it will update all scalar properties on your newCart object and set them to modified. However, navigation properties would not get the same respect. As of today EF does not support of full object graph merging, and leaves that for you to manage on your own. So if you have newCart.Customer navigational property it would not get updated. It’s <a href="https://entityframework.codeplex.com/workitem/864">the second most requested feature</a> for EF at the moment, so I think they would add it in the future release.</p>

<p>So for now you have to manually call <code class="language-plaintext highlighter-rouge">SetValues</code> on all your navigational properties in order for them to be updated. There are also <a href="https://github.com/refactorthis/GraphDiff">other solutions</a> that people have written that might help with updating a full graph.</p>

<p>Finally, if you object graph is not very large, you can get away with getting <code class="language-plaintext highlighter-rouge">DbEntityEntry</code> and calling <code class="language-plaintext highlighter-rouge">SetValues</code> on each navigational property. But if you do have a large graph and want something automatic I would try something like GraphDiff first.</p>

				<p>Detached objects, or objects that are created outside of Entity Framework(EF), don’t have automatic tracking enabled, and updating database from detached objects is not hard, but requires extra knowledge of EF. With this post I’d like to spell out different ways of doing it.</p>

<p>Before doing anything else, we must first check the state of an entity. If you are using Code First, an entity would be your POCO class that is mapped to the database table.</p>

<p>To get information about an entity in question, and it’s relation to the current DbContext, you call a <code class="language-plaintext highlighter-rouge">DbContext.Entry&lt;TEntity&gt;</code> method. It will return a <code class="language-plaintext highlighter-rouge">DbEntityEntry&lt;TEntity&gt;</code> object which can be used to check the state and perform additional actions on the entity.</p>

<p>When you create a new instance of a class outside of EF, it will have a detached state because context is not tracking that object.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">customer</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">Customer</span><span class="p">();</span>
<span class="kt">var</span> <span class="n">customerEntry</span> <span class="p">=</span> <span class="n">_context</span><span class="p">.</span><span class="n">Entry</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="n">customer</span><span class="p">);</span>
<span class="n">Debug</span><span class="p">.</span><span class="nf">Write</span><span class="p">(</span><span class="n">customerEntry</span><span class="p">.</span><span class="n">State</span><span class="p">)</span> <span class="c1">// EntityState.Detached</span>
</code></pre></div></div>

<p>If your object is in any state other than <code class="language-plaintext highlighter-rouge">EntityState.Detached</code>, that means EF knows about it and tracks it, so you don’t need to do anything else, <code class="language-plaintext highlighter-rouge">DbContext.SaveChanges()</code> would take care of persisting differences into the database.</p>

<p>When at first I was trying to update database from a detached object I thought that I can simply attach it and set it to be modified.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">Update</span><span class="p">(</span><span class="n">T</span> <span class="n">entity</span><span class="p">)</span>
<span class="p">{</span>
	<span class="kt">var</span> <span class="n">entry</span> <span class="p">=</span> <span class="n">_context</span><span class="p">.</span><span class="n">Entry</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="n">entity</span><span class="p">);</span>

	<span class="k">if</span> <span class="p">(</span><span class="n">entry</span><span class="p">.</span><span class="n">State</span> <span class="p">==</span> <span class="n">EntityState</span><span class="p">.</span><span class="n">Detached</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="n">_context</span><span class="p">.</span><span class="n">Set</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;().</span><span class="nf">Attach</span><span class="p">(</span><span class="n">entity</span><span class="p">);</span>
		<span class="n">entry</span><span class="p">.</span><span class="n">State</span> <span class="p">=</span> <span class="n">EntityState</span><span class="p">.</span><span class="n">Modified</span><span class="p">;</span>
	<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And that would work, but only if the object with the same key is not already present in the context. And if it does exist, you get a nice error:</p>

<blockquote>
  <p>An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.</p>
</blockquote>

<p>So what do you do when an object is already being tracked by EF and you have a detached object, how do you merge them together?</p>

<p>Fortunately, EF does provide a way to update an existing object from a detached object. There are couple different ways you can do it, and it all depends on the context, and what you know about your object.</p>

<p>Here is the first way you can do it:</p>

<h3 id="querying-database-first-and-updating-tracked-object">Querying Database First And Updating Tracked Object</h3>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">using</span><span class="p">(</span><span class="kt">var</span> <span class="n">db</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">StoreDbContext</span><span class="p">())</span>
<span class="p">{</span>
	<span class="kt">var</span> <span class="n">existingCart</span> <span class="p">=</span> <span class="n">db</span><span class="p">.</span><span class="n">Carts</span><span class="p">.</span><span class="nf">Find</span><span class="p">(</span><span class="n">cartId</span><span class="p">);</span>
	<span class="k">if</span><span class="p">(</span><span class="n">existingCart</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
	<span class="p">{</span>
		<span class="c1">//entity is already in the context</span>
		<span class="kt">var</span> <span class="n">attachedEntry</span> <span class="p">=</span> <span class="n">db</span><span class="p">.</span><span class="nf">Entry</span><span class="p">(</span><span class="n">existingCart</span><span class="p">);</span>
		<span class="n">attachedEntry</span><span class="p">.</span><span class="n">CurrentValues</span><span class="p">.</span><span class="nf">SetValues</span><span class="p">(</span><span class="n">newCart</span><span class="p">);</span>
	<span class="p">}</span>
	<span class="k">else</span>
	<span class="p">{</span>
		<span class="c1">//Since we don't have it in db, this is a simple add.</span>
		<span class="n">db</span><span class="p">.</span><span class="n">Cart</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">newCart</span><span class="p">);</span>
	<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>After querying a database and finding a record, we know that EF is already tracking the existing object. We then get an entry object of the tracked entity and call attachedEntry.<code class="language-plaintext highlighter-rouge">CurrentValues.SetValues</code> to update it with new values. This method works like an auto mapper and updates scalar properties from the passed in object. Also if the property values is different from the original, it sets the property state to be modified.</p>

<p>That works, but requires an extra database call to get an existing record. There is also a way to do that without an extra query.</p>

<h3 id="not-performing-an-extra-database-call-and-checking-local-context">Not Performing An Extra Database Call And Checking Local Context</h3>

<p>There are times when you know for fact an entity is already in the database. An example would be when a database generated id of your object is not set to zero or default. In that situation you can save an extra call by querying the local context first. If an entity does exist in the local context you perform a similar update with attachedEntry.<code class="language-plaintext highlighter-rouge">CurrentValues.SetValues</code>, and if it does not exist, you can modify a state of your detached object to modified, which would attach the object and update the database.</p>

<p>For example, when I know that the cart id is not zero, that means it already exists in the database:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span><span class="p">(</span><span class="n">newCart</span><span class="p">.</span><span class="n">Id</span> <span class="p">&gt;</span> <span class="m">0</span><span class="p">)</span> <span class="c1">// Id already assigned, need to update.</span>
<span class="p">{</span>
	<span class="c1">//We query local context first to see if it's there.</span>
	<span class="kt">var</span> <span class="n">attachedEntity</span> <span class="p">=</span> <span class="n">db</span><span class="p">.</span><span class="n">Carts</span><span class="p">.</span><span class="n">Local</span><span class="p">.</span><span class="nf">Find</span><span class="p">(</span><span class="n">newCart</span><span class="p">.</span><span class="n">Id</span><span class="p">);</span>

	<span class="c1">//We have it in the context, need to update.</span>
	<span class="k">if</span> <span class="p">(</span><span class="n">attachedEntity</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
		<span class="kt">var</span> <span class="n">attachedEntry</span> <span class="p">=</span> <span class="n">_context</span><span class="p">.</span><span class="nf">Entry</span><span class="p">(</span><span class="n">attachedEntity</span><span class="p">);</span>
		<span class="n">attachedEntry</span><span class="p">.</span><span class="n">CurrentValues</span><span class="p">.</span><span class="nf">SetValues</span><span class="p">(</span><span class="n">newCart</span><span class="p">);</span>
	<span class="p">}</span>
	<span class="k">else</span>
	<span class="p">{</span>
		<span class="c1">//If it's not found locally, we can attach it by setting state to modified.</span>
		<span class="c1">//This would result in a SQL update statement for all fields</span>
		<span class="c1">//when SaveChanges is called.</span>
		<span class="kt">var</span> <span class="n">entry</span> <span class="p">=</span> <span class="n">db</span><span class="p">.</span><span class="nf">Entry</span><span class="p">(</span><span class="n">newCart</span><span class="p">);</span>
		<span class="n">entry</span><span class="p">.</span><span class="n">State</span> <span class="p">=</span> <span class="n">EntityState</span><span class="p">.</span><span class="n">Modified</span><span class="p">;</span>
	<span class="p">}</span>
<span class="p">}</span>
<span class="k">else</span>
<span class="p">{</span>
	<span class="c1">//This is a simple add since we don't have it in db.</span>
	<span class="n">db</span><span class="p">.</span><span class="n">Cart</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">newCart</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>There is a small difference when you query the database first. EF knows which values have been modified an only those specific value. On the other hand, when you are blindly attaching modified entity, EF doesn’t know what fields have changes and performs an update on all fields.</p>

<h3 id="it-works-but-not-fully">It Works, But Not Fully…</h3>

<p>When you call <code class="language-plaintext highlighter-rouge">CurrentValues.SetValues(newCart)</code> it will update all scalar properties on your newCart object and set them to modified. However, navigation properties would not get the same respect. As of today EF does not support of full object graph merging, and leaves that for you to manage on your own. So if you have newCart.Customer navigational property it would not get updated. It’s <a href="https://entityframework.codeplex.com/workitem/864">the second most requested feature</a> for EF at the moment, so I think they would add it in the future release.</p>

<p>So for now you have to manually call <code class="language-plaintext highlighter-rouge">SetValues</code> on all your navigational properties in order for them to be updated. There are also <a href="https://github.com/refactorthis/GraphDiff">other solutions</a> that people have written that might help with updating a full graph.</p>

<p>Finally, if you object graph is not very large, you can get away with getting <code class="language-plaintext highlighter-rouge">DbEntityEntry</code> and calling <code class="language-plaintext highlighter-rouge">SetValues</code> on each navigational property. But if you do have a large graph and want something automatic I would try something like GraphDiff first.</p>

										
					<p>Posted in: entity-framework</p>
						
				
					<p>Tagged with: c#, entity-framework, code-first, and detached-objects</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/entity-framework/2013/12/23/entity-framework-updating-database-from-detached-objects/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/entity-framework/2013/12/23/entity-framework-updating-database-from-detached-objects/]]></guid>
		<pubDate>2013-12-23T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Book Review: E-Myth Revisited]]></title>
		<description>
			<![CDATA[
				<p>As a part of my transition from “wantrepreneuer” to entrepreneur, I’ve
been indulging in a great amount of business and motivational content. While on my way to work, I was listening to one of my favorite podcasts, <a href="http://www.entrepreneuronfire.com/">The Entrepreneur On Fire</a>. One of the guests recommended a book that he said completely shifted his mindset about business and put all the pieces together. It got me interested, so I picked up a copy from audible.com. This post is dedicated to the review of that audio book, <a href="http://www.amazon.com/gp/product/0887307280/ref=as_li_ss_tl?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0887307280&amp;linkCode=as2&amp;tag=sermassblo-20">The E-Myth
Revisited: Why Most Small Businesses Don’t Work and What to Do About It</a>. 
The following is a summary of the concepts that I thought were valuable and my reflections on those ideas.</p>


				<p>As a part of my transition from “wantrepreneuer” to entrepreneur, I’ve
been indulging in a great amount of business and motivational content. While on my way to work, I was listening to one of my favorite podcasts, <a href="http://www.entrepreneuronfire.com/">The Entrepreneur On Fire</a>. One of the guests recommended a book that he said completely shifted his mindset about business and put all the pieces together. It got me interested, so I picked up a copy from audible.com. This post is dedicated to the review of that audio book, <a href="http://www.amazon.com/gp/product/0887307280/ref=as_li_ss_tl?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0887307280&amp;linkCode=as2&amp;tag=sermassblo-20">The E-Myth
Revisited: Why Most Small Businesses Don’t Work and What to Do About It</a>. 
The following is a summary of the concepts that I thought were valuable and my reflections on those ideas.</p>

<h3 id="three-critical-roles">Three Critical Roles</h3>
<p>In order to create a business that’s going to stand the test of time and continue growing, you need to have the following three roles: Entrepreneur, Manager, and Technician. All three must be equal in the amount of strength, energy, and time devoted to it. The entrepreneur does the strategic thinking, planning, innovating, and has a vision for the future. The manager makes sure the established process is followed; she makes sure stuff gets done and brings order to the chaos. The technician works on the product itself.</p>

<p>Because software engineers are great at building things, we don’t necessarily notice or pay enough attention to the lack of other equally important roles in our business. We concentrate almost all of our energy on building things, which is only a one third of a successful business.</p>

<h3 id="work-on-your-business-rather-than-in-it">Work <em>On</em> Your Business Rather Than <em>In</em> It</h3>
<p>When you work in your business, you become self-employed. Working on your business means developing it and creating a system so that you can leverage other people’s time and grow your business. The system has to be well-established and easy enough to be followed by your future employees.</p>

<p>This is where I have a lot to learn. While working on the idea, I really need to put together a list of things that can be completed by other people and not try to do everything myself. Even development work can be outsourced. I understand it won’t be as good as something that I would write, but I think it’s up to me to create a system that will have those quality checks built in. As an entrepreneur, there must be other more important tasks like talking to potential customers and figuring out their pain points rather than creating a perfect data access layer.</p>

<h3 id="divide-roles-and-assign-accountability">Divide Roles and Assign Accountability</h3>

<p>When starting a new venture, it’s important to write down all the positions that you envision for your business as it matures. For example, you will have a Chief Executive Officer, a Chief Operating Officer, a Vice President of Sales, Vice President of Marketing, Vice President of Operations, and then you will have your managers and other staff. Once you have all those positions written down, you assign people to be responsible for those roles. You might end up with 12 or more roles. If it’s just you and your partner, then each of you will have to assume many roles. The point is to divide the roles and hold everyone accountable. So, if one of your roles is V.P. of Marketing, then it’s your responsibility to bring customers in the door, and you have all the decision-making ability in that domain. It is also important to have a different mindset when performing a particular job; you must make a mental shift and think to yourself that right now I’m performing job x and from that position I’ll be making my decisions and taking action.</p>

<p>When your business starts to grow, you will slowly hire people to handle some of your responsibilities, so you will no longer be responsible for them.</p>

<p>To ensure that I don’t make the same mistake twice, I will work on making sure that roles are clearly divided when I start a new venture. I’ve had many experiences starting with partners and arguing over many different subjects. Now I see that the problem was that we didn’t have clearly established roles and people assigned. If V.P. of Marketing is your role, then it’s your final decision—not the guy who does your development work—on how you want to send out those email campaigns. Finally, if you are not contributing efficiently in your assigned job, you need to be fired or replaced in that role.</p>

<h3 id="create-a-system-for-average-skills">Create a System for Average Skills</h3>
<p>If your business depends on a person who is a genius, then you really can’t replace that person, and if he or she leaves, you would be out of business. Building a business in a way that enables an average person to perform a job well is very important because now you can hire anyone and your quality won’t suffer. You add safety nets and create checklists to ensure quality is met.</p>

<h3 id="focus-on-building-a-business-rather-than-building-a-product">Focus on Building a Business Rather Than Building a Product</h3>
<p>Building a system is more important than building a product. A successful business can build many different products and then change them to adapt to the market. If you lock yourself into a specific product, then you are really at a disadvantage because if the market shifts, you will be out of your job.</p>


										
					<p>Posted in: book-review</p>
						
				
					<p>Tagged with: entrepreneur</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/book-review/2013/10/29/book-review-e-myth-revisited/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/book-review/2013/10/29/book-review-e-myth-revisited/]]></guid>
		<pubDate>2013-10-29T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Going Database Free Feels Great]]></title>
		<description>
			<![CDATA[
				<h3 id="a-new-fresh-look-at-old-and-boring">A New, Fresh Look at Old and Boring</h3>

<p>I get excited when playing with frameworks that are different and challenging to a widely-accepted view on the subject at hand. One of those commonly accepted notions is that in order to build a content management system (CMS), you need a web server and a database. One guy who challenged that notion is Tom Preston-Werner who, in his original article <a href="http://tom.preston-werner.com/2008/11/17/blogging-like-a-hacker.html">“Blogging Like a Hacker”</a>, set out to fix his frustrations with existing systems. He wrote:</p>

<blockquote>
  <p>I was tired of complicated blogging engines like WordPress and Mephisto. I wanted to write great posts, not style a zillion template pages, moderate comments all day long, and constantly lag behind the latest software release.</p>
</blockquote>

<p>He broke down the problem and realized that the core of the platform is your content, your layout, and the templating engine that will allow you to format and display your content. A simple, genius solution that he came up with is a static site generator, a project named <a href="http://jekyllrb.com/">Jekyll</a> that will take your posts in the form of <a href="http://daringfireball.net/projects/markdown/">markdown</a> files and run them through a generator that converts your layout and templates into a fully-generated static site. You can take that and host it anywhere you like because it’s just a simple site with static files.</p>

<h3 id="jekyll-a-perfect-fit">Jekyll: A Perfect Fit</h3>

<h4 id="markdown-format">Markdown Format</h4>

<p>I already love markdown format. I think it fits perfectly with the web. It allows you to craft simple web pages without HTML getting in your way, and it’s unified. There are now numerous editors that support markdown, so you get to choose the one you like rather than get stuck with what your CMS or blogging platform has to offer. In addition, your blog posts are physical text files that you can save in source control or back up in something like Dropbox. And if you ever decide to switch platforms, you can easily take and import those files to the new and shiny thing.</p>

<h4 id="simple-html-layouts">Simple HTML Layouts</h4>

<p>You can create your own simple HTML files and drop Liquid template variables to display the content. Super simple and powerful.</p>

<p>Here is an example of a post page with template tags.</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"home entry"</span><span class="nt">&gt;</span>
  <span class="nt">&lt;h1&gt;</span>{{ page.title }}<span class="nt">&lt;/h1&gt;</span>
  <span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">"date"</span><span class="nt">&gt;</span>{{ page.date | date_to_long_string }}<span class="nt">&lt;/span&gt;</span>
  {{ content }} ...
<span class="nt">&lt;/div&gt;</span>
</code></pre></div></div>

<p>The page tags are also custom, and you can define your own. It’s as flexible as you can imagine. Here is an example:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">---</span>
<span class="na">layout</span><span class="pi">:</span> <span class="s">post</span>
<span class="na">title</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Going</span><span class="nv"> </span><span class="s">Database</span><span class="nv"> </span><span class="s">Free</span><span class="nv"> </span><span class="s">Feels</span><span class="nv"> </span><span class="s">Great"</span>
<span class="na">tags</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">jekyll"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">cms"</span><span class="pi">]</span>
<span class="nn">---</span>

</code></pre></div></div>

<p>The date comes from the file name. Jekyll uses filename convention to pull the post date, so your post has to start with a date, for example: <code class="language-plaintext highlighter-rouge">2013-09-21-myblogpost.html.md</code></p>

<p>You can also generate sitemap and feed files, as well as define your own URL structure, and much more.</p>

<h4 id="super-cheap">Super cheap</h4>

<p>Did I mention that it’s super cheap to host a static site because you don’t need that fancy web server and database? All you need is an Amazon S3 account, and it will cost you pennies every month to run your site. You can just as easily host your site on Github for free.</p>

<h4 id="unlimited-traffic">Unlimited traffic</h4>

<p>How many times have you seen articles on Hacker News that, when you click on them, give you a nice 500-page error? That’s because their Wordpress on the shared hosting cannot handle all the traffic, and it just bogs down. Well, with static sites hosted in the cloud, you get unlimited traffic potential out of the box. It will serve almost any amount of traffic you can throw at it.</p>

<h4 id="secure-as-it-can-get-no-need-to-maintain">Secure as it can get, no need to maintain</h4>

<p>The beauty of the static site is that it’s simple and doesn’t have any programming logic. You don’t need to download any patches or security updates-it’s all just static HTML file goodness. Feels like we are back in 1996, and it’s awesome!</p>

<h4 id="static-site--cdn--fast">Static Site + CDN = FAST!</h4>

<p>Now to my favorite part. Being a performance freak, I have to admit that I decided to try it out because I knew that putting a CDN in front of the static site can make it really fast. I tried Amazon Cloud Front at first, but their speed was not very impressive. I was getting 600-700 ms response times, which is slower than the DiscountASP provider I was using before. I found <a href="http://www.maxcdn.com/">MaxCDN</a>, and they were just what I was looking for. I now see responses in the 50 ms or less range, and <a href="http://webpagetest.org">www.webpagetest.org</a> reports <a href="http://www.webpagetest.org/result/130923_BB_14G/1/details/">96/100</a> point results. It’s incredibly fast!! Here is a proof:</p>

<p><img src="/uploads/2013/09/webpagetest.png" alt="WebPageTest.org results" /></p>

<p>In addition, MaxCDN is doing a great job of zipping all of my content for me automatically.</p>

<h4 id="plugins">Plugins</h4>

<p>Jekyll has a big ecosystem, and there are a lot of plugins that are available. One in particular that I found very useful is <a href="https://github.com/ixti/jekyll-assets">jekyll-assets</a>. It’s very easy to set up, and it will take care of your minification, combining of css/js files, coffee script conversion, and cache busting, etc.</p>

<h4 id="what-about-comments">What about comments</h4>

<p>Aren’t comments something that your platform needs? How do you go about that? Well, that’s simple—you can install a 3rd party solution like <a href="http://disqus.com/">Disqus</a>, or you can roll your own with <a href="http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-data-html/">Javascript and Windows Azure mobile services</a>. In this day and age, anything that requires a database can be sprinkled on the page with Javascript, and 3rd parties will host your data very cheaply.</p>

<h3 id="extras">Extras</h3>

<p>I’ve created a <a href="https://github.com/mercury2269/S3Publish">simple publishing application</a> that you can run from the root of your Jekyll site. It will take contents of the site folder, figure out the differences between local copy and Amazon S3, and publish those differences to Amazon S3. Finally, it will purge cache in MaxCDN.</p>

<h3 id="summary">Summary</h3>

<p>By keeping things simple and ignoring prior biases, we gain incredible benefits that solve problems perfectly. I’m excited and looking forward to blogging on my new, shiny, statically-generated site.</p>

				<h3 id="a-new-fresh-look-at-old-and-boring">A New, Fresh Look at Old and Boring</h3>

<p>I get excited when playing with frameworks that are different and challenging to a widely-accepted view on the subject at hand. One of those commonly accepted notions is that in order to build a content management system (CMS), you need a web server and a database. One guy who challenged that notion is Tom Preston-Werner who, in his original article <a href="http://tom.preston-werner.com/2008/11/17/blogging-like-a-hacker.html">“Blogging Like a Hacker”</a>, set out to fix his frustrations with existing systems. He wrote:</p>

<blockquote>
  <p>I was tired of complicated blogging engines like WordPress and Mephisto. I wanted to write great posts, not style a zillion template pages, moderate comments all day long, and constantly lag behind the latest software release.</p>
</blockquote>

<p>He broke down the problem and realized that the core of the platform is your content, your layout, and the templating engine that will allow you to format and display your content. A simple, genius solution that he came up with is a static site generator, a project named <a href="http://jekyllrb.com/">Jekyll</a> that will take your posts in the form of <a href="http://daringfireball.net/projects/markdown/">markdown</a> files and run them through a generator that converts your layout and templates into a fully-generated static site. You can take that and host it anywhere you like because it’s just a simple site with static files.</p>

<h3 id="jekyll-a-perfect-fit">Jekyll: A Perfect Fit</h3>

<h4 id="markdown-format">Markdown Format</h4>

<p>I already love markdown format. I think it fits perfectly with the web. It allows you to craft simple web pages without HTML getting in your way, and it’s unified. There are now numerous editors that support markdown, so you get to choose the one you like rather than get stuck with what your CMS or blogging platform has to offer. In addition, your blog posts are physical text files that you can save in source control or back up in something like Dropbox. And if you ever decide to switch platforms, you can easily take and import those files to the new and shiny thing.</p>

<h4 id="simple-html-layouts">Simple HTML Layouts</h4>

<p>You can create your own simple HTML files and drop Liquid template variables to display the content. Super simple and powerful.</p>

<p>Here is an example of a post page with template tags.</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"home entry"</span><span class="nt">&gt;</span>
  <span class="nt">&lt;h1&gt;</span>{{ page.title }}<span class="nt">&lt;/h1&gt;</span>
  <span class="nt">&lt;span</span> <span class="na">class=</span><span class="s">"date"</span><span class="nt">&gt;</span>{{ page.date | date_to_long_string }}<span class="nt">&lt;/span&gt;</span>
  {{ content }} ...
<span class="nt">&lt;/div&gt;</span>
</code></pre></div></div>

<p>The page tags are also custom, and you can define your own. It’s as flexible as you can imagine. Here is an example:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">---</span>
<span class="na">layout</span><span class="pi">:</span> <span class="s">post</span>
<span class="na">title</span><span class="pi">:</span> <span class="s2">"</span><span class="s">Going</span><span class="nv"> </span><span class="s">Database</span><span class="nv"> </span><span class="s">Free</span><span class="nv"> </span><span class="s">Feels</span><span class="nv"> </span><span class="s">Great"</span>
<span class="na">tags</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">jekyll"</span><span class="pi">,</span> <span class="s2">"</span><span class="s">cms"</span><span class="pi">]</span>
<span class="nn">---</span>

</code></pre></div></div>

<p>The date comes from the file name. Jekyll uses filename convention to pull the post date, so your post has to start with a date, for example: <code class="language-plaintext highlighter-rouge">2013-09-21-myblogpost.html.md</code></p>

<p>You can also generate sitemap and feed files, as well as define your own URL structure, and much more.</p>

<h4 id="super-cheap">Super cheap</h4>

<p>Did I mention that it’s super cheap to host a static site because you don’t need that fancy web server and database? All you need is an Amazon S3 account, and it will cost you pennies every month to run your site. You can just as easily host your site on Github for free.</p>

<h4 id="unlimited-traffic">Unlimited traffic</h4>

<p>How many times have you seen articles on Hacker News that, when you click on them, give you a nice 500-page error? That’s because their Wordpress on the shared hosting cannot handle all the traffic, and it just bogs down. Well, with static sites hosted in the cloud, you get unlimited traffic potential out of the box. It will serve almost any amount of traffic you can throw at it.</p>

<h4 id="secure-as-it-can-get-no-need-to-maintain">Secure as it can get, no need to maintain</h4>

<p>The beauty of the static site is that it’s simple and doesn’t have any programming logic. You don’t need to download any patches or security updates-it’s all just static HTML file goodness. Feels like we are back in 1996, and it’s awesome!</p>

<h4 id="static-site--cdn--fast">Static Site + CDN = FAST!</h4>

<p>Now to my favorite part. Being a performance freak, I have to admit that I decided to try it out because I knew that putting a CDN in front of the static site can make it really fast. I tried Amazon Cloud Front at first, but their speed was not very impressive. I was getting 600-700 ms response times, which is slower than the DiscountASP provider I was using before. I found <a href="http://www.maxcdn.com/">MaxCDN</a>, and they were just what I was looking for. I now see responses in the 50 ms or less range, and <a href="http://webpagetest.org">www.webpagetest.org</a> reports <a href="http://www.webpagetest.org/result/130923_BB_14G/1/details/">96/100</a> point results. It’s incredibly fast!! Here is a proof:</p>

<p><img src="/uploads/2013/09/webpagetest.png" alt="WebPageTest.org results" /></p>

<p>In addition, MaxCDN is doing a great job of zipping all of my content for me automatically.</p>

<h4 id="plugins">Plugins</h4>

<p>Jekyll has a big ecosystem, and there are a lot of plugins that are available. One in particular that I found very useful is <a href="https://github.com/ixti/jekyll-assets">jekyll-assets</a>. It’s very easy to set up, and it will take care of your minification, combining of css/js files, coffee script conversion, and cache busting, etc.</p>

<h4 id="what-about-comments">What about comments</h4>

<p>Aren’t comments something that your platform needs? How do you go about that? Well, that’s simple—you can install a 3rd party solution like <a href="http://disqus.com/">Disqus</a>, or you can roll your own with <a href="http://www.windowsazure.com/en-us/develop/mobile/tutorials/get-started-with-data-html/">Javascript and Windows Azure mobile services</a>. In this day and age, anything that requires a database can be sprinkled on the page with Javascript, and 3rd parties will host your data very cheaply.</p>

<h3 id="extras">Extras</h3>

<p>I’ve created a <a href="https://github.com/mercury2269/S3Publish">simple publishing application</a> that you can run from the root of your Jekyll site. It will take contents of the site folder, figure out the differences between local copy and Amazon S3, and publish those differences to Amazon S3. Finally, it will purge cache in MaxCDN.</p>

<h3 id="summary">Summary</h3>

<p>By keeping things simple and ignoring prior biases, we gain incredible benefits that solve problems perfectly. I’m excited and looking forward to blogging on my new, shiny, statically-generated site.</p>

										
					<p>Posted in: jekyll</p>
						
				
					<p>Tagged with: jekyll, cms, and amazon-s3</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/jekyll/2013/09/24/going-database-free-feels-great/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/jekyll/2013/09/24/going-database-free-feels-great/]]></guid>
		<pubDate>2013-09-24T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[TDD - Understanding Is A Key To Success]]></title>
		<description>
			<![CDATA[
				<p>I’ve been practicing Test Driven Development (TDD) for a while and recently I learned that my tests were not really helping but actually becoming a huge burden. So for the past couple months I’ve been on a journey to truly master the TDD and I’m at the point now where I think I have a much better understanding of it. Through my struggles and discoveries with doing TDD comes out this blog post.</p>

<h3 id="why-do-we-need-tdd">Why Do We Need TDD</h3>

<p>TDD helps you to design your software components interactively. How does it help you? You write specifications or behaviors of your component and then your write a solution for that behavior and then you refactor to make the code clean. It’s extremely valuable in terms of providing safety net so you can have confidence while refactoring, and keep code clean and maintainable while not breaking desired specifications.</p>

<h3 id="its-important-to-understand-what-tdd-doesnt-do">It’s Important to Understand What TDD Doesn’t Do</h3>

<p>It doesn’t help you to find bugs, or regression test the whole system. It also doesn’t help you to test interaction between components or if your application is configured properly. There are other means to do that like automated integration tests with projects like Selenium.</p>

<h3 id="common-mistakes-or-when-safety-net-becomes-maintenance-hell">Common Mistakes or When Safety Net Becomes Maintenance Hell</h3>

<p>I believe almost all developers who start with TDD without guidance of an experienced TDD practitioner are destined to repeat common mistakes and fail. I’ve done this myself, even though I’ve read few TDD books and I thought I had it. Over the last 3 years I’ve been working on and off on a big and complex calculation functionality piece and used TDD to create a regression safety net. I wrote a huge amount of tests but when the time came to change functionality it didn’t go as smooth as planned. Any changes in the systems behavior would break a huge amount of tests and I could see that my tests were making things a lot more difficult instead of helping. So I went on to really understand TDD and truly learn it. I learned that writing a safety net that would actually help is not easy, requires a true understanding of the TDD, use of the design patterns to remove duplicatio,n and keeping unit tests DAMP (Descriptive and Meaninful Phrases).</p>

<h3 id="trully-understanding-tdd">Trully Understanding TDD</h3>

<p>The most important thing: Through each unit test you are specifying one behavior of the component and NOT testing methods of your class. With TDD your unit tests or your specifications become the documentation of how your components are expected to work. BDD tries to address this issue by changing the terminology, so you think in terms of behaviors rather than tests. But to me it’s all the same TDD just with different set of mind. When you truly understand TDD you would do BDD naturally. (I’m not an expert, these are just my understanding from what I learned and research)</p>

<p>Your components <strong>must be tested outside-in</strong>. Starting with the public API of your service for example. We’ll address some of the setup design patterns to make this possible because you will need to have a descent amount of setup code in order to test the whole component. And since this setup code needs to be in every test and it has to be easy to read and understand.</p>

<h3 id="keys-to-success">Keys to Success</h3>

<ul>
  <li>
    <p>Easy to read tests, your tests must be DAMP, they should be easy to read and understand. Extra special care need to be taken when writing test names because you want your test to fail in the future and you want a person who will read your test to understand exactly what happened without looking at internals. BDD addresses it with specifying Given When Then. With frameworks like xUnit I like to follow Subject_Scenario_Result in my method names.</p>
  </li>
  <li>
    <p>Tests must specify one thing, and one thing ONLY. Your unit tests verifies the behavior of only one specification. If you throw in assertions about unrelated behaviors you will soon discover that when a certain thing changes many of your tests will fail and you won’t be able to tell what went wrong, therefore defeating the purpose of unit tests.</p>
  </li>
  <li>
    <p>Outside in, you don’t want to test each individual method of your classes, but rather component’s public API, for example if you have a service that returns available shipping options and you a public interface for that method is CalculateShippingOptions you want to specify functionality through that method.</p>
  </li>
  <li>
    <p>Tests are really specifications or behaviors of your code. Think of it as documentation for your components.</p>
  </li>
  <li>
    <p>Mock all external components which functionality you are not trying to test.</p>
  </li>
  <li>
    <p>Treat your unit tests code as your production code, refactoring and keeping it clean is mandatory.</p>
  </li>
  <li>
    <p>Don’t over-specify your system. Only leave specs that are absolutely necessary in order for your component to work properly. 100% test coverage is meaningless it creates unnecessary work and maintenance burden and it’s not pragmatic.</p>
  </li>
</ul>

<h3 id="design-patterns-to-help">Design Patterns to Help</h3>

<p>Writing tests outside-in will require a lot of setup for each test and we want that setup code to be reused. BDD frameworks address it by reusing scenario sentences. And for TDD we have design patterns that help immensely.</p>

<h4 id="builder-pattern">Builder Pattern</h4>

<p>First pattern is the <a href="http://en.wikipedia.org/wiki/Builder_pattern">Builder Pattern </a>. When you are creating a scenario for your test, rather then setting up objects manually you should have a class that does that for you. For example you would usually build you objects manually like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">shippingOption</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">ShippingOption</span><span class="p">();</span>
<span class="n">shippingOption</span><span class="p">.</span><span class="n">ServiceLevel</span> <span class="p">=</span> <span class="m">888</span><span class="p">;</span>
<span class="n">shippingOption</span><span class="p">.</span><span class="n">Name</span> <span class="p">=</span> <span class="s">"Ground Shipping"</span>
<span class="p">...</span> <span class="n">etc</span>
<span class="kt">var</span> <span class="n">shippingOptions</span> <span class="p">=</span> <span class="k">new</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">ShippingOption</span><span class="p">&gt;();</span>
<span class="n">shippingOptions</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">shippingOption</span><span class="p">);</span>
</code></pre></div></div>

<p>That setup code can be huge, you can replace it with ShippingOptionsBuilder</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">ShippingOptionsBuilder</span>
<span class="p">{</span>
	<span class="k">private</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">ShippingOption</span><span class="p">&gt;</span> <span class="n">_options</span><span class="p">;</span>

	<span class="k">public</span> <span class="nf">ShippingOptionsBuilder</span><span class="p">()</span>
	<span class="p">{</span>
		<span class="n">_options</span> <span class="p">=</span> <span class="k">new</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">ShippingOptions</span><span class="p">&gt;();</span>
	<span class="p">}</span>

	<span class="k">public</span> <span class="n">ShippingOptionsBuilder</span> <span class="nf">AddGround</span><span class="p">()</span>
	<span class="p">{</span>
		<span class="kt">var</span> <span class="n">shippingOption</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">ShippingOption</span><span class="p">();</span>
		<span class="n">shippingOption</span><span class="p">.</span><span class="n">ServiceLevel</span> <span class="p">=</span> <span class="m">888</span><span class="p">;</span>
		<span class="n">shippingOption</span><span class="p">.</span><span class="n">Name</span> <span class="p">=</span> <span class="s">"Ground Shipping"</span>
		<span class="p">...</span><span class="n">etc</span>
		<span class="n">_options</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">shippingOption</span><span class="p">);</span>
		<span class="k">return</span> <span class="k">this</span><span class="p">;</span>
	<span class="p">}</span>
	<span class="k">public</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">ShippingOptions</span><span class="p">&gt;</span> <span class="nf">Build</span><span class="p">()</span>
	<span class="p">{</span>
		<span class="k">return</span> <span class="n">_options</span><span class="p">;</span>
	<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>So now to build your setup code you simply do this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">options</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">ShippingOptionsBuilder</span><span class="p">().</span><span class="nf">AddGround</span><span class="p">().</span><span class="nf">Build</span><span class="p">();</span>
</code></pre></div></div>

<p>And if you later on add other options like next day air you would simply add another method and call it like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">options</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">ShippingOptionsBuilder</span><span class="p">().</span><span class="nf">AddGround</span><span class="p">().</span><span class="nf">AddNextDayAir</span><span class="p">().</span><span class="nf">Build</span><span class="p">();</span>
</code></pre></div></div>

<p>It’s very simple but powerful, if your ShippingOption object changes your setup code would only change in one place rather than in many unit tests. And it also help with readability I can quickly read that line and see exactly what we have in our setup.</p>

<h4 id="suite-fixture-setup">Suite Fixture Setup</h4>

<p>A component might have multiple dependencies and we need a way to abstract the creation of the component so it can be easily changed later without us needing to modify a lot of tests. This is where suite fixture comes in to play.</p>

<p>Let’s say we have a ShippingCalculator that will be tested but it takes a couple of dependencies. We’ll create a fixture so it can be reused across tests.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">ShippingCalculatorFixture</span>
<span class="p">{</span>
	<span class="k">public</span> <span class="n">IShippingRepository</span> <span class="n">ShippingRepository</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
	<span class="k">public</span> <span class="n">IZipRepository</span> <span class="n">ZipRepository</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>

	<span class="k">public</span> <span class="nf">ShippingCalculatorFixture</span><span class="p">()</span>
	<span class="p">{</span>
		<span class="n">ShippingRepository</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Mock</span><span class="p">&lt;</span><span class="n">IShippingRepository</span><span class="p">&gt;().</span><span class="n">Object</span><span class="p">;</span>
		<span class="n">ZipRepository</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Mock</span><span class="p">&lt;</span><span class="n">ZipRepository</span><span class="p">&gt;().</span><span class="n">Object</span><span class="p">;</span>
	<span class="p">}</span>

	<span class="k">internal</span> <span class="n">ShippingCalculator</span> <span class="nf">CreateSut</span><span class="p">()</span>
	<span class="p">{</span>
		<span class="k">return</span> <span class="k">new</span> <span class="nf">ShippingCalculator</span><span class="p">(</span><span class="n">ShippingRepository</span><span class="p">,</span> <span class="n">ZipRepository</span><span class="p">);;</span>
	<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>So now in your setup you can create an instance of the fixture that will hold reference to your dependencies and also create a system under test component.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">SetUp</span><span class="p">]</span>
<span class="k">public</span> <span class="nf">Init</span><span class="p">()</span>
<span class="p">{</span>
	<span class="n">Fixture</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">ShippingCalculatorFixture</span><span class="p">();</span>
	<span class="n">ShippingCalculator</span> <span class="p">=</span> <span class="n">Fixture</span><span class="p">.</span><span class="nf">CreateSut</span><span class="p">();</span>
<span class="p">}</span>

<span class="p">[</span><span class="n">Test</span><span class="p">]</span>
<span class="k">public</span> <span class="nf">ExampleOfTheFixtureSetup</span><span class="p">()</span>
<span class="p">{</span>
	<span class="p">..</span><span class="n">your</span> <span class="n">arrange</span>
	<span class="c1">//Act</span>
	<span class="n">ShippingCalculator</span><span class="p">.</span><span class="nf">Calculate</span><span class="p">();</span>
	<span class="p">...</span> <span class="n">your</span> <span class="n">assert</span>
<span class="p">}</span>
</code></pre></div></div>

<p>For example we need in our test to mock out repository. It’s easy to access it through the fixture object that holds a reference to it.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">Test</span><span class="p">]</span>
<span class="k">public</span> <span class="nf">ExampleOfTheFixtureSetupWithDependency</span><span class="p">()</span>
<span class="p">{</span>
	<span class="p">..</span><span class="n">your</span> <span class="n">arrange</span>
	<span class="n">Mock</span><span class="p">.</span><span class="nf">Get</span><span class="p">(</span><span class="n">Fixture</span><span class="p">.</span><span class="n">ShippingRepository</span><span class="p">).</span><span class="nf">Setup</span><span class="p">(</span><span class="n">p</span> <span class="p">=&gt;</span> <span class="nf">SomeMethod</span><span class="p">()).</span><span class="nf">Returns</span><span class="p">(</span><span class="k">true</span><span class="p">);</span>

	<span class="c1">//Act</span>
	<span class="n">ShippingCalculator</span><span class="p">.</span><span class="nf">Calculate</span><span class="p">();</span>
	<span class="p">...</span> <span class="n">your</span> <span class="n">assert</span>
<span class="p">}</span>
</code></pre></div></div>

<p>You can also create an extension method</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">internal</span> <span class="k">static</span> <span class="k">class</span> <span class="nc">MockExtensions</span>
<span class="p">{</span>
		<span class="k">internal</span> <span class="k">static</span> <span class="n">Mock</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">GetMock</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="k">this</span> <span class="n">T</span> <span class="n">obj</span><span class="p">)</span> <span class="k">where</span> <span class="n">T</span> <span class="p">:</span> <span class="k">class</span>
		<span class="err">{</span>
			<span class="nc">return</span> <span class="n">Mock</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;.</span><span class="nf">Get</span><span class="p">(</span><span class="n">obj</span><span class="p">);</span>
		<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>So it can be simplified like this</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">Test</span><span class="p">]</span>
<span class="k">public</span> <span class="nf">ExampleOfTheFixtureSetupWithDependency</span><span class="p">()</span>
<span class="p">{</span>
	<span class="p">..</span><span class="n">your</span> <span class="n">arrange</span>
	<span class="n">Fixture</span><span class="p">.</span><span class="n">ShippingRepository</span><span class="p">.</span><span class="n">GetMock</span><span class="p">.</span><span class="nf">Setup</span><span class="p">(</span><span class="n">p</span> <span class="p">=&gt;</span> <span class="nf">SomeMethod</span><span class="p">()).</span><span class="nf">Returns</span><span class="p">(</span><span class="k">true</span><span class="p">);</span>

	<span class="c1">//Act</span>
	<span class="n">ShippingCalculator</span><span class="p">.</span><span class="nf">Calculate</span><span class="p">();</span>
	<span class="p">...</span> <span class="n">your</span> <span class="n">assert</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Some really good resources that helped me tremendously with my learning were:</p>

<p><a href="http://blog.stevensanderson.com/2009/08/24/writing-great-unit-tests-best-and-worst-practises/">http://blog.stevensanderson.com/2009/08/24/writing-great-unit-tests-best-and-worst-practises/</a></p>

<p><a href="http://blog.stevensanderson.com/2009/11/04/selective-unit-testing-costs-and-benefits/">http://blog.stevensanderson.com/2009/11/04/selective-unit-testing-costs-and-benefits/</a></p>

<p><a href="http://blog.ploeh.dk/2009/01/28/Zero-FrictionTDD/">http://blog.ploeh.dk/2009/01/28/Zero-FrictionTDD/</a></p>

<p>Great pluralsight course that goes deeper into patterns:
<a href="http://pluralsight.com/training/courses/TableOfContents?courseName=advanced-unit-testing">http://pluralsight.com/training/courses/TableOfContents?courseName=advanced-unit-testing</a></p>

<p>Good luck with your mastering Test Driven Development! Please let me know if I miss something or you might think I’m completely wrong.</p>

				<p>I’ve been practicing Test Driven Development (TDD) for a while and recently I learned that my tests were not really helping but actually becoming a huge burden. So for the past couple months I’ve been on a journey to truly master the TDD and I’m at the point now where I think I have a much better understanding of it. Through my struggles and discoveries with doing TDD comes out this blog post.</p>

<h3 id="why-do-we-need-tdd">Why Do We Need TDD</h3>

<p>TDD helps you to design your software components interactively. How does it help you? You write specifications or behaviors of your component and then your write a solution for that behavior and then you refactor to make the code clean. It’s extremely valuable in terms of providing safety net so you can have confidence while refactoring, and keep code clean and maintainable while not breaking desired specifications.</p>

<h3 id="its-important-to-understand-what-tdd-doesnt-do">It’s Important to Understand What TDD Doesn’t Do</h3>

<p>It doesn’t help you to find bugs, or regression test the whole system. It also doesn’t help you to test interaction between components or if your application is configured properly. There are other means to do that like automated integration tests with projects like Selenium.</p>

<h3 id="common-mistakes-or-when-safety-net-becomes-maintenance-hell">Common Mistakes or When Safety Net Becomes Maintenance Hell</h3>

<p>I believe almost all developers who start with TDD without guidance of an experienced TDD practitioner are destined to repeat common mistakes and fail. I’ve done this myself, even though I’ve read few TDD books and I thought I had it. Over the last 3 years I’ve been working on and off on a big and complex calculation functionality piece and used TDD to create a regression safety net. I wrote a huge amount of tests but when the time came to change functionality it didn’t go as smooth as planned. Any changes in the systems behavior would break a huge amount of tests and I could see that my tests were making things a lot more difficult instead of helping. So I went on to really understand TDD and truly learn it. I learned that writing a safety net that would actually help is not easy, requires a true understanding of the TDD, use of the design patterns to remove duplicatio,n and keeping unit tests DAMP (Descriptive and Meaninful Phrases).</p>

<h3 id="trully-understanding-tdd">Trully Understanding TDD</h3>

<p>The most important thing: Through each unit test you are specifying one behavior of the component and NOT testing methods of your class. With TDD your unit tests or your specifications become the documentation of how your components are expected to work. BDD tries to address this issue by changing the terminology, so you think in terms of behaviors rather than tests. But to me it’s all the same TDD just with different set of mind. When you truly understand TDD you would do BDD naturally. (I’m not an expert, these are just my understanding from what I learned and research)</p>

<p>Your components <strong>must be tested outside-in</strong>. Starting with the public API of your service for example. We’ll address some of the setup design patterns to make this possible because you will need to have a descent amount of setup code in order to test the whole component. And since this setup code needs to be in every test and it has to be easy to read and understand.</p>

<h3 id="keys-to-success">Keys to Success</h3>

<ul>
  <li>
    <p>Easy to read tests, your tests must be DAMP, they should be easy to read and understand. Extra special care need to be taken when writing test names because you want your test to fail in the future and you want a person who will read your test to understand exactly what happened without looking at internals. BDD addresses it with specifying Given When Then. With frameworks like xUnit I like to follow Subject_Scenario_Result in my method names.</p>
  </li>
  <li>
    <p>Tests must specify one thing, and one thing ONLY. Your unit tests verifies the behavior of only one specification. If you throw in assertions about unrelated behaviors you will soon discover that when a certain thing changes many of your tests will fail and you won’t be able to tell what went wrong, therefore defeating the purpose of unit tests.</p>
  </li>
  <li>
    <p>Outside in, you don’t want to test each individual method of your classes, but rather component’s public API, for example if you have a service that returns available shipping options and you a public interface for that method is CalculateShippingOptions you want to specify functionality through that method.</p>
  </li>
  <li>
    <p>Tests are really specifications or behaviors of your code. Think of it as documentation for your components.</p>
  </li>
  <li>
    <p>Mock all external components which functionality you are not trying to test.</p>
  </li>
  <li>
    <p>Treat your unit tests code as your production code, refactoring and keeping it clean is mandatory.</p>
  </li>
  <li>
    <p>Don’t over-specify your system. Only leave specs that are absolutely necessary in order for your component to work properly. 100% test coverage is meaningless it creates unnecessary work and maintenance burden and it’s not pragmatic.</p>
  </li>
</ul>

<h3 id="design-patterns-to-help">Design Patterns to Help</h3>

<p>Writing tests outside-in will require a lot of setup for each test and we want that setup code to be reused. BDD frameworks address it by reusing scenario sentences. And for TDD we have design patterns that help immensely.</p>

<h4 id="builder-pattern">Builder Pattern</h4>

<p>First pattern is the <a href="http://en.wikipedia.org/wiki/Builder_pattern">Builder Pattern </a>. When you are creating a scenario for your test, rather then setting up objects manually you should have a class that does that for you. For example you would usually build you objects manually like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">shippingOption</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">ShippingOption</span><span class="p">();</span>
<span class="n">shippingOption</span><span class="p">.</span><span class="n">ServiceLevel</span> <span class="p">=</span> <span class="m">888</span><span class="p">;</span>
<span class="n">shippingOption</span><span class="p">.</span><span class="n">Name</span> <span class="p">=</span> <span class="s">"Ground Shipping"</span>
<span class="p">...</span> <span class="n">etc</span>
<span class="kt">var</span> <span class="n">shippingOptions</span> <span class="p">=</span> <span class="k">new</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">ShippingOption</span><span class="p">&gt;();</span>
<span class="n">shippingOptions</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">shippingOption</span><span class="p">);</span>
</code></pre></div></div>

<p>That setup code can be huge, you can replace it with ShippingOptionsBuilder</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">ShippingOptionsBuilder</span>
<span class="p">{</span>
	<span class="k">private</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">ShippingOption</span><span class="p">&gt;</span> <span class="n">_options</span><span class="p">;</span>

	<span class="k">public</span> <span class="nf">ShippingOptionsBuilder</span><span class="p">()</span>
	<span class="p">{</span>
		<span class="n">_options</span> <span class="p">=</span> <span class="k">new</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">ShippingOptions</span><span class="p">&gt;();</span>
	<span class="p">}</span>

	<span class="k">public</span> <span class="n">ShippingOptionsBuilder</span> <span class="nf">AddGround</span><span class="p">()</span>
	<span class="p">{</span>
		<span class="kt">var</span> <span class="n">shippingOption</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">ShippingOption</span><span class="p">();</span>
		<span class="n">shippingOption</span><span class="p">.</span><span class="n">ServiceLevel</span> <span class="p">=</span> <span class="m">888</span><span class="p">;</span>
		<span class="n">shippingOption</span><span class="p">.</span><span class="n">Name</span> <span class="p">=</span> <span class="s">"Ground Shipping"</span>
		<span class="p">...</span><span class="n">etc</span>
		<span class="n">_options</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">shippingOption</span><span class="p">);</span>
		<span class="k">return</span> <span class="k">this</span><span class="p">;</span>
	<span class="p">}</span>
	<span class="k">public</span> <span class="n">List</span><span class="p">&lt;</span><span class="n">ShippingOptions</span><span class="p">&gt;</span> <span class="nf">Build</span><span class="p">()</span>
	<span class="p">{</span>
		<span class="k">return</span> <span class="n">_options</span><span class="p">;</span>
	<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>So now to build your setup code you simply do this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">options</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">ShippingOptionsBuilder</span><span class="p">().</span><span class="nf">AddGround</span><span class="p">().</span><span class="nf">Build</span><span class="p">();</span>
</code></pre></div></div>

<p>And if you later on add other options like next day air you would simply add another method and call it like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">options</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">ShippingOptionsBuilder</span><span class="p">().</span><span class="nf">AddGround</span><span class="p">().</span><span class="nf">AddNextDayAir</span><span class="p">().</span><span class="nf">Build</span><span class="p">();</span>
</code></pre></div></div>

<p>It’s very simple but powerful, if your ShippingOption object changes your setup code would only change in one place rather than in many unit tests. And it also help with readability I can quickly read that line and see exactly what we have in our setup.</p>

<h4 id="suite-fixture-setup">Suite Fixture Setup</h4>

<p>A component might have multiple dependencies and we need a way to abstract the creation of the component so it can be easily changed later without us needing to modify a lot of tests. This is where suite fixture comes in to play.</p>

<p>Let’s say we have a ShippingCalculator that will be tested but it takes a couple of dependencies. We’ll create a fixture so it can be reused across tests.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">ShippingCalculatorFixture</span>
<span class="p">{</span>
	<span class="k">public</span> <span class="n">IShippingRepository</span> <span class="n">ShippingRepository</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
	<span class="k">public</span> <span class="n">IZipRepository</span> <span class="n">ZipRepository</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>

	<span class="k">public</span> <span class="nf">ShippingCalculatorFixture</span><span class="p">()</span>
	<span class="p">{</span>
		<span class="n">ShippingRepository</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Mock</span><span class="p">&lt;</span><span class="n">IShippingRepository</span><span class="p">&gt;().</span><span class="n">Object</span><span class="p">;</span>
		<span class="n">ZipRepository</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Mock</span><span class="p">&lt;</span><span class="n">ZipRepository</span><span class="p">&gt;().</span><span class="n">Object</span><span class="p">;</span>
	<span class="p">}</span>

	<span class="k">internal</span> <span class="n">ShippingCalculator</span> <span class="nf">CreateSut</span><span class="p">()</span>
	<span class="p">{</span>
		<span class="k">return</span> <span class="k">new</span> <span class="nf">ShippingCalculator</span><span class="p">(</span><span class="n">ShippingRepository</span><span class="p">,</span> <span class="n">ZipRepository</span><span class="p">);;</span>
	<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>So now in your setup you can create an instance of the fixture that will hold reference to your dependencies and also create a system under test component.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">SetUp</span><span class="p">]</span>
<span class="k">public</span> <span class="nf">Init</span><span class="p">()</span>
<span class="p">{</span>
	<span class="n">Fixture</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">ShippingCalculatorFixture</span><span class="p">();</span>
	<span class="n">ShippingCalculator</span> <span class="p">=</span> <span class="n">Fixture</span><span class="p">.</span><span class="nf">CreateSut</span><span class="p">();</span>
<span class="p">}</span>

<span class="p">[</span><span class="n">Test</span><span class="p">]</span>
<span class="k">public</span> <span class="nf">ExampleOfTheFixtureSetup</span><span class="p">()</span>
<span class="p">{</span>
	<span class="p">..</span><span class="n">your</span> <span class="n">arrange</span>
	<span class="c1">//Act</span>
	<span class="n">ShippingCalculator</span><span class="p">.</span><span class="nf">Calculate</span><span class="p">();</span>
	<span class="p">...</span> <span class="n">your</span> <span class="n">assert</span>
<span class="p">}</span>
</code></pre></div></div>

<p>For example we need in our test to mock out repository. It’s easy to access it through the fixture object that holds a reference to it.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">Test</span><span class="p">]</span>
<span class="k">public</span> <span class="nf">ExampleOfTheFixtureSetupWithDependency</span><span class="p">()</span>
<span class="p">{</span>
	<span class="p">..</span><span class="n">your</span> <span class="n">arrange</span>
	<span class="n">Mock</span><span class="p">.</span><span class="nf">Get</span><span class="p">(</span><span class="n">Fixture</span><span class="p">.</span><span class="n">ShippingRepository</span><span class="p">).</span><span class="nf">Setup</span><span class="p">(</span><span class="n">p</span> <span class="p">=&gt;</span> <span class="nf">SomeMethod</span><span class="p">()).</span><span class="nf">Returns</span><span class="p">(</span><span class="k">true</span><span class="p">);</span>

	<span class="c1">//Act</span>
	<span class="n">ShippingCalculator</span><span class="p">.</span><span class="nf">Calculate</span><span class="p">();</span>
	<span class="p">...</span> <span class="n">your</span> <span class="n">assert</span>
<span class="p">}</span>
</code></pre></div></div>

<p>You can also create an extension method</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">internal</span> <span class="k">static</span> <span class="k">class</span> <span class="nc">MockExtensions</span>
<span class="p">{</span>
		<span class="k">internal</span> <span class="k">static</span> <span class="n">Mock</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">GetMock</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="k">this</span> <span class="n">T</span> <span class="n">obj</span><span class="p">)</span> <span class="k">where</span> <span class="n">T</span> <span class="p">:</span> <span class="k">class</span>
		<span class="err">{</span>
			<span class="nc">return</span> <span class="n">Mock</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;.</span><span class="nf">Get</span><span class="p">(</span><span class="n">obj</span><span class="p">);</span>
		<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>So it can be simplified like this</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">Test</span><span class="p">]</span>
<span class="k">public</span> <span class="nf">ExampleOfTheFixtureSetupWithDependency</span><span class="p">()</span>
<span class="p">{</span>
	<span class="p">..</span><span class="n">your</span> <span class="n">arrange</span>
	<span class="n">Fixture</span><span class="p">.</span><span class="n">ShippingRepository</span><span class="p">.</span><span class="n">GetMock</span><span class="p">.</span><span class="nf">Setup</span><span class="p">(</span><span class="n">p</span> <span class="p">=&gt;</span> <span class="nf">SomeMethod</span><span class="p">()).</span><span class="nf">Returns</span><span class="p">(</span><span class="k">true</span><span class="p">);</span>

	<span class="c1">//Act</span>
	<span class="n">ShippingCalculator</span><span class="p">.</span><span class="nf">Calculate</span><span class="p">();</span>
	<span class="p">...</span> <span class="n">your</span> <span class="n">assert</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Some really good resources that helped me tremendously with my learning were:</p>

<p><a href="http://blog.stevensanderson.com/2009/08/24/writing-great-unit-tests-best-and-worst-practises/">http://blog.stevensanderson.com/2009/08/24/writing-great-unit-tests-best-and-worst-practises/</a></p>

<p><a href="http://blog.stevensanderson.com/2009/11/04/selective-unit-testing-costs-and-benefits/">http://blog.stevensanderson.com/2009/11/04/selective-unit-testing-costs-and-benefits/</a></p>

<p><a href="http://blog.ploeh.dk/2009/01/28/Zero-FrictionTDD/">http://blog.ploeh.dk/2009/01/28/Zero-FrictionTDD/</a></p>

<p>Great pluralsight course that goes deeper into patterns:
<a href="http://pluralsight.com/training/courses/TableOfContents?courseName=advanced-unit-testing">http://pluralsight.com/training/courses/TableOfContents?courseName=advanced-unit-testing</a></p>

<p>Good luck with your mastering Test Driven Development! Please let me know if I miss something or you might think I’m completely wrong.</p>

										
					<p>Posted in: tdd</p>
						
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/tdd/understanding-is-key-to-success/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/tdd/understanding-is-key-to-success/]]></guid>
		<pubDate>2013-07-12T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Neat Features In MiniProfiler Library]]></title>
		<description>
			<![CDATA[
				<p>I’ve been reviewing <a href="http://www.miniprofiler.com">MiniProfiler</a> library source code and here are things that I though were unusual and neat. The reason why it caught my attention is because it’s not something that I use every day so I wanted to list it here. Also, I know that developers who I work with at my job don’t use these features also so they could probably find it interesting.</p>

<h3 id="grouping-related-files-in-visual-studio">Grouping related files in visual studio.</h3>

<p>I’ve noticed that classes that inherit from an interface are grouped together in the Visual Studio like this:</p>

<p><img src="/uploads/2013/05/visualstudio-grouped-objects.png" alt="" /></p>

<p>That is pretty neat, that way you don’t have to hunt around for all implementations of the interface and it’s all in one place.</p>

<p>By default Visual Studio groups related .aspx files like .cs and .designer.cs. If you look at the .csproj file files that are nested under the main file have a <code class="language-plaintext highlighter-rouge">DependenUpon</code> element under the the parent compile element.</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;Compile</span> <span class="na">Include=</span><span class="s">"SiteMap.aspx.designer.cs"</span><span class="nt">&gt;</span>
	<span class="nt">&lt;DependentUpon&gt;</span>SiteMap.aspx<span class="nt">&lt;/DependentUpon&gt;</span>
<span class="nt">&lt;/Compile&gt;</span>
</code></pre></div></div>

<p>By default Visual Studio does not have an option to group arbitrary files but it could easily be done by editing a csproj file. So it’s like a trick to work around default functionality. If you don’t want to manually update that file there is a small little plugin <a href="http://visualstudiogallery.msdn.microsoft.com/9d6ef0ce-2bef-4a82-9a84-7718caa5bb45">NestIn</a> that will do that for you.</p>

<h3 id="nested-settings-class">Nested Settings Class</h3>

<p>MiniProfiler has a nested static class so you can access settings by going to <code class="language-plaintext highlighter-rouge">MiniProfiler.Settings.SomeSetting</code>. I like that composition for settings and it’s pretty easy to do. All you have to do is to set your classes partial and then create a static Settings subclass underneath the partial class like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">partial</span> <span class="k">class</span> <span class="nc">MiniProfiler</span>
    <span class="p">{</span>
        <span class="c1">/// &lt;summary&gt;</span>
        <span class="c1">/// Various configuration properties.</span>
        <span class="c1">/// &lt;/summary&gt;</span>
        <span class="k">public</span> <span class="k">static</span> <span class="k">class</span> <span class="nc">Settings</span>
        <span class="p">{</span>
</code></pre></div></div>

<p>You can also group your settings class with your main class and that’s what is done in MiniProfiler.</p>

<h3 id="default-values">Default Values</h3>

<p><code class="language-plaintext highlighter-rouge">MiniProfiler.Settings</code> uses <code class="language-plaintext highlighter-rouge">DefaultValue</code> Attributes on properties. It’s important to note that this attribute does not initialize the property and that needs to be done separately.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="nf">DefaultValue</span><span class="p">(</span><span class="m">20</span><span class="p">)]</span>
<span class="k">public</span> <span class="k">static</span> <span class="kt">int</span> <span class="n">MaxUnviewedProfiles</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
</code></pre></div></div>

<p>Initialization happens using reflection in the static constructor of the Settings class.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">static</span> <span class="nf">Settings</span><span class="p">()</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">props</span> <span class="p">=</span> <span class="k">from</span> <span class="n">p</span> <span class="k">in</span> <span class="k">typeof</span><span class="p">(</span><span class="n">Settings</span><span class="p">).</span><span class="nf">GetProperties</span><span class="p">(</span><span class="n">BindingFlags</span><span class="p">.</span><span class="n">Public</span> <span class="p">|</span> <span class="n">BindingFlags</span><span class="p">.</span><span class="n">Static</span><span class="p">)</span>
<span class="k">let</span> <span class="n">t</span> <span class="p">=</span> <span class="k">typeof</span><span class="p">(</span><span class="n">DefaultValueAttribute</span><span class="p">)</span>
<span class="k">where</span> <span class="n">p</span><span class="p">.</span><span class="nf">IsDefined</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">inherit</span><span class="p">:</span> <span class="k">false</span><span class="p">)</span>
<span class="k">let</span> <span class="n">a</span> <span class="p">=</span> <span class="n">p</span><span class="p">.</span><span class="nf">GetCustomAttributes</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">inherit</span><span class="p">:</span> <span class="k">false</span><span class="p">).</span><span class="nf">Single</span><span class="p">()</span> <span class="k">as</span> <span class="n">DefaultValueAttribute</span>
<span class="k">select</span> <span class="k">new</span> <span class="p">{</span> <span class="n">PropertyInfo</span> <span class="p">=</span> <span class="n">p</span><span class="p">,</span> <span class="n">DefaultValue</span> <span class="p">=</span> <span class="n">a</span> <span class="p">};</span>

<span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">pair</span> <span class="k">in</span> <span class="n">props</span><span class="p">)</span>
<span class="p">{</span>
	<span class="n">pair</span><span class="p">.</span><span class="n">PropertyInfo</span><span class="p">.</span><span class="nf">SetValue</span><span class="p">(</span><span class="k">null</span><span class="p">,</span> <span class="n">Convert</span><span class="p">.</span><span class="nf">ChangeType</span><span class="p">(</span><span class="n">pair</span><span class="p">.</span><span class="n">DefaultValue</span><span class="p">.</span><span class="n">Value</span><span class="p">,</span> <span class="n">pair</span><span class="p">.</span><span class="n">PropertyInfo</span><span class="p">.</span><span class="n">PropertyType</span><span class="p">),</span> <span class="k">null</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">...</span>
</code></pre></div></div>

<p>I think that’s a nice way to initialize the properties. It keeps declaration and initialization together and easier to see. I wouldn’t do something like that if you had a small settings class and would just initialize in the constructor. But on the large classes it makes sense.</p>

<h3 id="hooking-up-routes">Hooking up Routes</h3>

<p>There is a single handler file that has a static method to initialize itself as a route. And it gets called when MiniProfiler sets up ProfilerProvider. What I found cool about this file is that it handles its own registration into routes.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">RegisterRoutes</span><span class="p">()</span>
<span class="p">{</span>
	<span class="kt">var</span> <span class="n">routes</span> <span class="p">=</span> <span class="n">RouteTable</span><span class="p">.</span><span class="n">Routes</span><span class="p">;</span>
	<span class="kt">var</span> <span class="n">handler</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">MiniProfilerHandler</span><span class="p">();</span>
	<span class="kt">var</span> <span class="n">prefix</span> <span class="p">=</span> <span class="n">MiniProfiler</span><span class="p">.</span><span class="n">Settings</span><span class="p">.</span><span class="n">RouteBasePath</span><span class="p">.</span><span class="nf">Replace</span><span class="p">(</span><span class="s">"~/"</span><span class="p">,</span> <span class="kt">string</span><span class="p">.</span><span class="n">Empty</span><span class="p">).</span><span class="nf">EnsureTrailingSlash</span><span class="p">();</span>

	<span class="k">using</span> <span class="p">(</span><span class="n">routes</span><span class="p">.</span><span class="nf">GetWriteLock</span><span class="p">())</span>
	<span class="p">{</span>
		<span class="kt">var</span> <span class="n">route</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">Route</span><span class="p">(</span><span class="n">prefix</span> <span class="p">+</span> <span class="s">"{filename}"</span><span class="p">,</span> <span class="n">handler</span><span class="p">)</span>
		<span class="p">{</span>
		<span class="c1">// we have to specify these, so no MVC route helpers will match, e.g. @Html.ActionLink("Home", "Index", "Home")</span>
		<span class="n">Defaults</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">RouteValueDictionary</span><span class="p">(</span><span class="k">new</span> <span class="p">{</span> <span class="n">controller</span> <span class="p">=</span> <span class="s">"MiniProfilerHandler"</span><span class="p">,</span> <span class="n">action</span> <span class="p">=</span> <span class="s">"ProcessRequest"</span> <span class="p">}),</span>
		<span class="n">Constraints</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">RouteValueDictionary</span><span class="p">(</span><span class="k">new</span> <span class="p">{</span> <span class="n">controller</span> <span class="p">=</span> <span class="s">"MiniProfilerHandler"</span><span class="p">,</span> <span class="n">action</span> <span class="p">=</span> <span class="s">"ProcessRequest"</span> <span class="p">})</span>
		<span class="p">};</span>

		<span class="c1">// put our routes at the beginning, like a boss</span>
		<span class="n">routes</span><span class="p">.</span><span class="nf">Insert</span><span class="p">(</span><span class="m">0</span><span class="p">,</span> <span class="n">route</span><span class="p">);</span>
	<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Keep in mind , in order for static files like .js and .css to get routed to the managed module you will need to turn on</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;system.webServer&gt;</span>
	<span class="nt">&lt;modules</span> <span class="na">runAllManagedModulesForAllRequests=</span><span class="s">"true"</span> <span class="nt">/&gt;</span>
<span class="nt">&lt;/system.webServer&gt;</span>
</code></pre></div></div>

<p>or if you don’t want to turn it on globally you can do it based on the specific url like this:</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;system.webServer&gt;</span>
	...
	<span class="nt">&lt;handlers&gt;</span>
	<span class="nt">&lt;add</span> <span class="na">name=</span><span class="s">"MiniProfiler"</span> <span class="na">path=</span><span class="s">"mini-profiler-resources/*"</span> <span class="na">verb=</span><span class="s">"*"</span> <span class="na">type=</span><span class="s">"System.Web.Routing.UrlRoutingModule"</span> <span class="na">resourceType=</span><span class="s">"Unspecified"</span> <span class="na">preCondition=</span><span class="s">"integratedMode"</span> <span class="nt">/&gt;</span>
	<span class="nt">&lt;/handlers&gt;</span>
<span class="nt">&lt;/system.webServer&gt;</span>
</code></pre></div></div>

<p>You can basically accomplish the same thing if you create an ashx handler and configure it in the handlers section. By setting up routes you can at least cover clients that have runAllManagedModulesForAllRequest set to true, so they would have one less thing to worry about. But it would also cause some frustration for people who don’t.</p>

<p>That’s it for now, I’ll list more as I’m working through it.</p>


				<p>I’ve been reviewing <a href="http://www.miniprofiler.com">MiniProfiler</a> library source code and here are things that I though were unusual and neat. The reason why it caught my attention is because it’s not something that I use every day so I wanted to list it here. Also, I know that developers who I work with at my job don’t use these features also so they could probably find it interesting.</p>

<h3 id="grouping-related-files-in-visual-studio">Grouping related files in visual studio.</h3>

<p>I’ve noticed that classes that inherit from an interface are grouped together in the Visual Studio like this:</p>

<p><img src="/uploads/2013/05/visualstudio-grouped-objects.png" alt="" /></p>

<p>That is pretty neat, that way you don’t have to hunt around for all implementations of the interface and it’s all in one place.</p>

<p>By default Visual Studio groups related .aspx files like .cs and .designer.cs. If you look at the .csproj file files that are nested under the main file have a <code class="language-plaintext highlighter-rouge">DependenUpon</code> element under the the parent compile element.</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;Compile</span> <span class="na">Include=</span><span class="s">"SiteMap.aspx.designer.cs"</span><span class="nt">&gt;</span>
	<span class="nt">&lt;DependentUpon&gt;</span>SiteMap.aspx<span class="nt">&lt;/DependentUpon&gt;</span>
<span class="nt">&lt;/Compile&gt;</span>
</code></pre></div></div>

<p>By default Visual Studio does not have an option to group arbitrary files but it could easily be done by editing a csproj file. So it’s like a trick to work around default functionality. If you don’t want to manually update that file there is a small little plugin <a href="http://visualstudiogallery.msdn.microsoft.com/9d6ef0ce-2bef-4a82-9a84-7718caa5bb45">NestIn</a> that will do that for you.</p>

<h3 id="nested-settings-class">Nested Settings Class</h3>

<p>MiniProfiler has a nested static class so you can access settings by going to <code class="language-plaintext highlighter-rouge">MiniProfiler.Settings.SomeSetting</code>. I like that composition for settings and it’s pretty easy to do. All you have to do is to set your classes partial and then create a static Settings subclass underneath the partial class like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">partial</span> <span class="k">class</span> <span class="nc">MiniProfiler</span>
    <span class="p">{</span>
        <span class="c1">/// &lt;summary&gt;</span>
        <span class="c1">/// Various configuration properties.</span>
        <span class="c1">/// &lt;/summary&gt;</span>
        <span class="k">public</span> <span class="k">static</span> <span class="k">class</span> <span class="nc">Settings</span>
        <span class="p">{</span>
</code></pre></div></div>

<p>You can also group your settings class with your main class and that’s what is done in MiniProfiler.</p>

<h3 id="default-values">Default Values</h3>

<p><code class="language-plaintext highlighter-rouge">MiniProfiler.Settings</code> uses <code class="language-plaintext highlighter-rouge">DefaultValue</code> Attributes on properties. It’s important to note that this attribute does not initialize the property and that needs to be done separately.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="nf">DefaultValue</span><span class="p">(</span><span class="m">20</span><span class="p">)]</span>
<span class="k">public</span> <span class="k">static</span> <span class="kt">int</span> <span class="n">MaxUnviewedProfiles</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
</code></pre></div></div>

<p>Initialization happens using reflection in the static constructor of the Settings class.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">static</span> <span class="nf">Settings</span><span class="p">()</span>
<span class="p">{</span>
<span class="kt">var</span> <span class="n">props</span> <span class="p">=</span> <span class="k">from</span> <span class="n">p</span> <span class="k">in</span> <span class="k">typeof</span><span class="p">(</span><span class="n">Settings</span><span class="p">).</span><span class="nf">GetProperties</span><span class="p">(</span><span class="n">BindingFlags</span><span class="p">.</span><span class="n">Public</span> <span class="p">|</span> <span class="n">BindingFlags</span><span class="p">.</span><span class="n">Static</span><span class="p">)</span>
<span class="k">let</span> <span class="n">t</span> <span class="p">=</span> <span class="k">typeof</span><span class="p">(</span><span class="n">DefaultValueAttribute</span><span class="p">)</span>
<span class="k">where</span> <span class="n">p</span><span class="p">.</span><span class="nf">IsDefined</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">inherit</span><span class="p">:</span> <span class="k">false</span><span class="p">)</span>
<span class="k">let</span> <span class="n">a</span> <span class="p">=</span> <span class="n">p</span><span class="p">.</span><span class="nf">GetCustomAttributes</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">inherit</span><span class="p">:</span> <span class="k">false</span><span class="p">).</span><span class="nf">Single</span><span class="p">()</span> <span class="k">as</span> <span class="n">DefaultValueAttribute</span>
<span class="k">select</span> <span class="k">new</span> <span class="p">{</span> <span class="n">PropertyInfo</span> <span class="p">=</span> <span class="n">p</span><span class="p">,</span> <span class="n">DefaultValue</span> <span class="p">=</span> <span class="n">a</span> <span class="p">};</span>

<span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="n">pair</span> <span class="k">in</span> <span class="n">props</span><span class="p">)</span>
<span class="p">{</span>
	<span class="n">pair</span><span class="p">.</span><span class="n">PropertyInfo</span><span class="p">.</span><span class="nf">SetValue</span><span class="p">(</span><span class="k">null</span><span class="p">,</span> <span class="n">Convert</span><span class="p">.</span><span class="nf">ChangeType</span><span class="p">(</span><span class="n">pair</span><span class="p">.</span><span class="n">DefaultValue</span><span class="p">.</span><span class="n">Value</span><span class="p">,</span> <span class="n">pair</span><span class="p">.</span><span class="n">PropertyInfo</span><span class="p">.</span><span class="n">PropertyType</span><span class="p">),</span> <span class="k">null</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">...</span>
</code></pre></div></div>

<p>I think that’s a nice way to initialize the properties. It keeps declaration and initialization together and easier to see. I wouldn’t do something like that if you had a small settings class and would just initialize in the constructor. But on the large classes it makes sense.</p>

<h3 id="hooking-up-routes">Hooking up Routes</h3>

<p>There is a single handler file that has a static method to initialize itself as a route. And it gets called when MiniProfiler sets up ProfilerProvider. What I found cool about this file is that it handles its own registration into routes.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">RegisterRoutes</span><span class="p">()</span>
<span class="p">{</span>
	<span class="kt">var</span> <span class="n">routes</span> <span class="p">=</span> <span class="n">RouteTable</span><span class="p">.</span><span class="n">Routes</span><span class="p">;</span>
	<span class="kt">var</span> <span class="n">handler</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">MiniProfilerHandler</span><span class="p">();</span>
	<span class="kt">var</span> <span class="n">prefix</span> <span class="p">=</span> <span class="n">MiniProfiler</span><span class="p">.</span><span class="n">Settings</span><span class="p">.</span><span class="n">RouteBasePath</span><span class="p">.</span><span class="nf">Replace</span><span class="p">(</span><span class="s">"~/"</span><span class="p">,</span> <span class="kt">string</span><span class="p">.</span><span class="n">Empty</span><span class="p">).</span><span class="nf">EnsureTrailingSlash</span><span class="p">();</span>

	<span class="k">using</span> <span class="p">(</span><span class="n">routes</span><span class="p">.</span><span class="nf">GetWriteLock</span><span class="p">())</span>
	<span class="p">{</span>
		<span class="kt">var</span> <span class="n">route</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">Route</span><span class="p">(</span><span class="n">prefix</span> <span class="p">+</span> <span class="s">"{filename}"</span><span class="p">,</span> <span class="n">handler</span><span class="p">)</span>
		<span class="p">{</span>
		<span class="c1">// we have to specify these, so no MVC route helpers will match, e.g. @Html.ActionLink("Home", "Index", "Home")</span>
		<span class="n">Defaults</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">RouteValueDictionary</span><span class="p">(</span><span class="k">new</span> <span class="p">{</span> <span class="n">controller</span> <span class="p">=</span> <span class="s">"MiniProfilerHandler"</span><span class="p">,</span> <span class="n">action</span> <span class="p">=</span> <span class="s">"ProcessRequest"</span> <span class="p">}),</span>
		<span class="n">Constraints</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">RouteValueDictionary</span><span class="p">(</span><span class="k">new</span> <span class="p">{</span> <span class="n">controller</span> <span class="p">=</span> <span class="s">"MiniProfilerHandler"</span><span class="p">,</span> <span class="n">action</span> <span class="p">=</span> <span class="s">"ProcessRequest"</span> <span class="p">})</span>
		<span class="p">};</span>

		<span class="c1">// put our routes at the beginning, like a boss</span>
		<span class="n">routes</span><span class="p">.</span><span class="nf">Insert</span><span class="p">(</span><span class="m">0</span><span class="p">,</span> <span class="n">route</span><span class="p">);</span>
	<span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Keep in mind , in order for static files like .js and .css to get routed to the managed module you will need to turn on</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;system.webServer&gt;</span>
	<span class="nt">&lt;modules</span> <span class="na">runAllManagedModulesForAllRequests=</span><span class="s">"true"</span> <span class="nt">/&gt;</span>
<span class="nt">&lt;/system.webServer&gt;</span>
</code></pre></div></div>

<p>or if you don’t want to turn it on globally you can do it based on the specific url like this:</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;system.webServer&gt;</span>
	...
	<span class="nt">&lt;handlers&gt;</span>
	<span class="nt">&lt;add</span> <span class="na">name=</span><span class="s">"MiniProfiler"</span> <span class="na">path=</span><span class="s">"mini-profiler-resources/*"</span> <span class="na">verb=</span><span class="s">"*"</span> <span class="na">type=</span><span class="s">"System.Web.Routing.UrlRoutingModule"</span> <span class="na">resourceType=</span><span class="s">"Unspecified"</span> <span class="na">preCondition=</span><span class="s">"integratedMode"</span> <span class="nt">/&gt;</span>
	<span class="nt">&lt;/handlers&gt;</span>
<span class="nt">&lt;/system.webServer&gt;</span>
</code></pre></div></div>

<p>You can basically accomplish the same thing if you create an ashx handler and configure it in the handlers section. By setting up routes you can at least cover clients that have runAllManagedModulesForAllRequest set to true, so they would have one less thing to worry about. But it would also cause some frustration for people who don’t.</p>

<p>That’s it for now, I’ll list more as I’m working through it.</p>


										
					<p>Posted in: miniprofiler</p>
						
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/miniprofiler/neat-things/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/miniprofiler/neat-things/]]></guid>
		<pubDate>2013-05-08T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Powershell Commands And Notes]]></title>
		<description>
			<![CDATA[
				<h3 id="get-help">Get-Help</h3>

<p>Powershell has great documentation inside of the shell, including examples. To turn on complete documentation add -full argument.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Get-Help [command name or topic]
Get-Help [command name or topic] -full
</code></pre></div></div>

<p>All powershell commands start with a verb and followed by a noun.</p>

<h3 id="get-command">Get-Command</h3>
<p>To get a list of commands:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Get-command
</code></pre></div></div>

<p>All commands related to process or noun</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-command -noun process
</code></pre></div></div>

<p>All commands that have a verb</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-command -verb get
</code></pre></div></div>

<h4 id="commands">Commands</h4>

<p>List of processes</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-process
</code></pre></div></div>

<p>To stop process and get help on the command, to see examples.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-help stop-process -full	
</code></pre></div></div>

<h4 id="what-if">What if?</h4>

<p>Almost all commands have -WhatIf argument, you can try a command before executing.</p>

<h4 id="pipe">Pipe</h4>

<table>
  <tbody>
    <tr>
      <td>One of the most powerful features. Take output and “Pipe” to the next command get-process</td>
      <td>sort-object</td>
    </tr>
  </tbody>
</table>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-process | sort-object -property Id
</code></pre></div></div>

<p>To see the list of all available properties from the command</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-process | get-member
</code></pre></div></div>

<h3 id="get-member">Get-Member</h3>

<p>Think of it when you have a question, what do I have, or what does this object have.</p>

<h4 id="filtering-and-blocks">Filtering and blocks</h4>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-process | where-object { $_.processname -eq 'powershell' }
</code></pre></div></div>

<p>Curly braces represent the filter block. The $_ represents the current item.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get process | where-object { $_.CPU -gt 1 } | foreach-object { $_.processname + " is over threashold " }
</code></pre></div></div>

<p>Outputting to the file</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get process | where-object { $_.CPU -gt 1 } | foreach-object { $_.processname + " is over threashold " } | out-file cpuinfo.txt
</code></pre></div></div>

<h3 id="execution-policy">Execution policy</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Get-ExecutionPolicy
</code></pre></div></div>

<p>You won’t be able to run any scripts if the scripts are restricted. 
To change execution policy.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Set-ExecutionPolicy remotesigned
</code></pre></div></div>

<h3 id="scripts">Scripts</h3>

<p>Once you have your execution policy set to remotesigned you can execute scripts that were created on the local machine. Save scripts with .ps1 extension. And script can be executed by providing a path to the script in the powershell. Like ./somescript.ps1. First dot stands for the current directory.</p>

<h3 id="great-topics-with-get-help">Great Topics with Get-Help</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Get-Help About_Execution_Policies
Get-Help About_Operators
Get-Help About_Common_Parameters
Get-Help About_Pipelines
Get-Help About_Scripts
Get-Help About_*
</code></pre></div></div>

<p>#Creating scripts to start applications and more.</p>

<p>Typing is better than clicking.
Automate tasks that are common with windows explorer.</p>

<p>Get your current location</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-location
$pwd
gl
</code></pre></div></div>

<p>To change your location:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set-location /.documents
chdir ..
cd ./documents
</code></pre></div></div>

<p>Push location will save your current location before moving to the new location. Once you are done use pop-location to get back to where you were before.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>push-location /
pushd ~/desktop
pop-location
popd
</code></pre></div></div>

<p>Common use is to control the location inside of the script</p>

<h3 id="navigation">Navigation</h3>

<p>Drive -&gt; Folder -&gt; file</p>

<p>Powershell treats many things like drives, for example registry, functions and system drives.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-psdrive
</code></pre></div></div>

<p>You can cd into certificate stores</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cd cert:
dir
</code></pre></div></div>

<p>Environment</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cd env:
dir
</code></pre></div></div>

<p>Registry</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cd hkcu:
dir
</code></pre></div></div>

<p>Push and pop work on custom drives.</p>

<h4 id="item-commands">Item commands</h4>
<p>This are very useful.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-command *item
</code></pre></div></div>

<h4 id="invoke-item">Invoke-item</h4>

<p>Equivalent as double click, will open with default registered file.
Alias</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ii message.txt
</code></pre></div></div>

<p>Will open folder if set to the folder.</p>

<p>http://bit.ly/psphere to add to the windows explorer open in powershell</p>

<h3 id="automating-projects">Automating projects</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cd ~/documents/project
push-location "~/documents/project/test"


function push-project( $project ) 
{ 
	# 1: navigate powershll to the project folder
	pushd "~/document/project/$project"
	# 2: open windows explorer at the project folder
	invoke-item .;
	# 3: open any solution found in the project folder
	invoke-item *.sln;
}
</code></pre></div></div>

<h3 id="profiles">Profiles</h3>

<p>Powershell saves scripts into the users profile</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$profile
</code></pre></div></div>

<p>Create a profile script file</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>new-item -type file -path $profile
invoke-item $profile
</code></pre></div></div>

<p>You can add the function to your user profile. And you can add an alias for the function</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>new-alias -name pp -value push-project
</code></pre></div></div>

<p>There are 4 profile scripts in powershell</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$profile | select *

Get-Help *Location
Get-Help *Item
Get-Help About_Providers
Get-Help About_Functions
Get-Help About_Profiles
</code></pre></div></div>

				<h3 id="get-help">Get-Help</h3>

<p>Powershell has great documentation inside of the shell, including examples. To turn on complete documentation add -full argument.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Get-Help [command name or topic]
Get-Help [command name or topic] -full
</code></pre></div></div>

<p>All powershell commands start with a verb and followed by a noun.</p>

<h3 id="get-command">Get-Command</h3>
<p>To get a list of commands:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Get-command
</code></pre></div></div>

<p>All commands related to process or noun</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-command -noun process
</code></pre></div></div>

<p>All commands that have a verb</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-command -verb get
</code></pre></div></div>

<h4 id="commands">Commands</h4>

<p>List of processes</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-process
</code></pre></div></div>

<p>To stop process and get help on the command, to see examples.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-help stop-process -full	
</code></pre></div></div>

<h4 id="what-if">What if?</h4>

<p>Almost all commands have -WhatIf argument, you can try a command before executing.</p>

<h4 id="pipe">Pipe</h4>

<table>
  <tbody>
    <tr>
      <td>One of the most powerful features. Take output and “Pipe” to the next command get-process</td>
      <td>sort-object</td>
    </tr>
  </tbody>
</table>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-process | sort-object -property Id
</code></pre></div></div>

<p>To see the list of all available properties from the command</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-process | get-member
</code></pre></div></div>

<h3 id="get-member">Get-Member</h3>

<p>Think of it when you have a question, what do I have, or what does this object have.</p>

<h4 id="filtering-and-blocks">Filtering and blocks</h4>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-process | where-object { $_.processname -eq 'powershell' }
</code></pre></div></div>

<p>Curly braces represent the filter block. The $_ represents the current item.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get process | where-object { $_.CPU -gt 1 } | foreach-object { $_.processname + " is over threashold " }
</code></pre></div></div>

<p>Outputting to the file</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get process | where-object { $_.CPU -gt 1 } | foreach-object { $_.processname + " is over threashold " } | out-file cpuinfo.txt
</code></pre></div></div>

<h3 id="execution-policy">Execution policy</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Get-ExecutionPolicy
</code></pre></div></div>

<p>You won’t be able to run any scripts if the scripts are restricted. 
To change execution policy.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Set-ExecutionPolicy remotesigned
</code></pre></div></div>

<h3 id="scripts">Scripts</h3>

<p>Once you have your execution policy set to remotesigned you can execute scripts that were created on the local machine. Save scripts with .ps1 extension. And script can be executed by providing a path to the script in the powershell. Like ./somescript.ps1. First dot stands for the current directory.</p>

<h3 id="great-topics-with-get-help">Great Topics with Get-Help</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Get-Help About_Execution_Policies
Get-Help About_Operators
Get-Help About_Common_Parameters
Get-Help About_Pipelines
Get-Help About_Scripts
Get-Help About_*
</code></pre></div></div>

<p>#Creating scripts to start applications and more.</p>

<p>Typing is better than clicking.
Automate tasks that are common with windows explorer.</p>

<p>Get your current location</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-location
$pwd
gl
</code></pre></div></div>

<p>To change your location:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>set-location /.documents
chdir ..
cd ./documents
</code></pre></div></div>

<p>Push location will save your current location before moving to the new location. Once you are done use pop-location to get back to where you were before.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>push-location /
pushd ~/desktop
pop-location
popd
</code></pre></div></div>

<p>Common use is to control the location inside of the script</p>

<h3 id="navigation">Navigation</h3>

<p>Drive -&gt; Folder -&gt; file</p>

<p>Powershell treats many things like drives, for example registry, functions and system drives.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-psdrive
</code></pre></div></div>

<p>You can cd into certificate stores</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cd cert:
dir
</code></pre></div></div>

<p>Environment</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cd env:
dir
</code></pre></div></div>

<p>Registry</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cd hkcu:
dir
</code></pre></div></div>

<p>Push and pop work on custom drives.</p>

<h4 id="item-commands">Item commands</h4>
<p>This are very useful.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get-command *item
</code></pre></div></div>

<h4 id="invoke-item">Invoke-item</h4>

<p>Equivalent as double click, will open with default registered file.
Alias</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ii message.txt
</code></pre></div></div>

<p>Will open folder if set to the folder.</p>

<p>http://bit.ly/psphere to add to the windows explorer open in powershell</p>

<h3 id="automating-projects">Automating projects</h3>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>cd ~/documents/project
push-location "~/documents/project/test"


function push-project( $project ) 
{ 
	# 1: navigate powershll to the project folder
	pushd "~/document/project/$project"
	# 2: open windows explorer at the project folder
	invoke-item .;
	# 3: open any solution found in the project folder
	invoke-item *.sln;
}
</code></pre></div></div>

<h3 id="profiles">Profiles</h3>

<p>Powershell saves scripts into the users profile</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$profile
</code></pre></div></div>

<p>Create a profile script file</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>new-item -type file -path $profile
invoke-item $profile
</code></pre></div></div>

<p>You can add the function to your user profile. And you can add an alias for the function</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>new-alias -name pp -value push-project
</code></pre></div></div>

<p>There are 4 profile scripts in powershell</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$profile | select *

Get-Help *Location
Get-Help *Item
Get-Help About_Providers
Get-Help About_Functions
Get-Help About_Profiles
</code></pre></div></div>

						
				
					<p>Tagged with: powershell</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/powershell/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/powershell/]]></guid>
		<pubDate>2013-04-14T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Git Notes and Commands]]></title>
		<description>
			<![CDATA[
				<h4 id="configuring">Configuring</h4>

<p>System-level configuration, for the entire PC
<code class="language-plaintext highlighter-rouge">c:\Program Files (x86)\Git\etc\gitconfig</code> or <code class="language-plaintext highlighter-rouge">~\.gitconfig</code> on MAC. Accessed by:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config <span class="nt">--system</span>
</code></pre></div></div>

<p>User-level configuration, stored in c:\users&lt;name&gt;.gitconfig</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config <span class="nt">--global</span>
</code></pre></div></div>

<p>Repository level configuration, stored .git/config</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config
</code></pre></div></div>

<p>Show all global options</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global --list
</code></pre></div></div>

<p>Setting properties on global</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global user.name
git config --global user.email
</code></pre></div></div>

<p>Configuring core editor</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global core.editor "'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
</code></pre></div></div>

<p>Configuring beyond compare</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global diff.tool bc3
git config --global difftool.bc3.path "c:/program files (x86)/beyond compare 3/bcomp.exe"
git config --global difftool.prompt false
git config --global merge.tool bc3
git config --global mergetool.bc3.path "c:/program files (x86)/beyond compare 3/bcomp.exe"
git config --global mergetool.prompt false
git config --global mergetool.keepbackup false
git config --global mergetool.keeptemporaries false
</code></pre></div></div>

<p>Configuring auto correct for the git commands</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global help.autocorrect 1
</code></pre></div></div>

<p>Use colors to show a lot of git information</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global color.ui auto
</code></pre></div></div>

<p>Auto carriage return line feed. False is for windows only will submit it as is. True will convert. Input is for mac, it will convert crlf into lf.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global core.autocrlf false
</code></pre></div></div>

<p>To remove a setting</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --unset user.name
</code></pre></div></div>

<p>You can also edit the config files yourself.</p>

<h4 id="working-locally">Working Locally</h4>

<h5 id="creating-a-local-repository">Creating a local repository</h5>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git init
git status
git add file.txt
git status
git commit
</code></pre></div></div>

<p>Look at the history and see the commit SHA:
git log</p>

<p>Add all modified/updated files</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get add -u
</code></pre></div></div>

<p>Commit with message</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git commit -m "Message"
</code></pre></div></div>

<p>To view the diffs between SHA1 hashes</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git diff dd2929..333322
</code></pre></div></div>

<p>Easier, latest commit is know as HEAD</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git diff HEAD~1..HEAD
git diff HEAD~1..
</code></pre></div></div>

<p>Add all files including untracked files</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git add -A
</code></pre></div></div>

<p>Stage as two different commits, add specific files and then commit.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git add file1.txt
git commit
</code></pre></div></div>

<h5 id="deleting-files">Deleting Files</h5>

<p>Delete the file first. Then stage the deletion with</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git add -u
</code></pre></div></div>

<p>Rename the file first then:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git add -A
</code></pre></div></div>

<p>To clear out unstaged changed to the README.txt file</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git checkout README.txt
</code></pre></div></div>

<p>To do a global clear out, and remove all unstaged changes
git reset –hard</p>

<p>To take out the last commit out of the repository and move back to the staging area, that way you can change that commit around</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git reset --soft HEAD~1
</code></pre></div></div>

<p>make changes</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git commit -m "reorganized commit"
</code></pre></div></div>

<p>To delete last commit and discard all the changes</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git reset --hard HEAD~1
</code></pre></div></div>

<h4 id="remove-unstaged-files">Remove unstaged files</h4>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git clean -n //what would it do
git clean -f //performs the operation
</code></pre></div></div>

<h5 id="gitignore">.gitignore</h5>

<p>Create a file that will list all of the files and directories that need to be omitted.</p>

<h4 id="working-remote">Working Remote</h4>

<p>clone repository</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git clone https://....
</code></pre></div></div>

<p>see list of commits</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git log
</code></pre></div></div>

<p>commits per line</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git log --oneline
</code></pre></div></div>

<p>see number of commits</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git log --oneline | wc -1
</code></pre></div></div>

<p>see the graph
git log –graph</p>

<p>Authors and commit messages</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git shortlog
</code></pre></div></div>

<p>Statistics about authors</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git shortlog -sne
</code></pre></div></div>

<p>Look at the specific commit</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git show HEAD
git show HEAD~10
git show 939393
</code></pre></div></div>

<p>Look at the remotes, origin is the git default where the repository came from</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git remote
git remote -v //verbose shows remote  urls
</code></pre></div></div>

<p>To see the repository config
cat .get/config</p>

<p>Display all the branches in the repository</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch
</code></pre></div></div>

<p>Display all the remote branches</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch -r
</code></pre></div></div>

<p>Look at the tags, known stable versions</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git tags
</code></pre></div></div>

<p>To add a remote repository, is commonly down to evaluate patches and pull requests into your project</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git remote add origin https://github.com/....
</code></pre></div></div>

<p>Once remote repository is added you can</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git fetch  //all
git fetch origin
</code></pre></div></div>

<p>to see changes on remote repository</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get log origin/master
</code></pre></div></div>

<p>Merge remote branch into the your current branch</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git merge origin/master
</code></pre></div></div>

<p>Fast forward means, replay commits that happen if there were no other changes and move the HEAD</p>

<p>Shortcut for <code class="language-plaintext highlighter-rouge">git fetch; git merge origin/master</code> is</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git pull
</code></pre></div></div>

<p>To set your branch to mirror some other remote branch, or remote tracking branch, or upstream tracking.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch --set-upstream master origin/master
</code></pre></div></div>

<p>If you can also specify without setting the remote like this. origin is the remote name and master is the remote branch.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git pull origin master
</code></pre></div></div>

<p>Git commit and add modified files together</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git commit -am "Some message"
</code></pre></div></div>

<p>Push your changes to the remote
git push</p>

<p>To remove the origin on the current branch</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git remote rm origin
</code></pre></div></div>

<p>to tag a current version, or stable point</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git tag v1.0.0
</code></pre></div></div>

<p>to create tag with the annotation</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git tag -a v1.0
</code></pre></div></div>

<p>To create a tag with the signature, signed with the password</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git tag -s v1.0
</code></pre></div></div>

<p>To verify a tag</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git tag -v v1.0
</code></pre></div></div>

<p>To push tags to remote (by default git would not push tags)</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git push --tags
</code></pre></div></div>

<h3 id="branching-merging-and-rebasing-with-git">Branching Merging and Rebasing with Git</h3>

<p>list of the commits on the current branch with a graph</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git log --graph --oneline
</code></pre></div></div>

<p>To visualize all branches, decorate applies the branch and tag information</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git lot --graph --oneline --all --decorate
</code></pre></div></div>

<p>Adding aliases in the git config</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global alias.lga "log --graph --oneline --all --decorate"
git config --global alias.lg "log --graph --all --pretty=format:'%C(bold)%h%Creset -%C(auto)%d%Creset %s %C(green dim)(%cr)%Creset %C(ul)&lt;%an&gt;'"
git lga
git lg
cat ~/.gitconfig
</code></pre></div></div>

<p>To Create a new branch
git branch feature1</p>

<p>Checkout new branch</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git checkout feature1
</code></pre></div></div>

<p>Big difference between branches and tags is that tags always stay on the same commit where branches move along.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git checkout master
</code></pre></div></div>

<p>Create a branch from a specific commit</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch fix1 9929292
git checkout fix1
</code></pre></div></div>

<p>To rename a branch is to move it</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch -m fix1 bug1234
</code></pre></div></div>

<p>To delete a branch</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch -d bug1234
</code></pre></div></div>

<p>To force delete a branch</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch -D bug1234
</code></pre></div></div>

<p>To create a branch and checkout (shortcut)
git checkout -b feature2</p>

<p>To get back a deleted branch. From a dangling commit, a commit that doesn’t have a home. These are kept for 30 days.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git reflog // log of all references
git branch bug1234 5a78c8b //with the first 8 of the SHA
</code></pre></div></div>

<p>To see head</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git show HEAD
</code></pre></div></div>

<p>Save half completed work is to stash it. Temporary holding area for the changes that are not committed to the branch.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git stash
git status
git stash list //holding area
git stash apply //to pull the changes back
git stash pop //applies it and removes it from the list
</code></pre></div></div>

<h4 id="merging">Merging</h4>

<p>Merge fiture1 into the current branch</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git merge feature1
git branch -d feature1 //deletes unused branch
</code></pre></div></div>

<p>Fast forward merge, is just moving the branch label into the new location.</p>

<p>To resolve conflicts using the merge tool</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git mergetool
</code></pre></div></div>

<p>Compare the repository to the staging area</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git diff --cached
</code></pre></div></div>

<h4 id="rebasing">Rebasing</h4>

<p>You can play back your commits on a certain branch rather creating a branch if there are no conflicts. Rebase current branch on top of master</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git rebase master
</code></pre></div></div>

<p>You can also use mergetool to solve merge conflicts and then continue</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git rebase --continue
</code></pre></div></div>

<h4 id="cherry-pick">Cherry Pick</h4>

<p>If you need to get one commit and apply it on top of a branch.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git cherrypick sks939ss
</code></pre></div></div>

<p>#Working with remote</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git fetch origin master //get latests
git push origin master
</code></pre></div></div>

<p>to push a branch to remote</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git push origin v1.0_fixes
</code></pre></div></div>

<p>list remote branches</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch -r
</code></pre></div></div>

<p>To delete remote branch, push to the remote without specifying the local name</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git push origin :v1.0_fixes_remote_branch_name
</code></pre></div></div>

<h3 id="complete-configuration-file">Complete Configuration File</h3>

<script src="https://gist.github.com/mercury2269/7e8d11ac55e507fc06e0.js"></script>


				<h4 id="configuring">Configuring</h4>

<p>System-level configuration, for the entire PC
<code class="language-plaintext highlighter-rouge">c:\Program Files (x86)\Git\etc\gitconfig</code> or <code class="language-plaintext highlighter-rouge">~\.gitconfig</code> on MAC. Accessed by:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config <span class="nt">--system</span>
</code></pre></div></div>

<p>User-level configuration, stored in c:\users&lt;name&gt;.gitconfig</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config <span class="nt">--global</span>
</code></pre></div></div>

<p>Repository level configuration, stored .git/config</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config
</code></pre></div></div>

<p>Show all global options</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global --list
</code></pre></div></div>

<p>Setting properties on global</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global user.name
git config --global user.email
</code></pre></div></div>

<p>Configuring core editor</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global core.editor "'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
</code></pre></div></div>

<p>Configuring beyond compare</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global diff.tool bc3
git config --global difftool.bc3.path "c:/program files (x86)/beyond compare 3/bcomp.exe"
git config --global difftool.prompt false
git config --global merge.tool bc3
git config --global mergetool.bc3.path "c:/program files (x86)/beyond compare 3/bcomp.exe"
git config --global mergetool.prompt false
git config --global mergetool.keepbackup false
git config --global mergetool.keeptemporaries false
</code></pre></div></div>

<p>Configuring auto correct for the git commands</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global help.autocorrect 1
</code></pre></div></div>

<p>Use colors to show a lot of git information</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global color.ui auto
</code></pre></div></div>

<p>Auto carriage return line feed. False is for windows only will submit it as is. True will convert. Input is for mac, it will convert crlf into lf.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global core.autocrlf false
</code></pre></div></div>

<p>To remove a setting</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --unset user.name
</code></pre></div></div>

<p>You can also edit the config files yourself.</p>

<h4 id="working-locally">Working Locally</h4>

<h5 id="creating-a-local-repository">Creating a local repository</h5>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git init
git status
git add file.txt
git status
git commit
</code></pre></div></div>

<p>Look at the history and see the commit SHA:
git log</p>

<p>Add all modified/updated files</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get add -u
</code></pre></div></div>

<p>Commit with message</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git commit -m "Message"
</code></pre></div></div>

<p>To view the diffs between SHA1 hashes</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git diff dd2929..333322
</code></pre></div></div>

<p>Easier, latest commit is know as HEAD</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git diff HEAD~1..HEAD
git diff HEAD~1..
</code></pre></div></div>

<p>Add all files including untracked files</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git add -A
</code></pre></div></div>

<p>Stage as two different commits, add specific files and then commit.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git add file1.txt
git commit
</code></pre></div></div>

<h5 id="deleting-files">Deleting Files</h5>

<p>Delete the file first. Then stage the deletion with</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git add -u
</code></pre></div></div>

<p>Rename the file first then:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git add -A
</code></pre></div></div>

<p>To clear out unstaged changed to the README.txt file</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git checkout README.txt
</code></pre></div></div>

<p>To do a global clear out, and remove all unstaged changes
git reset –hard</p>

<p>To take out the last commit out of the repository and move back to the staging area, that way you can change that commit around</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git reset --soft HEAD~1
</code></pre></div></div>

<p>make changes</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git commit -m "reorganized commit"
</code></pre></div></div>

<p>To delete last commit and discard all the changes</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git reset --hard HEAD~1
</code></pre></div></div>

<h4 id="remove-unstaged-files">Remove unstaged files</h4>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git clean -n //what would it do
git clean -f //performs the operation
</code></pre></div></div>

<h5 id="gitignore">.gitignore</h5>

<p>Create a file that will list all of the files and directories that need to be omitted.</p>

<h4 id="working-remote">Working Remote</h4>

<p>clone repository</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git clone https://....
</code></pre></div></div>

<p>see list of commits</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git log
</code></pre></div></div>

<p>commits per line</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git log --oneline
</code></pre></div></div>

<p>see number of commits</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git log --oneline | wc -1
</code></pre></div></div>

<p>see the graph
git log –graph</p>

<p>Authors and commit messages</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git shortlog
</code></pre></div></div>

<p>Statistics about authors</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git shortlog -sne
</code></pre></div></div>

<p>Look at the specific commit</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git show HEAD
git show HEAD~10
git show 939393
</code></pre></div></div>

<p>Look at the remotes, origin is the git default where the repository came from</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git remote
git remote -v //verbose shows remote  urls
</code></pre></div></div>

<p>To see the repository config
cat .get/config</p>

<p>Display all the branches in the repository</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch
</code></pre></div></div>

<p>Display all the remote branches</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch -r
</code></pre></div></div>

<p>Look at the tags, known stable versions</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git tags
</code></pre></div></div>

<p>To add a remote repository, is commonly down to evaluate patches and pull requests into your project</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git remote add origin https://github.com/....
</code></pre></div></div>

<p>Once remote repository is added you can</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git fetch  //all
git fetch origin
</code></pre></div></div>

<p>to see changes on remote repository</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>get log origin/master
</code></pre></div></div>

<p>Merge remote branch into the your current branch</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git merge origin/master
</code></pre></div></div>

<p>Fast forward means, replay commits that happen if there were no other changes and move the HEAD</p>

<p>Shortcut for <code class="language-plaintext highlighter-rouge">git fetch; git merge origin/master</code> is</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git pull
</code></pre></div></div>

<p>To set your branch to mirror some other remote branch, or remote tracking branch, or upstream tracking.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch --set-upstream master origin/master
</code></pre></div></div>

<p>If you can also specify without setting the remote like this. origin is the remote name and master is the remote branch.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git pull origin master
</code></pre></div></div>

<p>Git commit and add modified files together</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git commit -am "Some message"
</code></pre></div></div>

<p>Push your changes to the remote
git push</p>

<p>To remove the origin on the current branch</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git remote rm origin
</code></pre></div></div>

<p>to tag a current version, or stable point</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git tag v1.0.0
</code></pre></div></div>

<p>to create tag with the annotation</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git tag -a v1.0
</code></pre></div></div>

<p>To create a tag with the signature, signed with the password</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git tag -s v1.0
</code></pre></div></div>

<p>To verify a tag</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git tag -v v1.0
</code></pre></div></div>

<p>To push tags to remote (by default git would not push tags)</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git push --tags
</code></pre></div></div>

<h3 id="branching-merging-and-rebasing-with-git">Branching Merging and Rebasing with Git</h3>

<p>list of the commits on the current branch with a graph</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git log --graph --oneline
</code></pre></div></div>

<p>To visualize all branches, decorate applies the branch and tag information</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git lot --graph --oneline --all --decorate
</code></pre></div></div>

<p>Adding aliases in the git config</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git config --global alias.lga "log --graph --oneline --all --decorate"
git config --global alias.lg "log --graph --all --pretty=format:'%C(bold)%h%Creset -%C(auto)%d%Creset %s %C(green dim)(%cr)%Creset %C(ul)&lt;%an&gt;'"
git lga
git lg
cat ~/.gitconfig
</code></pre></div></div>

<p>To Create a new branch
git branch feature1</p>

<p>Checkout new branch</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git checkout feature1
</code></pre></div></div>

<p>Big difference between branches and tags is that tags always stay on the same commit where branches move along.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git checkout master
</code></pre></div></div>

<p>Create a branch from a specific commit</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch fix1 9929292
git checkout fix1
</code></pre></div></div>

<p>To rename a branch is to move it</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch -m fix1 bug1234
</code></pre></div></div>

<p>To delete a branch</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch -d bug1234
</code></pre></div></div>

<p>To force delete a branch</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch -D bug1234
</code></pre></div></div>

<p>To create a branch and checkout (shortcut)
git checkout -b feature2</p>

<p>To get back a deleted branch. From a dangling commit, a commit that doesn’t have a home. These are kept for 30 days.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git reflog // log of all references
git branch bug1234 5a78c8b //with the first 8 of the SHA
</code></pre></div></div>

<p>To see head</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git show HEAD
</code></pre></div></div>

<p>Save half completed work is to stash it. Temporary holding area for the changes that are not committed to the branch.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git stash
git status
git stash list //holding area
git stash apply //to pull the changes back
git stash pop //applies it and removes it from the list
</code></pre></div></div>

<h4 id="merging">Merging</h4>

<p>Merge fiture1 into the current branch</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git merge feature1
git branch -d feature1 //deletes unused branch
</code></pre></div></div>

<p>Fast forward merge, is just moving the branch label into the new location.</p>

<p>To resolve conflicts using the merge tool</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git mergetool
</code></pre></div></div>

<p>Compare the repository to the staging area</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git diff --cached
</code></pre></div></div>

<h4 id="rebasing">Rebasing</h4>

<p>You can play back your commits on a certain branch rather creating a branch if there are no conflicts. Rebase current branch on top of master</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git rebase master
</code></pre></div></div>

<p>You can also use mergetool to solve merge conflicts and then continue</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git rebase --continue
</code></pre></div></div>

<h4 id="cherry-pick">Cherry Pick</h4>

<p>If you need to get one commit and apply it on top of a branch.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git cherrypick sks939ss
</code></pre></div></div>

<p>#Working with remote</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git fetch origin master //get latests
git push origin master
</code></pre></div></div>

<p>to push a branch to remote</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git push origin v1.0_fixes
</code></pre></div></div>

<p>list remote branches</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git branch -r
</code></pre></div></div>

<p>To delete remote branch, push to the remote without specifying the local name</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>git push origin :v1.0_fixes_remote_branch_name
</code></pre></div></div>

<h3 id="complete-configuration-file">Complete Configuration File</h3>

<script src="https://gist.github.com/mercury2269/7e8d11ac55e507fc06e0.js"></script>


						
				
					<p>Tagged with: git</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/git/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/git/]]></guid>
		<pubDate>2013-04-14T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Single Page Applications - Exciting Next Step In Evolution]]></title>
		<description>
			<![CDATA[
				<h3 id="spas-bring-new-fresh-user-experience">SPAs bring new fresh user experience</h3>
<p>The web is constantly evolving. About 7 years ago we didn’t know what jQuery was and AJAX was mostly associated with the cleaning product. Now it’s 2013 and it is no longer enough to sprinkle simple AJAX calls to get some dynamic data without refreshing the page. Modern applications run completely in the browser and provide a very fast and intuitive user interface.  In addition, it creates a new user experience that makes it feel fresh and vibrant, while going back to standard web sites with postbacks feel clumsy and slow. No wonder new startups are embracing this concept. It gives you an edge and can make or break a company when dealing with competition.</p>

<p>We also see a rise of backend technologies that focus on returning JSON and embracing RESTful web services. One of the example is recent addition of the ASP.NET Web API framework from Microsoft. And of course a numerous amount of javascript frameworks for building SPAs. <a href="http://blog.stevensanderson.com/2012/08/01/rich-javascript-applications-the-seven-frameworks-throne-of-js-2012/.">Here is a list with comparison of many of them.</a></p>

<h3 id="new-concept-need-same-good-programming-principles">New concept, need same good programming principles</h3>

<p>Since we are moving away from simple javascript and stepping into the realm of building complex applications in the browser we must apply time tested design principles for building maintainable, testable and readable software. We want our applications to be easy to change and understand. And the user interface get changed more frequently than anything else. Therefore it’s extremely important to have good design, follow patterns and separate your concerns.</p>

<blockquote>
  <p>Any fool can write code that a
computer can understand. Good
programmers write code that humans can
understand.</p>
  <ul>
    <li>Martin Fowler</li>
  </ul>
</blockquote>

<p>Javascript libraries for building SPAs give you a nice starting point, but what I have discovered is that it leaves a lot of open questions and ability to shoot yourself in the foot when you don’t understand the concepts. There are however frameworks like EmberJs that will force you into doing things the predefined way, which would probably be a great starting point for beginners. But again it won’t give you as much flexibility of building a framework that works for you.</p>

<h3 id="foundation-ingridients">Foundation Ingridients</h3>

<p>So where do we start, how do we begin this journey of re-inventing ourselves. Well what do you do when you start learning a new language? I usually pick up a good book on that language and learn the basics.</p>

<h3 id="javascript-language">Javascript language</h3>
<p>Since Javascript is the language of SPAs you as developer cannot longer get aways with simple functions or jQuery selectors. Just like any language other language you need to give it full credit and pick up a book and learn how to compose your objects, modules, how inheritance works and so on. Luckily there are excellent books out there. One of them that I thought was straight to the point and a must read is:</p>

<p><a href="http://www.amazon.com/gp/product/0596806752/ref=as_li_ss_il?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0596806752&amp;linkCode=as2&amp;tag=sermassblo-20"><img border="0" src="http://ws.assoc-amazon.com/widgets/q?_encoding=UTF8&amp;ASIN=0596806752&amp;Format=_SL110_&amp;ID=AsinImage&amp;MarketPlace=US&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=sermassblo-20" /></a><img src="http://www.assoc-amazon.com/e/ir?t=sermassblo-20&amp;l=as2&amp;o=1&amp;a=0596806752" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<h4 id="learning-the-patterns">Learning the patterns</h4>
<p>After learning the language, if you are not familiar with MV* patterns used most SPAs you will need to learn and understand them in order to know where things go. It helps that patterns have already been discussed thoroughly for other UI frameworks that are similar to SPAs like WPF and Silverlight. So there are plenty of resources and solutions that already have been hashed out. <a href="http://devlicio.us/blogs/rob_eisenberg/">Rob Eisenberg</a> has compiled <a href="http://devlicio.us/blogs/rob_eisenberg/archive/2010/05/01/mvvm-study-interlude.aspx">a great list</a> of resource on learning the presentation patterns.</p>

<h4 id="unit-tests">Unit tests</h4>
<p>Once you know how to separate your concerns and not to mix DOM access code with application logic with you will be able to greatly improve your code quality and maintainability by writing unit tests. You can start by going through a list of articles on testing here http://superherojs.com/</p>

<h2 id="paying-your-dues-and-evolving">Paying your dues and evolving</h2>

<p>Once you pay your dues and learning Javascript language along with patterns and principle and unit testing you will have a good foundation to make a maintainable application that will be easy to change, understand and will stand the test of time.</p>

<p>Finally on a more general note we as developers must learn to evolve. What’s awesome is that all the good programming principles that you’ve learned over the years can be applied at everything. It comes down to learning new patterns and language. And patterns knowledge would last a lot longer than frameworks or even languages. I’m excited to step on this road of learning and discovering. Are you with me?</p>


				<h3 id="spas-bring-new-fresh-user-experience">SPAs bring new fresh user experience</h3>
<p>The web is constantly evolving. About 7 years ago we didn’t know what jQuery was and AJAX was mostly associated with the cleaning product. Now it’s 2013 and it is no longer enough to sprinkle simple AJAX calls to get some dynamic data without refreshing the page. Modern applications run completely in the browser and provide a very fast and intuitive user interface.  In addition, it creates a new user experience that makes it feel fresh and vibrant, while going back to standard web sites with postbacks feel clumsy and slow. No wonder new startups are embracing this concept. It gives you an edge and can make or break a company when dealing with competition.</p>

<p>We also see a rise of backend technologies that focus on returning JSON and embracing RESTful web services. One of the example is recent addition of the ASP.NET Web API framework from Microsoft. And of course a numerous amount of javascript frameworks for building SPAs. <a href="http://blog.stevensanderson.com/2012/08/01/rich-javascript-applications-the-seven-frameworks-throne-of-js-2012/.">Here is a list with comparison of many of them.</a></p>

<h3 id="new-concept-need-same-good-programming-principles">New concept, need same good programming principles</h3>

<p>Since we are moving away from simple javascript and stepping into the realm of building complex applications in the browser we must apply time tested design principles for building maintainable, testable and readable software. We want our applications to be easy to change and understand. And the user interface get changed more frequently than anything else. Therefore it’s extremely important to have good design, follow patterns and separate your concerns.</p>

<blockquote>
  <p>Any fool can write code that a
computer can understand. Good
programmers write code that humans can
understand.</p>
  <ul>
    <li>Martin Fowler</li>
  </ul>
</blockquote>

<p>Javascript libraries for building SPAs give you a nice starting point, but what I have discovered is that it leaves a lot of open questions and ability to shoot yourself in the foot when you don’t understand the concepts. There are however frameworks like EmberJs that will force you into doing things the predefined way, which would probably be a great starting point for beginners. But again it won’t give you as much flexibility of building a framework that works for you.</p>

<h3 id="foundation-ingridients">Foundation Ingridients</h3>

<p>So where do we start, how do we begin this journey of re-inventing ourselves. Well what do you do when you start learning a new language? I usually pick up a good book on that language and learn the basics.</p>

<h3 id="javascript-language">Javascript language</h3>
<p>Since Javascript is the language of SPAs you as developer cannot longer get aways with simple functions or jQuery selectors. Just like any language other language you need to give it full credit and pick up a book and learn how to compose your objects, modules, how inheritance works and so on. Luckily there are excellent books out there. One of them that I thought was straight to the point and a must read is:</p>

<p><a href="http://www.amazon.com/gp/product/0596806752/ref=as_li_ss_il?ie=UTF8&amp;camp=1789&amp;creative=390957&amp;creativeASIN=0596806752&amp;linkCode=as2&amp;tag=sermassblo-20"><img border="0" src="http://ws.assoc-amazon.com/widgets/q?_encoding=UTF8&amp;ASIN=0596806752&amp;Format=_SL110_&amp;ID=AsinImage&amp;MarketPlace=US&amp;ServiceVersion=20070822&amp;WS=1&amp;tag=sermassblo-20" /></a><img src="http://www.assoc-amazon.com/e/ir?t=sermassblo-20&amp;l=as2&amp;o=1&amp;a=0596806752" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" /></p>

<h4 id="learning-the-patterns">Learning the patterns</h4>
<p>After learning the language, if you are not familiar with MV* patterns used most SPAs you will need to learn and understand them in order to know where things go. It helps that patterns have already been discussed thoroughly for other UI frameworks that are similar to SPAs like WPF and Silverlight. So there are plenty of resources and solutions that already have been hashed out. <a href="http://devlicio.us/blogs/rob_eisenberg/">Rob Eisenberg</a> has compiled <a href="http://devlicio.us/blogs/rob_eisenberg/archive/2010/05/01/mvvm-study-interlude.aspx">a great list</a> of resource on learning the presentation patterns.</p>

<h4 id="unit-tests">Unit tests</h4>
<p>Once you know how to separate your concerns and not to mix DOM access code with application logic with you will be able to greatly improve your code quality and maintainability by writing unit tests. You can start by going through a list of articles on testing here http://superherojs.com/</p>

<h2 id="paying-your-dues-and-evolving">Paying your dues and evolving</h2>

<p>Once you pay your dues and learning Javascript language along with patterns and principle and unit testing you will have a good foundation to make a maintainable application that will be easy to change, understand and will stand the test of time.</p>

<p>Finally on a more general note we as developers must learn to evolve. What’s awesome is that all the good programming principles that you’ve learned over the years can be applied at everything. It comes down to learning new patterns and language. And patterns knowledge would last a lot longer than frameworks or even languages. I’m excited to step on this road of learning and discovering. Are you with me?</p>


										
					<p>Posted in: spa</p>
						
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/spa/introduction/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/spa/introduction/]]></guid>
		<pubDate>2013-03-26T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Semantic Versioning]]></title>
		<description>
			<![CDATA[
				<p>If you are using simple incremental versioning like v39, v40 and etc., you are missing out. In software world every aspect has been thoroughly thought through, has a meaning and adds some kind of value. One of those aspects is project versioning. Many companies I worked at didn’t really give any thought on that subject and “homebrewed” some kind of simple incremental system. Most of the time that system would simply increment the version without giving any other information. A much better approach is to have versioning as a precise structure or rules to the project. Where all developers that work on the project understand and can differentiate between major, minor and patch releases.</p>

<p>It’s not hard and you don’t have to look far and re-use something that already works. So I encourage you to take a look at the formalized document by the cofounder of github that precisely identifies <a href="http://semver.org/">semantic versioning</a>. Chances are next time you work on the open source project it will use the same system and you will be already familiar with it.</p>

<p>Enjoy.</p>


				<p>If you are using simple incremental versioning like v39, v40 and etc., you are missing out. In software world every aspect has been thoroughly thought through, has a meaning and adds some kind of value. One of those aspects is project versioning. Many companies I worked at didn’t really give any thought on that subject and “homebrewed” some kind of simple incremental system. Most of the time that system would simply increment the version without giving any other information. A much better approach is to have versioning as a precise structure or rules to the project. Where all developers that work on the project understand and can differentiate between major, minor and patch releases.</p>

<p>It’s not hard and you don’t have to look far and re-use something that already works. So I encourage you to take a look at the formalized document by the cofounder of github that precisely identifies <a href="http://semver.org/">semantic versioning</a>. Chances are next time you work on the open source project it will use the same system and you will be already familiar with it.</p>

<p>Enjoy.</p>


										
					<p>Posted in: programming</p>
						
				
					<p>Tagged with: programming-conecepts</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/programming/semantic-versioning/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/programming/semantic-versioning/]]></guid>
		<pubDate>2013-03-11T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Displaying MiniProfiler For Logged In Developers with MVC4]]></title>
		<description>
			<![CDATA[
				<p>ASP.NET MVC 4 introduced an important change in membership providers. Moving away from core membership to a more flexible and simpler <a href="http://weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx">SimpleMembershipProvider</a>.
Default “Internet Application” template initializes SimpleMembership by including an action filer InitializeSimpleMembership which gets gets added to the Account controller. So whenever you try to access account controller a filer would check if the SimpleMembershipInitializer was initialized and do the necessary work if needed.</p>

<p>In one of the applications I’m working on at the moment I wanted to only show MiniProfiler for logged in developers, so that required some changes to the default project structure. Since we want to have <a href="http://miniprofiler.com/">MiniProfiler</a> visible on the entire site we need to make sure that membership provider gets initialized for all controllers. One way is to add InitializeSimpleMembershipAttribute to the global filters, however that would require you to hit the page twice since the action attribute fires after the Application_PostAuthorizeRequest (where we will be checking Roles) and the provider would not be initialized on the first request.</p>

<p>I’ve opted out to move the initialization logic from Action attribute to the Application_Start() of the Global.asax file. Since that only fires once per application I thought it would be a better place for it. So it looks like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">MvcApplication</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Web</span><span class="p">.</span><span class="n">HttpApplication</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="k">void</span> <span class="nf">Application_Start</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="p">...</span>
       <span class="nf">InitMembership</span><span class="p">();</span>
    <span class="p">}</span>
    <span class="k">private</span> <span class="k">void</span> <span class="nf">InitMembership</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="n">Database</span><span class="p">.</span><span class="n">SetInitializer</span><span class="p">&lt;</span><span class="n">UsersContext</span><span class="p">&gt;(</span><span class="k">null</span><span class="p">);</span>

        <span class="k">try</span>
        <span class="p">{</span>
            <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">context</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">UsersContext</span><span class="p">())</span>
            <span class="p">{</span>
                <span class="k">if</span> <span class="p">(!</span><span class="n">context</span><span class="p">.</span><span class="n">Database</span><span class="p">.</span><span class="nf">Exists</span><span class="p">())</span>
                <span class="p">{</span>
                    <span class="c1">// Create the SimpleMembership database without Entity Framework migration schema</span>
                    <span class="p">((</span><span class="n">IObjectContextAdapter</span><span class="p">)</span><span class="n">context</span><span class="p">).</span><span class="n">ObjectContext</span><span class="p">.</span><span class="nf">CreateDatabase</span><span class="p">();</span>
                <span class="p">}</span>
            <span class="p">}</span>

            <span class="n">WebSecurity</span><span class="p">.</span><span class="nf">InitializeDatabaseConnection</span><span class="p">(</span><span class="s">"DefaultConnection"</span><span class="p">,</span> <span class="s">"UserProfile"</span><span class="p">,</span> <span class="s">"UserId"</span><span class="p">,</span> <span class="s">"UserName"</span><span class="p">,</span> <span class="n">autoCreateTables</span><span class="p">:</span> <span class="k">true</span><span class="p">);</span>

            <span class="k">if</span> <span class="p">(!</span><span class="n">Roles</span><span class="p">.</span><span class="nf">RoleExists</span><span class="p">(</span><span class="s">"Developer"</span><span class="p">))</span>
            <span class="p">{</span>
                <span class="n">Roles</span><span class="p">.</span><span class="nf">CreateRole</span><span class="p">(</span><span class="s">"Developer"</span><span class="p">);</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(!</span><span class="n">WebSecurity</span><span class="p">.</span><span class="nf">UserExists</span><span class="p">(</span><span class="s">"sergey"</span><span class="p">))</span>
            <span class="p">{</span>
                <span class="n">WebSecurity</span><span class="p">.</span><span class="nf">CreateUserAndAccount</span><span class="p">(</span><span class="s">"sergey"</span><span class="p">,</span> <span class="s">"password"</span><span class="p">);</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(!</span><span class="n">Roles</span><span class="p">.</span><span class="nf">GetRolesForUser</span><span class="p">(</span><span class="s">"sergey"</span><span class="p">).</span><span class="nf">Contains</span><span class="p">(</span><span class="s">"Developer"</span><span class="p">))</span>
            <span class="p">{</span>
                <span class="n">Roles</span><span class="p">.</span><span class="nf">AddUserToRole</span><span class="p">(</span><span class="s">"sergey"</span><span class="p">,</span> <span class="s">"Developer"</span><span class="p">);</span>
            <span class="p">}</span>
        <span class="p">}</span>
        <span class="k">catch</span> <span class="p">(</span><span class="n">Exception</span> <span class="n">ex</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nf">InvalidOperationException</span><span class="p">(</span><span class="s">"The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588"</span><span class="p">,</span> <span class="n">ex</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>I left the default database creating with entity framework for now, I will most likely remove it later. The important part is that we create a new role “Developer” and assign it to our default user. Also, we can completely remove InitializeSimpleMembershipAttribute from the solution and remove it from AccountController.</p>

<p>In our MiniProfiler we will check if user has that role and if he or she doesn’t we will discard the results.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">protected</span> <span class="k">void</span> <span class="nf">Application_BeginRequest</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">MiniProfiler</span><span class="p">.</span><span class="nf">Start</span><span class="p">();</span>
<span class="p">}</span>

<span class="k">protected</span> <span class="k">void</span> <span class="nf">Application_PostAuthorizeRequest</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(!</span><span class="n">Request</span><span class="p">.</span><span class="n">IsAuthenticated</span> <span class="p">||</span> <span class="p">!</span><span class="n">Roles</span><span class="p">.</span><span class="nf">GetRolesForUser</span><span class="p">(</span><span class="n">User</span><span class="p">.</span><span class="n">Identity</span><span class="p">.</span><span class="n">Name</span><span class="p">).</span><span class="nf">Contains</span><span class="p">(</span><span class="s">"Developer"</span><span class="p">))</span>
    <span class="p">{</span>
        <span class="n">MiniProfiler</span><span class="p">.</span><span class="nf">Stop</span><span class="p">(</span><span class="n">discardResults</span><span class="p">:</span> <span class="k">true</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">protected</span> <span class="k">void</span> <span class="nf">Application_EndRequest</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">MiniProfiler</span><span class="p">.</span><span class="nf">Stop</span><span class="p">();</span> <span class="c1">//stop as early as you can, even earlier with MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Unfortunately this will run MiniProfiler for all requests, one trick that was recommended on <a href="http://stackoverflow.com/questions/6349280/how-to-properly-authenticate-mvc-mini-profiler-with-aspnetsqlmembershipprovider">stackoverflow</a> is to create a watermark cookie if use is in role so the profiler would only start if that cookie is present.</p>

<p>Enjoy!</p>


				<p>ASP.NET MVC 4 introduced an important change in membership providers. Moving away from core membership to a more flexible and simpler <a href="http://weblogs.asp.net/jgalloway/archive/2012/08/29/simplemembership-membership-providers-universal-providers-and-the-new-asp-net-4-5-web-forms-and-asp-net-mvc-4-templates.aspx">SimpleMembershipProvider</a>.
Default “Internet Application” template initializes SimpleMembership by including an action filer InitializeSimpleMembership which gets gets added to the Account controller. So whenever you try to access account controller a filer would check if the SimpleMembershipInitializer was initialized and do the necessary work if needed.</p>

<p>In one of the applications I’m working on at the moment I wanted to only show MiniProfiler for logged in developers, so that required some changes to the default project structure. Since we want to have <a href="http://miniprofiler.com/">MiniProfiler</a> visible on the entire site we need to make sure that membership provider gets initialized for all controllers. One way is to add InitializeSimpleMembershipAttribute to the global filters, however that would require you to hit the page twice since the action attribute fires after the Application_PostAuthorizeRequest (where we will be checking Roles) and the provider would not be initialized on the first request.</p>

<p>I’ve opted out to move the initialization logic from Action attribute to the Application_Start() of the Global.asax file. Since that only fires once per application I thought it would be a better place for it. So it looks like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">MvcApplication</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Web</span><span class="p">.</span><span class="n">HttpApplication</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="k">void</span> <span class="nf">Application_Start</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="p">...</span>
       <span class="nf">InitMembership</span><span class="p">();</span>
    <span class="p">}</span>
    <span class="k">private</span> <span class="k">void</span> <span class="nf">InitMembership</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="n">Database</span><span class="p">.</span><span class="n">SetInitializer</span><span class="p">&lt;</span><span class="n">UsersContext</span><span class="p">&gt;(</span><span class="k">null</span><span class="p">);</span>

        <span class="k">try</span>
        <span class="p">{</span>
            <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">context</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">UsersContext</span><span class="p">())</span>
            <span class="p">{</span>
                <span class="k">if</span> <span class="p">(!</span><span class="n">context</span><span class="p">.</span><span class="n">Database</span><span class="p">.</span><span class="nf">Exists</span><span class="p">())</span>
                <span class="p">{</span>
                    <span class="c1">// Create the SimpleMembership database without Entity Framework migration schema</span>
                    <span class="p">((</span><span class="n">IObjectContextAdapter</span><span class="p">)</span><span class="n">context</span><span class="p">).</span><span class="n">ObjectContext</span><span class="p">.</span><span class="nf">CreateDatabase</span><span class="p">();</span>
                <span class="p">}</span>
            <span class="p">}</span>

            <span class="n">WebSecurity</span><span class="p">.</span><span class="nf">InitializeDatabaseConnection</span><span class="p">(</span><span class="s">"DefaultConnection"</span><span class="p">,</span> <span class="s">"UserProfile"</span><span class="p">,</span> <span class="s">"UserId"</span><span class="p">,</span> <span class="s">"UserName"</span><span class="p">,</span> <span class="n">autoCreateTables</span><span class="p">:</span> <span class="k">true</span><span class="p">);</span>

            <span class="k">if</span> <span class="p">(!</span><span class="n">Roles</span><span class="p">.</span><span class="nf">RoleExists</span><span class="p">(</span><span class="s">"Developer"</span><span class="p">))</span>
            <span class="p">{</span>
                <span class="n">Roles</span><span class="p">.</span><span class="nf">CreateRole</span><span class="p">(</span><span class="s">"Developer"</span><span class="p">);</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(!</span><span class="n">WebSecurity</span><span class="p">.</span><span class="nf">UserExists</span><span class="p">(</span><span class="s">"sergey"</span><span class="p">))</span>
            <span class="p">{</span>
                <span class="n">WebSecurity</span><span class="p">.</span><span class="nf">CreateUserAndAccount</span><span class="p">(</span><span class="s">"sergey"</span><span class="p">,</span> <span class="s">"password"</span><span class="p">);</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(!</span><span class="n">Roles</span><span class="p">.</span><span class="nf">GetRolesForUser</span><span class="p">(</span><span class="s">"sergey"</span><span class="p">).</span><span class="nf">Contains</span><span class="p">(</span><span class="s">"Developer"</span><span class="p">))</span>
            <span class="p">{</span>
                <span class="n">Roles</span><span class="p">.</span><span class="nf">AddUserToRole</span><span class="p">(</span><span class="s">"sergey"</span><span class="p">,</span> <span class="s">"Developer"</span><span class="p">);</span>
            <span class="p">}</span>
        <span class="p">}</span>
        <span class="k">catch</span> <span class="p">(</span><span class="n">Exception</span> <span class="n">ex</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nf">InvalidOperationException</span><span class="p">(</span><span class="s">"The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588"</span><span class="p">,</span> <span class="n">ex</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>I left the default database creating with entity framework for now, I will most likely remove it later. The important part is that we create a new role “Developer” and assign it to our default user. Also, we can completely remove InitializeSimpleMembershipAttribute from the solution and remove it from AccountController.</p>

<p>In our MiniProfiler we will check if user has that role and if he or she doesn’t we will discard the results.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">protected</span> <span class="k">void</span> <span class="nf">Application_BeginRequest</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">MiniProfiler</span><span class="p">.</span><span class="nf">Start</span><span class="p">();</span>
<span class="p">}</span>

<span class="k">protected</span> <span class="k">void</span> <span class="nf">Application_PostAuthorizeRequest</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(!</span><span class="n">Request</span><span class="p">.</span><span class="n">IsAuthenticated</span> <span class="p">||</span> <span class="p">!</span><span class="n">Roles</span><span class="p">.</span><span class="nf">GetRolesForUser</span><span class="p">(</span><span class="n">User</span><span class="p">.</span><span class="n">Identity</span><span class="p">.</span><span class="n">Name</span><span class="p">).</span><span class="nf">Contains</span><span class="p">(</span><span class="s">"Developer"</span><span class="p">))</span>
    <span class="p">{</span>
        <span class="n">MiniProfiler</span><span class="p">.</span><span class="nf">Stop</span><span class="p">(</span><span class="n">discardResults</span><span class="p">:</span> <span class="k">true</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">protected</span> <span class="k">void</span> <span class="nf">Application_EndRequest</span><span class="p">()</span>
<span class="p">{</span>
    <span class="n">MiniProfiler</span><span class="p">.</span><span class="nf">Stop</span><span class="p">();</span> <span class="c1">//stop as early as you can, even earlier with MvcMiniProfiler.MiniProfiler.Stop(discardResults: true);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Unfortunately this will run MiniProfiler for all requests, one trick that was recommended on <a href="http://stackoverflow.com/questions/6349280/how-to-properly-authenticate-mvc-mini-profiler-with-aspnetsqlmembershipprovider">stackoverflow</a> is to create a watermark cookie if use is in role so the profiler would only start if that cookie is present.</p>

<p>Enjoy!</p>


										
					<p>Posted in: asp.net</p>
						
				
					<p>Tagged with: asp.net-mvc-4 and miniprofiler</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/asp-net/mvc4-role-base-miniprofiler/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/asp-net/mvc4-role-base-miniprofiler/]]></guid>
		<pubDate>2013-02-11T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Ensuring Variables Are Atomic or Thread Safe]]></title>
		<description>
			<![CDATA[
				<p>When multiple threads are writing to the static field you need to make sure that the writing operation is atomic or only one thread can write at a time. One of the ways to ensure you static fields are thread safe is to use <strong>Interlocked</strong> class part from the System.Threading namespace.</p>

<p>Here is an example of a static cache that does clean up every 1000 saves.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">QueryCache</span>
<span class="p">{</span>
    <span class="c1">//static field that we need to make sure is thread safe</span>
    <span class="k">private</span> <span class="k">static</span> <span class="kt">int</span> <span class="n">cacheCount</span><span class="p">;</span>
    <span class="k">private</span> <span class="k">const</span> <span class="kt">int</span> <span class="n">MAX_ITEMS</span> <span class="p">=</span> <span class="m">1000</span><span class="p">;</span>
    <span class="k">static</span> <span class="k">readonly</span> <span class="n">System</span><span class="p">.</span><span class="n">Collections</span><span class="p">.</span><span class="n">Concurrent</span><span class="p">.</span><span class="n">ConcurrentDictionary</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">,</span> <span class="kt">object</span><span class="p">&gt;</span> <span class="n">_cache</span> <span class="p">=</span> <span class="k">new</span> <span class="n">System</span><span class="p">.</span><span class="n">Collections</span><span class="p">.</span><span class="n">Concurrent</span><span class="p">.</span><span class="n">ConcurrentDictionary</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">,</span> <span class="kt">object</span><span class="p">&gt;();</span>
    <span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">SaveToCache</span><span class="p">(</span><span class="kt">string</span> <span class="n">key</span><span class="p">,</span> <span class="kt">object</span> <span class="k">value</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">if</span><span class="p">(</span><span class="n">Interlocked</span><span class="p">.</span><span class="nf">Increment</span><span class="p">(</span><span class="k">ref</span> <span class="n">cacheCount</span><span class="p">)</span> <span class="p">==</span> <span class="n">MAX_ITEMS</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="nf">CleanUpCache</span><span class="p">();</span>
        <span class="p">}</span>
        <span class="n">_cache</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="p">=</span> <span class="k">value</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Since multiple threads can be writing to the cache at the same time, we have to make sure we don’t have a collision when incrementing a cacheCount file.
<a href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx">Interlocked</a> class has some other useful methods like <code class="language-plaintext highlighter-rouge">Interlock.Exchange</code> to set the variable to a specific value atomically.</p>


				<p>When multiple threads are writing to the static field you need to make sure that the writing operation is atomic or only one thread can write at a time. One of the ways to ensure you static fields are thread safe is to use <strong>Interlocked</strong> class part from the System.Threading namespace.</p>

<p>Here is an example of a static cache that does clean up every 1000 saves.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">QueryCache</span>
<span class="p">{</span>
    <span class="c1">//static field that we need to make sure is thread safe</span>
    <span class="k">private</span> <span class="k">static</span> <span class="kt">int</span> <span class="n">cacheCount</span><span class="p">;</span>
    <span class="k">private</span> <span class="k">const</span> <span class="kt">int</span> <span class="n">MAX_ITEMS</span> <span class="p">=</span> <span class="m">1000</span><span class="p">;</span>
    <span class="k">static</span> <span class="k">readonly</span> <span class="n">System</span><span class="p">.</span><span class="n">Collections</span><span class="p">.</span><span class="n">Concurrent</span><span class="p">.</span><span class="n">ConcurrentDictionary</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">,</span> <span class="kt">object</span><span class="p">&gt;</span> <span class="n">_cache</span> <span class="p">=</span> <span class="k">new</span> <span class="n">System</span><span class="p">.</span><span class="n">Collections</span><span class="p">.</span><span class="n">Concurrent</span><span class="p">.</span><span class="n">ConcurrentDictionary</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">,</span> <span class="kt">object</span><span class="p">&gt;();</span>
    <span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">SaveToCache</span><span class="p">(</span><span class="kt">string</span> <span class="n">key</span><span class="p">,</span> <span class="kt">object</span> <span class="k">value</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">if</span><span class="p">(</span><span class="n">Interlocked</span><span class="p">.</span><span class="nf">Increment</span><span class="p">(</span><span class="k">ref</span> <span class="n">cacheCount</span><span class="p">)</span> <span class="p">==</span> <span class="n">MAX_ITEMS</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="nf">CleanUpCache</span><span class="p">();</span>
        <span class="p">}</span>
        <span class="n">_cache</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="p">=</span> <span class="k">value</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Since multiple threads can be writing to the cache at the same time, we have to make sure we don’t have a collision when incrementing a cacheCount file.
<a href="http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx">Interlocked</a> class has some other useful methods like <code class="language-plaintext highlighter-rouge">Interlock.Exchange</code> to set the variable to a specific value atomically.</p>


										
					<p>Posted in: asp.net</p>
						
				
					<p>Tagged with: thread-safety</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/asp-net/primitive-types-thread-safe-automic/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/asp-net/primitive-types-thread-safe-automic/]]></guid>
		<pubDate>2013-02-09T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Setting up MiniProfiler with WCF]]></title>
		<description>
			<![CDATA[
				<p>First of all MiniProfiler is awesome! And lucky for me some smart people made it work with WCF. Since there is no official guide on setting up the project I had to get the examples and work from there. Here is what I had to do in order to get it working.</p>

<p>There is no Nuget package for MiniProfiler.WCF library so you have to download <a href="https://github.com/SamSaffron/MiniProfiler">source code</a> from GitHub and compile it under Release configuration. Then take MiniProfiler.dll and MiniProfiler.WCF dlls and place them in your common folder where you keep your external libraries.</p>

<h3 id="service-setup">Service setup</h3>

<p>Next, in your WCF Service project register wcfMiniProfilerBehavior extensions under extensions element (you can find out the version number with right click and going to properties on the MiniProfiler.Wcf.dll file. )</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    ...
        <span class="nt">&lt;extensions&gt;</span>
          <span class="nt">&lt;behaviorExtensions&gt;</span>
            <span class="nt">&lt;add</span> <span class="na">name=</span><span class="s">"wcfMiniProfilerBehavior"</span> <span class="na">type=</span><span class="s">"StackExchange.Profiling.Wcf.WcfMiniProfilerBehavior, Miniprofiler.Wcf, Version=2.0.4.0, Culture=neutral"</span> <span class="nt">/&gt;</span>
          <span class="nt">&lt;/behaviorExtensions&gt;</span>
        <span class="nt">&lt;/extensions&gt;</span>
     <span class="nt">&lt;/system.serviceModel&gt;</span>
</code></pre></div></div>

<p>And in your WCF Service project you need to add the following endPointBehavior under behaviors element.</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="nt">&lt;behaviors&gt;</span>
    ...
          <span class="nt">&lt;endpointBehaviors&gt;</span>
            <span class="nt">&lt;behavior&gt;</span>
              <span class="nt">&lt;wcfMiniProfilerBehavior</span> <span class="nt">/&gt;</span>
            <span class="nt">&lt;/behavior&gt;</span>
          <span class="nt">&lt;/endpointBehaviors&gt;</span>
    <span class="nt">&lt;/behaviors&gt;</span>
</code></pre></div></div>

<p>Oh yea and don’t forget to reference a MiniProfiler.Wcf in your Service Project.
You will need to register MiniProfiler assembly in other projects where the actual profiling is going to take place, for example your data layer would have a reference to that file and wrap a connection with a dbprofiled connection, for more setup details see the <a href="http://miniprofiler.com/">official site</a>.</p>

<h3 id="client-setup">Client Setup</h3>

<p>If you are using proxies for your client setup you would register the following configuration in your client’s web.config.</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>      <span class="nt">&lt;system.serviceModel&gt;</span>
        <span class="nt">&lt;extensions&gt;</span>
          <span class="nt">&lt;behaviorExtensions&gt;</span>
            <span class="nt">&lt;add</span> <span class="na">name=</span><span class="s">"wcfMiniProfilerBehavior"</span> <span class="na">type=</span><span class="s">"StackExchange.Profiling.Wcf.WcfMiniProfilerBehavior, Miniprofiler.Wcf, Version=2.0.4.0, Culture=neutral"</span> <span class="nt">/&gt;</span>
          <span class="nt">&lt;/behaviorExtensions&gt;</span>
</code></pre></div></div>

<p>And behaviors</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="nt">&lt;behaviors&gt;</span>
      <span class="nt">&lt;endpointBehaviors&gt;</span>
        <span class="nt">&lt;behavior&gt;</span>
          <span class="nt">&lt;webHttp/&gt;</span>
          <span class="nt">&lt;wcfMiniProfilerBehavior</span> <span class="nt">/&gt;</span>
        <span class="nt">&lt;/behavior&gt;</span>
      <span class="nt">&lt;/endpointBehaviors&gt;</span>
    <span class="nt">&lt;/behaviors&gt;</span>
</code></pre></div></div>

<p>Just like in the Sample Project.</p>

<p>If you are using ChannelFactory without generating proxies you would need to add a behavior in the following way, for example:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">ChannelFactory</span> <span class="p">=</span> <span class="k">new</span> <span class="n">ChannelFactory</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="n">Binding</span><span class="p">,</span> <span class="n">Endpoint</span><span class="p">);</span>
<span class="n">ChannelFactory</span><span class="p">.</span><span class="n">Endpoint</span><span class="p">.</span><span class="n">Behaviors</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="k">new</span> <span class="nf">WcfMiniProfilerBehavior</span><span class="p">());</span>
<span class="n">Channel</span> <span class="p">=</span> <span class="n">ChannelFactory</span><span class="p">.</span><span class="nf">CreateChannel</span><span class="p">();</span>
</code></pre></div></div>

<p>That’s almost it, just add the standard initialization to Application_BeginRequest and etc. mine looks like this</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">protected</span> <span class="k">void</span> <span class="nf">Application_BeginRequest</span><span class="p">(</span><span class="n">Object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">IsLocal</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">MiniProfiler</span><span class="p">.</span><span class="nf">Start</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">protected</span> <span class="k">void</span> <span class="nf">Application_EndRequest</span><span class="p">(</span><span class="n">Object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">MiniProfiler</span><span class="p">.</span><span class="nf">Stop</span><span class="p">();</span>
<span class="p">}</span>

<span class="k">private</span> <span class="k">void</span> <span class="nf">InitProfilerSettings</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// some things should never be seen</span>
    <span class="kt">var</span> <span class="n">ignored</span> <span class="p">=</span> <span class="n">MiniProfiler</span><span class="p">.</span><span class="n">Settings</span><span class="p">.</span><span class="n">IgnoredPaths</span><span class="p">.</span><span class="nf">ToList</span><span class="p">();</span>
    <span class="n">ignored</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"WebResource.axd"</span><span class="p">);</span>
    <span class="n">ignored</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"/Styles/"</span><span class="p">);</span>
    <span class="n">MiniProfiler</span><span class="p">.</span><span class="n">Settings</span><span class="p">.</span><span class="n">IgnoredPaths</span> <span class="p">=</span> <span class="n">ignored</span><span class="p">.</span><span class="nf">ToArray</span><span class="p">();</span>

    <span class="n">MiniProfiler</span><span class="p">.</span><span class="n">Settings</span><span class="p">.</span><span class="n">SqlFormatter</span> <span class="p">=</span> <span class="k">new</span> <span class="n">StackExchange</span><span class="p">.</span><span class="n">Profiling</span><span class="p">.</span><span class="n">SqlFormatters</span><span class="p">.</span><span class="nf">SqlServerFormatter</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Also, need to add handler activation into web.config under system.webserver</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="nt">&lt;system.webServer&gt;</span>
    ...
    <span class="nt">&lt;handlers&gt;</span>
    <span class="nt">&lt;add</span> <span class="na">name=</span><span class="s">"MiniProfiler"</span> <span class="na">path=</span><span class="s">"mini-profiler-resources/*"</span> <span class="na">verb=</span><span class="s">"*"</span>
    <span class="na">type=</span><span class="s">"System.Web.Routing.UrlRoutingModule"</span> <span class="na">resourceType=</span><span class="s">"Unspecified"</span> <span class="na">preCondition=</span><span class="s">"integratedMode"</span> <span class="nt">/&gt;</span>
    <span class="nt">&lt;/handlers&gt;</span>
</code></pre></div></div>

<p>Finally, adding Mini Profile rendering scripts in your master page.</p>

<pre><code class="language-razor">    &lt;%= StackExchange.Profiling.MiniProfiler.RenderIncludes() %&gt;
</code></pre>


				<p>First of all MiniProfiler is awesome! And lucky for me some smart people made it work with WCF. Since there is no official guide on setting up the project I had to get the examples and work from there. Here is what I had to do in order to get it working.</p>

<p>There is no Nuget package for MiniProfiler.WCF library so you have to download <a href="https://github.com/SamSaffron/MiniProfiler">source code</a> from GitHub and compile it under Release configuration. Then take MiniProfiler.dll and MiniProfiler.WCF dlls and place them in your common folder where you keep your external libraries.</p>

<h3 id="service-setup">Service setup</h3>

<p>Next, in your WCF Service project register wcfMiniProfilerBehavior extensions under extensions element (you can find out the version number with right click and going to properties on the MiniProfiler.Wcf.dll file. )</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    ...
        <span class="nt">&lt;extensions&gt;</span>
          <span class="nt">&lt;behaviorExtensions&gt;</span>
            <span class="nt">&lt;add</span> <span class="na">name=</span><span class="s">"wcfMiniProfilerBehavior"</span> <span class="na">type=</span><span class="s">"StackExchange.Profiling.Wcf.WcfMiniProfilerBehavior, Miniprofiler.Wcf, Version=2.0.4.0, Culture=neutral"</span> <span class="nt">/&gt;</span>
          <span class="nt">&lt;/behaviorExtensions&gt;</span>
        <span class="nt">&lt;/extensions&gt;</span>
     <span class="nt">&lt;/system.serviceModel&gt;</span>
</code></pre></div></div>

<p>And in your WCF Service project you need to add the following endPointBehavior under behaviors element.</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="nt">&lt;behaviors&gt;</span>
    ...
          <span class="nt">&lt;endpointBehaviors&gt;</span>
            <span class="nt">&lt;behavior&gt;</span>
              <span class="nt">&lt;wcfMiniProfilerBehavior</span> <span class="nt">/&gt;</span>
            <span class="nt">&lt;/behavior&gt;</span>
          <span class="nt">&lt;/endpointBehaviors&gt;</span>
    <span class="nt">&lt;/behaviors&gt;</span>
</code></pre></div></div>

<p>Oh yea and don’t forget to reference a MiniProfiler.Wcf in your Service Project.
You will need to register MiniProfiler assembly in other projects where the actual profiling is going to take place, for example your data layer would have a reference to that file and wrap a connection with a dbprofiled connection, for more setup details see the <a href="http://miniprofiler.com/">official site</a>.</p>

<h3 id="client-setup">Client Setup</h3>

<p>If you are using proxies for your client setup you would register the following configuration in your client’s web.config.</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>      <span class="nt">&lt;system.serviceModel&gt;</span>
        <span class="nt">&lt;extensions&gt;</span>
          <span class="nt">&lt;behaviorExtensions&gt;</span>
            <span class="nt">&lt;add</span> <span class="na">name=</span><span class="s">"wcfMiniProfilerBehavior"</span> <span class="na">type=</span><span class="s">"StackExchange.Profiling.Wcf.WcfMiniProfilerBehavior, Miniprofiler.Wcf, Version=2.0.4.0, Culture=neutral"</span> <span class="nt">/&gt;</span>
          <span class="nt">&lt;/behaviorExtensions&gt;</span>
</code></pre></div></div>

<p>And behaviors</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="nt">&lt;behaviors&gt;</span>
      <span class="nt">&lt;endpointBehaviors&gt;</span>
        <span class="nt">&lt;behavior&gt;</span>
          <span class="nt">&lt;webHttp/&gt;</span>
          <span class="nt">&lt;wcfMiniProfilerBehavior</span> <span class="nt">/&gt;</span>
        <span class="nt">&lt;/behavior&gt;</span>
      <span class="nt">&lt;/endpointBehaviors&gt;</span>
    <span class="nt">&lt;/behaviors&gt;</span>
</code></pre></div></div>

<p>Just like in the Sample Project.</p>

<p>If you are using ChannelFactory without generating proxies you would need to add a behavior in the following way, for example:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">ChannelFactory</span> <span class="p">=</span> <span class="k">new</span> <span class="n">ChannelFactory</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="n">Binding</span><span class="p">,</span> <span class="n">Endpoint</span><span class="p">);</span>
<span class="n">ChannelFactory</span><span class="p">.</span><span class="n">Endpoint</span><span class="p">.</span><span class="n">Behaviors</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="k">new</span> <span class="nf">WcfMiniProfilerBehavior</span><span class="p">());</span>
<span class="n">Channel</span> <span class="p">=</span> <span class="n">ChannelFactory</span><span class="p">.</span><span class="nf">CreateChannel</span><span class="p">();</span>
</code></pre></div></div>

<p>That’s almost it, just add the standard initialization to Application_BeginRequest and etc. mine looks like this</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">protected</span> <span class="k">void</span> <span class="nf">Application_BeginRequest</span><span class="p">(</span><span class="n">Object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">IsLocal</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">MiniProfiler</span><span class="p">.</span><span class="nf">Start</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">protected</span> <span class="k">void</span> <span class="nf">Application_EndRequest</span><span class="p">(</span><span class="n">Object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">MiniProfiler</span><span class="p">.</span><span class="nf">Stop</span><span class="p">();</span>
<span class="p">}</span>

<span class="k">private</span> <span class="k">void</span> <span class="nf">InitProfilerSettings</span><span class="p">()</span>
<span class="p">{</span>
    <span class="c1">// some things should never be seen</span>
    <span class="kt">var</span> <span class="n">ignored</span> <span class="p">=</span> <span class="n">MiniProfiler</span><span class="p">.</span><span class="n">Settings</span><span class="p">.</span><span class="n">IgnoredPaths</span><span class="p">.</span><span class="nf">ToList</span><span class="p">();</span>
    <span class="n">ignored</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"WebResource.axd"</span><span class="p">);</span>
    <span class="n">ignored</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"/Styles/"</span><span class="p">);</span>
    <span class="n">MiniProfiler</span><span class="p">.</span><span class="n">Settings</span><span class="p">.</span><span class="n">IgnoredPaths</span> <span class="p">=</span> <span class="n">ignored</span><span class="p">.</span><span class="nf">ToArray</span><span class="p">();</span>

    <span class="n">MiniProfiler</span><span class="p">.</span><span class="n">Settings</span><span class="p">.</span><span class="n">SqlFormatter</span> <span class="p">=</span> <span class="k">new</span> <span class="n">StackExchange</span><span class="p">.</span><span class="n">Profiling</span><span class="p">.</span><span class="n">SqlFormatters</span><span class="p">.</span><span class="nf">SqlServerFormatter</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Also, need to add handler activation into web.config under system.webserver</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="nt">&lt;system.webServer&gt;</span>
    ...
    <span class="nt">&lt;handlers&gt;</span>
    <span class="nt">&lt;add</span> <span class="na">name=</span><span class="s">"MiniProfiler"</span> <span class="na">path=</span><span class="s">"mini-profiler-resources/*"</span> <span class="na">verb=</span><span class="s">"*"</span>
    <span class="na">type=</span><span class="s">"System.Web.Routing.UrlRoutingModule"</span> <span class="na">resourceType=</span><span class="s">"Unspecified"</span> <span class="na">preCondition=</span><span class="s">"integratedMode"</span> <span class="nt">/&gt;</span>
    <span class="nt">&lt;/handlers&gt;</span>
</code></pre></div></div>

<p>Finally, adding Mini Profile rendering scripts in your master page.</p>

<pre><code class="language-razor">    &lt;%= StackExchange.Profiling.MiniProfiler.RenderIncludes() %&gt;
</code></pre>


						
				
					<p>Tagged with: asp.net-wcf and miniprofiler</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/setting-up-miniprofiler-to-work-with-wcf/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/setting-up-miniprofiler-to-work-with-wcf/]]></guid>
		<pubDate>2013-02-04T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Replace With Regular Expressions in Visual Studio]]></title>
		<description>
			<![CDATA[
				<p>Regular expressions are very handy especially when you are refactoring and there is a lot of manual changes. Visual Studio Replace with regex came in really handy when porting our code base at work to use <a href="http://miniprofiler.com/">MiniProfiler</a>. Since MiniProfiler returns a DbConnection rather than SqlConnection, there are few small shorthands that no longer worked with DbConnection.</p>

<p>The following example will work with SqlCommand but would not work with the DbCommand because DbCommand.Parameters doesn’t expose a Value property which is a short hand notation that returns the last SqlParameter Value.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">using</span><span class="p">(</span><span class="kt">var</span> <span class="n">cn</span> <span class="p">=</span> <span class="n">SqlTools</span><span class="p">.</span><span class="nf">GetSqlConnection</span><span class="p">(</span><span class="s">"Default"</span><span class="p">))</span>
    <span class="p">{</span>
        <span class="kt">var</span> <span class="n">cmd</span> <span class="p">=</span> <span class="n">cn</span><span class="p">.</span><span class="nf">CreateCommand</span><span class="p">();</span>
        <span class="n">cmd</span><span class="p">.</span><span class="n">Parameters</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="k">new</span> <span class="nf">SqlParameter</span><span class="p">(</span><span class="s">"@Password"</span><span class="p">,</span> <span class="n">SqlDbType</span><span class="p">.</span><span class="n">NVarChar</span><span class="p">,</span> <span class="m">128</span><span class="p">)).</span><span class="n">Value</span> <span class="p">=</span> <span class="n">password</span><span class="p">;</span>
</code></pre></div></div>

<p>So I needed to modify this code in about 650 places to use object initializer like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">cmd</span><span class="p">.</span><span class="n">Parameters</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="k">new</span> <span class="nf">SqlParameter</span><span class="p">(</span><span class="s">"@UserName"</span><span class="p">,</span> <span class="n">SqlDbType</span><span class="p">.</span><span class="n">NVarChar</span><span class="p">,</span> <span class="m">256</span><span class="p">)</span> <span class="p">{</span> <span class="n">Value</span> <span class="p">=</span> <span class="n">username</span> <span class="p">});</span>
</code></pre></div></div>

<p>With a little bit of research I wrote a regular expression for Visial Studio Replace to fix this issue. Which looks like this:</p>

<p>Find what: <code class="language-plaintext highlighter-rouge">new SqlParameter\({[^)]*}\)\)\.{[A-Za-z]+} = {[^\}]+};</code></p>

<p>Repleace with what: <code class="language-plaintext highlighter-rouge">new SqlParameter(\1) { \2 = \3 });</code></p>

<p>And vua-lah!, it is all fixed.</p>

<p>One important feature to notice is that you use curly braces to mark the values that you are extracting from the string, this is different from other flavors where you use parenthesis.</p>

<p><strong>Update 04-23-2013</strong></p>

<p>Visual Studio 2012 is using a different syntax to capture strings. The above expression would have to be slightly modified, as follows:</p>

<p>Find what: <code class="language-plaintext highlighter-rouge">new SqlParameter\(([^)]*)\)\)\.([A-Za-z]+) = ([^\}]+);</code></p>

<p>Repleace with what: <code class="language-plaintext highlighter-rouge">new SqlParameter($1) { $2 = $3 });</code></p>


				<p>Regular expressions are very handy especially when you are refactoring and there is a lot of manual changes. Visual Studio Replace with regex came in really handy when porting our code base at work to use <a href="http://miniprofiler.com/">MiniProfiler</a>. Since MiniProfiler returns a DbConnection rather than SqlConnection, there are few small shorthands that no longer worked with DbConnection.</p>

<p>The following example will work with SqlCommand but would not work with the DbCommand because DbCommand.Parameters doesn’t expose a Value property which is a short hand notation that returns the last SqlParameter Value.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">using</span><span class="p">(</span><span class="kt">var</span> <span class="n">cn</span> <span class="p">=</span> <span class="n">SqlTools</span><span class="p">.</span><span class="nf">GetSqlConnection</span><span class="p">(</span><span class="s">"Default"</span><span class="p">))</span>
    <span class="p">{</span>
        <span class="kt">var</span> <span class="n">cmd</span> <span class="p">=</span> <span class="n">cn</span><span class="p">.</span><span class="nf">CreateCommand</span><span class="p">();</span>
        <span class="n">cmd</span><span class="p">.</span><span class="n">Parameters</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="k">new</span> <span class="nf">SqlParameter</span><span class="p">(</span><span class="s">"@Password"</span><span class="p">,</span> <span class="n">SqlDbType</span><span class="p">.</span><span class="n">NVarChar</span><span class="p">,</span> <span class="m">128</span><span class="p">)).</span><span class="n">Value</span> <span class="p">=</span> <span class="n">password</span><span class="p">;</span>
</code></pre></div></div>

<p>So I needed to modify this code in about 650 places to use object initializer like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="n">cmd</span><span class="p">.</span><span class="n">Parameters</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="k">new</span> <span class="nf">SqlParameter</span><span class="p">(</span><span class="s">"@UserName"</span><span class="p">,</span> <span class="n">SqlDbType</span><span class="p">.</span><span class="n">NVarChar</span><span class="p">,</span> <span class="m">256</span><span class="p">)</span> <span class="p">{</span> <span class="n">Value</span> <span class="p">=</span> <span class="n">username</span> <span class="p">});</span>
</code></pre></div></div>

<p>With a little bit of research I wrote a regular expression for Visial Studio Replace to fix this issue. Which looks like this:</p>

<p>Find what: <code class="language-plaintext highlighter-rouge">new SqlParameter\({[^)]*}\)\)\.{[A-Za-z]+} = {[^\}]+};</code></p>

<p>Repleace with what: <code class="language-plaintext highlighter-rouge">new SqlParameter(\1) { \2 = \3 });</code></p>

<p>And vua-lah!, it is all fixed.</p>

<p>One important feature to notice is that you use curly braces to mark the values that you are extracting from the string, this is different from other flavors where you use parenthesis.</p>

<p><strong>Update 04-23-2013</strong></p>

<p>Visual Studio 2012 is using a different syntax to capture strings. The above expression would have to be slightly modified, as follows:</p>

<p>Find what: <code class="language-plaintext highlighter-rouge">new SqlParameter\(([^)]*)\)\)\.([A-Za-z]+) = ([^\}]+);</code></p>

<p>Repleace with what: <code class="language-plaintext highlighter-rouge">new SqlParameter($1) { $2 = $3 });</code></p>


										
					<p>Posted in: asp.net</p>
						
				
					<p>Tagged with: regex</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/asp-net/visual-studio-replace-with-regular-expressions/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/asp-net/visual-studio-replace-with-regular-expressions/]]></guid>
		<pubDate>2013-02-01T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Typing Challenge]]></title>
		<description>
			<![CDATA[
				<p>It’s sad to see many professional programmers typing with two or three fingers. Like in any profession you should become a master of your craft, and for us developers touch typing is a basic skill that you must master. Like a chef who has never learned how to properly prepare vegetables it’s not efficient, makes your already difficult profession harder and just not professional.</p>

<p>When I first started my programming career I have to admit I was pretty mediocre. Even though I could type about 45 words per minute (WPM) I was still typing with 3 fingers and looking at the keyboard. In the beginning typing uncommon characters made me feel awkward and frustrated and my WMP went out the window. I think my real WMP while writing code was about 10-13. I think i really decided to take the bull by the horns when I realized that it actually interfered with my coding. I’m not good at multitasking and when I write my code I need to keep in the flow of one task and that thinking about task at hand. Looking at the keyboard while typing will slow you down and slow down the flow of your thoughts and eventually your brain will get frustrated and get distracted.</p>

<p>It’s pretty amazing how much such a basic skill of touch typing can <strong>improve the quality of your career</strong>. I can tell that it made my job a lot more pleasurable. I actually look forward to writing code since it doesn’t require much effort. Also, I can tell that I’m relying on IDE much less and it just feels great.</p>

<p>For me working doing 15 minutes of practice every day worked magic, but you gotta stick with it for at least for couple weeks. Also don’t cheat yourself and making sure every finger is doing it’s proper job. You will actually see results pretty fast.</p>

<p>So I challenge you to take 15 minutes out of your day and head over to <a href="http://typing.io">Typing for developers</a>
and stick to taking lessons for about 2 weeks.</p>

<p>That’s it and enjoy!</p>


				<p>It’s sad to see many professional programmers typing with two or three fingers. Like in any profession you should become a master of your craft, and for us developers touch typing is a basic skill that you must master. Like a chef who has never learned how to properly prepare vegetables it’s not efficient, makes your already difficult profession harder and just not professional.</p>

<p>When I first started my programming career I have to admit I was pretty mediocre. Even though I could type about 45 words per minute (WPM) I was still typing with 3 fingers and looking at the keyboard. In the beginning typing uncommon characters made me feel awkward and frustrated and my WMP went out the window. I think my real WMP while writing code was about 10-13. I think i really decided to take the bull by the horns when I realized that it actually interfered with my coding. I’m not good at multitasking and when I write my code I need to keep in the flow of one task and that thinking about task at hand. Looking at the keyboard while typing will slow you down and slow down the flow of your thoughts and eventually your brain will get frustrated and get distracted.</p>

<p>It’s pretty amazing how much such a basic skill of touch typing can <strong>improve the quality of your career</strong>. I can tell that it made my job a lot more pleasurable. I actually look forward to writing code since it doesn’t require much effort. Also, I can tell that I’m relying on IDE much less and it just feels great.</p>

<p>For me working doing 15 minutes of practice every day worked magic, but you gotta stick with it for at least for couple weeks. Also don’t cheat yourself and making sure every finger is doing it’s proper job. You will actually see results pretty fast.</p>

<p>So I challenge you to take 15 minutes out of your day and head over to <a href="http://typing.io">Typing for developers</a>
and stick to taking lessons for about 2 weeks.</p>

<p>That’s it and enjoy!</p>


										
					<p>Posted in: better-programmer</p>
						
				
					<p>Tagged with: better-programmer</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/better-programmer/typing-challenge/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/better-programmer/typing-challenge/]]></guid>
		<pubDate>2012-12-21T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[ADO.NET Optimizing DataReader Performance]]></title>
		<description>
			<![CDATA[
				<p>Coming back to ADO.NET, I sometimes forget of different ways of accessing values from the SqlDataReader, cost of a type unboxing and which method is to use when. For example, here are different ways we can access values:</p>

<ul>
  <li>using a typed accessor SqlDataReader.GetInt32(int columnOrdinal)</li>
  <li>geting a value directly with named column like this SqlDataReader[“columnName”] or with column ordinal SqlDataReader[0] and then casting it</li>
  <li>call SqlDataReader.GetOrdinal(“columnName”) to get column position and then combine the result and call the typed accessor method like SqlDataReader.GetInt32(SqlDataReader.GetOrdinal(“columnName”)).</li>
</ul>

<p>For performance benefits using Typed Accessors like <strong>reader.GetInt32</strong> or <strong>reader.GetDateTime</strong> <strong>is always faster</strong> since there is no type conversion or unboxing occurs. But these <strong>typed accessors only accept column ordinal</strong> or column position and most of the times you don’t want to hard code your column position since that could change at any time and break your application.</p>

<p>I wrote a series of tests that test each scenario in the context of:</p>

<ol>
  <li>Getting one record 100000 times, that emulates retrieving of one row.</li>
  <li>Getting 20k records 1000 times, or simulating retrieving large amount of rows</li>
</ol>

<p>The results are as follows:</p>

<h4 id="getting-one-row-over-100k-times">Getting one row over 100k times:</h4>
<p><img src="/uploads/2012/12/one-row.png" alt="one row" /></p>

<p>There is really <strong>no difference</strong> or any significant performance advantage when accessing <strong>one row</strong>. When you run the test multiple times numbers change slightly and there is no clear winner. So we can say if you are only getting one record you can use any one of those accessors and cast as you please.</p>

<h4 id="getting-20k-records-over-1000-times">Getting 20k records over 1000 times</h4>
<p><img src="/uploads/2012/12/datareader-multiplerows.png" alt="data reader multiple rows" /></p>

<p>Typed accessor proves to be the fastest. Right behind is casting by using column orderinal accessor. Casting with column name is probably 30% slower than casting typed casting. And finally <strong>if we call reader.GetOrdinal once and cache the column position we get as fast performance as typed accessor alone</strong>.</p>

<h3 id="summary">Summary</h3>
<p>If your query returns only one row or small amount of rows it doesn’t matter which method you use. It would only make sense if you have large number of rows and using reader.GetOrdinal to cache column number and then using typed accessors would yield the best performance.</p>

<p>If you want to see for yourself you can download the <a href="/uploads/2012/12/SqlDataReaderPerformance.zip">source code</a> and run it against the AdventureWorks database.</p>


				<p>Coming back to ADO.NET, I sometimes forget of different ways of accessing values from the SqlDataReader, cost of a type unboxing and which method is to use when. For example, here are different ways we can access values:</p>

<ul>
  <li>using a typed accessor SqlDataReader.GetInt32(int columnOrdinal)</li>
  <li>geting a value directly with named column like this SqlDataReader[“columnName”] or with column ordinal SqlDataReader[0] and then casting it</li>
  <li>call SqlDataReader.GetOrdinal(“columnName”) to get column position and then combine the result and call the typed accessor method like SqlDataReader.GetInt32(SqlDataReader.GetOrdinal(“columnName”)).</li>
</ul>

<p>For performance benefits using Typed Accessors like <strong>reader.GetInt32</strong> or <strong>reader.GetDateTime</strong> <strong>is always faster</strong> since there is no type conversion or unboxing occurs. But these <strong>typed accessors only accept column ordinal</strong> or column position and most of the times you don’t want to hard code your column position since that could change at any time and break your application.</p>

<p>I wrote a series of tests that test each scenario in the context of:</p>

<ol>
  <li>Getting one record 100000 times, that emulates retrieving of one row.</li>
  <li>Getting 20k records 1000 times, or simulating retrieving large amount of rows</li>
</ol>

<p>The results are as follows:</p>

<h4 id="getting-one-row-over-100k-times">Getting one row over 100k times:</h4>
<p><img src="/uploads/2012/12/one-row.png" alt="one row" /></p>

<p>There is really <strong>no difference</strong> or any significant performance advantage when accessing <strong>one row</strong>. When you run the test multiple times numbers change slightly and there is no clear winner. So we can say if you are only getting one record you can use any one of those accessors and cast as you please.</p>

<h4 id="getting-20k-records-over-1000-times">Getting 20k records over 1000 times</h4>
<p><img src="/uploads/2012/12/datareader-multiplerows.png" alt="data reader multiple rows" /></p>

<p>Typed accessor proves to be the fastest. Right behind is casting by using column orderinal accessor. Casting with column name is probably 30% slower than casting typed casting. And finally <strong>if we call reader.GetOrdinal once and cache the column position we get as fast performance as typed accessor alone</strong>.</p>

<h3 id="summary">Summary</h3>
<p>If your query returns only one row or small amount of rows it doesn’t matter which method you use. It would only make sense if you have large number of rows and using reader.GetOrdinal to cache column number and then using typed accessors would yield the best performance.</p>

<p>If you want to see for yourself you can download the <a href="/uploads/2012/12/SqlDataReaderPerformance.zip">source code</a> and run it against the AdventureWorks database.</p>


										
					<p>Posted in: ado.net</p>
						
				
					<p>Tagged with: ado.net and sqldatareader</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/ado-net/data-reader-performance-optimizations/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/ado-net/data-reader-performance-optimizations/]]></guid>
		<pubDate>2012-12-20T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Adding a Simple Anti Spam Question to FunnelWeb]]></title>
		<description>
			<![CDATA[
				<p>I’ve been getting a ridiculous amount of spam on my blog and even though <a href="http://funnelweblog.com/">FunnelWeb</a> checks with <a href="http://akismet.com/">akismet</a>, a lot of spam messages are still getting through. Most spam comments are placed by bots that look for input fields and then submit garbage in hopes that it somehow becomes a link. We can make it a little harder for it by including a simple question that humans can easily answer, which should reduce amount of spam.</p>

<p>It was very easy to do in FunnelWeb since it embraces ASP.NET MVC. All I had to do is to create an extra property in the <code class="language-plaintext highlighter-rouge">PageModel</code> model and annotate it with regular expression validation that looks for the key answer to the question I’ve provided. (?i) in the regular expression annotation means case insensitive comparison.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>   <span class="p">[</span><span class="n">Required</span><span class="p">]</span>
   <span class="p">[</span><span class="nf">StringLength</span><span class="p">(</span><span class="m">50</span><span class="p">)]</span>
   <span class="p">[</span><span class="nf">DisplayName</span><span class="p">(</span><span class="s">"Spam check"</span><span class="p">)]</span>
   <span class="p">[</span><span class="nf">HintSize</span><span class="p">((</span><span class="n">HintSize</span><span class="p">.</span><span class="n">Medium</span><span class="p">))]</span>
   <span class="p">[</span><span class="nf">Description</span><span class="p">(</span><span class="s">"What colour is grass?"</span><span class="p">)]</span>
   <span class="p">[</span><span class="nf">RegularExpression</span><span class="p">(</span><span class="s">"(?i)^green$"</span><span class="p">,</span> <span class="n">ErrorMessage</span> <span class="p">=</span> <span class="s">"Please confirm that you are human and enter a correct answer. What colour is grass?"</span><span class="p">)]</span>
   <span class="k">public</span> <span class="kt">string</span> <span class="n">SpamCheck</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
</code></pre></div></div>

<p>We don’t add any extra code in our controllers since it already checks if model is valid and if not it would return back with validation error messages. One more thing we need to do is to modify our view to display the spam check answer. We customize our views in the FunnelWeb by coping them into our themes folder and then making changes there keeping originals intact. So I’ve copied <strong>_EditComments.cshtml</strong> from Views/Shared folder and placed under my Theme folder in the Views/Shared folder and added the following to display the spam check.</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"editor-label"</span><span class="nt">&gt;</span>
  @Html.LabelFor(m =&gt; m.SpamCheck)
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"editor-field"</span><span class="nt">&gt;</span>
  @Html.EditorFor(m =&gt; m.SpamCheck, Html.AttributesFor(m =&gt; m.SpamCheck))
  @Html.ValidationMessageFor(m =&gt; m.SpamCheck) @Html.HintFor(m =&gt; m.SpamCheck)
<span class="nt">&lt;/div&gt;</span>
</code></pre></div></div>

<p>And that’s it, with minimal modification to our blogging platform we eliminated all those annoying spam bots posting garbage.</p>

<h4 id="update-11-26-12">Update 11-26-12</h4>

<p>Since putting up that spam filter I haven’t gotten a single spam comment in last 24 hours. Nice, no more need to administer your comments daily, one less thing to worry about!</p>


				<p>I’ve been getting a ridiculous amount of spam on my blog and even though <a href="http://funnelweblog.com/">FunnelWeb</a> checks with <a href="http://akismet.com/">akismet</a>, a lot of spam messages are still getting through. Most spam comments are placed by bots that look for input fields and then submit garbage in hopes that it somehow becomes a link. We can make it a little harder for it by including a simple question that humans can easily answer, which should reduce amount of spam.</p>

<p>It was very easy to do in FunnelWeb since it embraces ASP.NET MVC. All I had to do is to create an extra property in the <code class="language-plaintext highlighter-rouge">PageModel</code> model and annotate it with regular expression validation that looks for the key answer to the question I’ve provided. (?i) in the regular expression annotation means case insensitive comparison.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>   <span class="p">[</span><span class="n">Required</span><span class="p">]</span>
   <span class="p">[</span><span class="nf">StringLength</span><span class="p">(</span><span class="m">50</span><span class="p">)]</span>
   <span class="p">[</span><span class="nf">DisplayName</span><span class="p">(</span><span class="s">"Spam check"</span><span class="p">)]</span>
   <span class="p">[</span><span class="nf">HintSize</span><span class="p">((</span><span class="n">HintSize</span><span class="p">.</span><span class="n">Medium</span><span class="p">))]</span>
   <span class="p">[</span><span class="nf">Description</span><span class="p">(</span><span class="s">"What colour is grass?"</span><span class="p">)]</span>
   <span class="p">[</span><span class="nf">RegularExpression</span><span class="p">(</span><span class="s">"(?i)^green$"</span><span class="p">,</span> <span class="n">ErrorMessage</span> <span class="p">=</span> <span class="s">"Please confirm that you are human and enter a correct answer. What colour is grass?"</span><span class="p">)]</span>
   <span class="k">public</span> <span class="kt">string</span> <span class="n">SpamCheck</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
</code></pre></div></div>

<p>We don’t add any extra code in our controllers since it already checks if model is valid and if not it would return back with validation error messages. One more thing we need to do is to modify our view to display the spam check answer. We customize our views in the FunnelWeb by coping them into our themes folder and then making changes there keeping originals intact. So I’ve copied <strong>_EditComments.cshtml</strong> from Views/Shared folder and placed under my Theme folder in the Views/Shared folder and added the following to display the spam check.</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"editor-label"</span><span class="nt">&gt;</span>
  @Html.LabelFor(m =&gt; m.SpamCheck)
<span class="nt">&lt;/div&gt;</span>
<span class="nt">&lt;div</span> <span class="na">class=</span><span class="s">"editor-field"</span><span class="nt">&gt;</span>
  @Html.EditorFor(m =&gt; m.SpamCheck, Html.AttributesFor(m =&gt; m.SpamCheck))
  @Html.ValidationMessageFor(m =&gt; m.SpamCheck) @Html.HintFor(m =&gt; m.SpamCheck)
<span class="nt">&lt;/div&gt;</span>
</code></pre></div></div>

<p>And that’s it, with minimal modification to our blogging platform we eliminated all those annoying spam bots posting garbage.</p>

<h4 id="update-11-26-12">Update 11-26-12</h4>

<p>Since putting up that spam filter I haven’t gotten a single spam comment in last 24 hours. Nice, no more need to administer your comments daily, one less thing to worry about!</p>


										
					<p>Posted in: funnelweb</p>
						
				
					<p>Tagged with: funnelweb and spam</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/funnelweb/add-simple-anti-spam-question/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/funnelweb/add-simple-anti-spam-question/]]></guid>
		<pubDate>2012-11-26T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Changing the Location of Your ITunes Library Via C#]]></title>
		<description>
			<![CDATA[
				<p>iTunes is my least favorite software when it comes to managing music library. However sometimes you have no choice and have to deal with it. Couple times in the past I had to completely recreate my iTunes library from scratch since I could not move it to the newly installed system. Recently when I’ve build a new PC I was a bit smarter and did the research and mapped my library to the exact same folder and everything worked and everything transferred perfect.</p>

<p>This time however I’ve decided to move out my music library from home server to the media server and was stuck since all my music library tracks were mapped to the UNC \hpserver and new location of my music would be something like M:\Music. Unfortunately you can’t do that with iTunes and you are stuck with going one by one and relocation your track.</p>

<p>Luckily few days ago I’ve stumbled across Scott Hanselman’s <a href="http://www.hanselman.com/blog/RemovingDeadTracksDuplicatesThatDontExistFromITunesUsingC.aspx">post</a> on how to remove dead tracks from iTunes. After looking at the code it was pretty easy to add functionality to relocate tracks automatically and I’ve modified the sample project he provided to do just that. Thanks to him for bringing iTunes api to light!</p>

<p><img src="/uploads/2012/11/Screenshot.png" alt="Itunes relocate tracks" /></p>

<p><strong>Now I still have my library with play counts and all the data just like it was before but under a new location!</strong></p>

<p>Here is the link to the <a href="https://github.com/mercury2269/ITunesManager">modified source code</a> if you ever want to move your itunes library to a new location.</p>


				<p>iTunes is my least favorite software when it comes to managing music library. However sometimes you have no choice and have to deal with it. Couple times in the past I had to completely recreate my iTunes library from scratch since I could not move it to the newly installed system. Recently when I’ve build a new PC I was a bit smarter and did the research and mapped my library to the exact same folder and everything worked and everything transferred perfect.</p>

<p>This time however I’ve decided to move out my music library from home server to the media server and was stuck since all my music library tracks were mapped to the UNC \hpserver and new location of my music would be something like M:\Music. Unfortunately you can’t do that with iTunes and you are stuck with going one by one and relocation your track.</p>

<p>Luckily few days ago I’ve stumbled across Scott Hanselman’s <a href="http://www.hanselman.com/blog/RemovingDeadTracksDuplicatesThatDontExistFromITunesUsingC.aspx">post</a> on how to remove dead tracks from iTunes. After looking at the code it was pretty easy to add functionality to relocate tracks automatically and I’ve modified the sample project he provided to do just that. Thanks to him for bringing iTunes api to light!</p>

<p><img src="/uploads/2012/11/Screenshot.png" alt="Itunes relocate tracks" /></p>

<p><strong>Now I still have my library with play counts and all the data just like it was before but under a new location!</strong></p>

<p>Here is the link to the <a href="https://github.com/mercury2269/ITunesManager">modified source code</a> if you ever want to move your itunes library to a new location.</p>


										
					<p>Posted in: itunes</p>
						
				
					<p>Tagged with: itunes</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/itunes/change-location-of-itunes-library/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/itunes/change-location-of-itunes-library/]]></guid>
		<pubDate>2012-11-25T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[SQLite + Dapper = Simple Data Access Layer]]></title>
		<description>
			<![CDATA[
				<h3 id="summary">Summary</h3>

<p>SQLite is one of the little databases that you can use in your project when you don’t want to have a full blown database and want something simple, quick and awesome. It’s very easy to distribute or share with your team since it’s just a single file and can be checked into source control. Could be used as a development database, one off database for your desktop applications or just about anything else. It’s definitely nice to keep in your development tool belt.</p>

<h3 id="installation">Installation</h3>

<p>There is none, just add reference to SQLite C# drivers and it will create a database for your on first run. Simplest way is to go to Nuget package manager console and run:</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">Install-Package</span><span class="w"> </span><span class="nx">System.Data.SQLite</span><span class="w">
</span></code></pre></div></div>

<p>This will install both versions for x86 and x64 so you can build it for any CPU. There are also specific versions as well in case if you don’t want extra files <code class="language-plaintext highlighter-rouge">Install-Package System.Data.SQLite.x86 or System.Data.SQLite.x64</code>.</p>

<h3 id="model">Model</h3>

<p>In our sample we’ll save and retrieve customers from the database so we’ll create a folder “Model” and add a Customer class which will represent our data model.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">namespace</span> <span class="nn">SQLiteDemo.Model</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">class</span> <span class="nc">Customer</span>
    <span class="p">{</span>
        <span class="k">public</span> <span class="kt">int</span> <span class="n">Id</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
        <span class="k">public</span> <span class="kt">string</span> <span class="n">FirstName</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
        <span class="k">public</span> <span class="kt">string</span> <span class="n">LastName</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
        <span class="k">public</span> <span class="n">DateTime</span> <span class="n">DateOfBirth</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="simple-data-layer">Simple Data Layer</h3>

<p>For this demo I’ll use a console application and for simplicity sake I’ll create a folder “Data” for data access layer. In you production application you will most likely want to put your data access layer into a separate project.</p>

<p>We’ll also use a repository pattern for our Data Access Layer(DAL) since it’s the most commonly used and easily to understand.</p>

<p>We’ll add an interface <code class="language-plaintext highlighter-rouge">ICustomerRepository</code> which will have two methods to save and retrive customers and create a base class <code class="language-plaintext highlighter-rouge">SqLiteBaseRepository</code> which will handle common logic between our repositories like creating database connections.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">interface</span> <span class="nc">ICustomerRepository</span>
<span class="p">{</span>
    <span class="n">Customer</span> <span class="nf">GetCustomer</span><span class="p">(</span><span class="kt">long</span> <span class="n">id</span><span class="p">);</span>
    <span class="k">void</span> <span class="nf">SaveCustomer</span><span class="p">(</span><span class="n">Customer</span> <span class="n">customer</span><span class="p">);</span>
<span class="p">}</span>

<span class="k">public</span> <span class="k">class</span> <span class="nc">SqLiteBaseRepository</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">static</span> <span class="kt">string</span> <span class="n">DbFile</span>
    <span class="p">{</span>
        <span class="k">get</span> <span class="p">{</span> <span class="k">return</span> <span class="n">Environment</span><span class="p">.</span><span class="n">CurrentDirectory</span> <span class="p">+</span> <span class="s">"\\SimpleDb.sqlite"</span><span class="p">;</span> <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">static</span> <span class="n">SQLiteConnection</span> <span class="nf">SimpleDbConnection</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="k">new</span> <span class="nf">SQLiteConnection</span><span class="p">(</span><span class="s">"Data Source="</span> <span class="p">+</span> <span class="n">DbFile</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="using-dapper-as-our-simple-object-relational-mapping-orm">Using Dapper as our simple Object-relational mapping (ORM)</h3>

<p>Dapper is easy to use, fast and fits well for our simple data access layer. It has a simple API on top of already familiar SQL statements.</p>

<p>In your package manager console</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">Install-Package</span><span class="w"> </span><span class="nx">Dapper</span><span class="w">
</span></code></pre></div></div>

<p>In Customer Repository implementation (SqlLiteCustomerRepository) “SaveCustomer” method will first check if database file already exists and execute a create table script which if nothing is found, it will output a file to the environment runtime directory where your executable is located.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">void</span> <span class="nf">SaveCustomer</span><span class="p">(</span><span class="n">Customer</span> <span class="n">customer</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(!</span><span class="n">File</span><span class="p">.</span><span class="nf">Exists</span><span class="p">(</span><span class="n">DbFile</span><span class="p">))</span>
    <span class="p">{</span>
        <span class="nf">CreateDatabase</span><span class="p">();</span>
    <span class="p">}</span>

    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">cnn</span> <span class="p">=</span> <span class="nf">SimpleDbConnection</span><span class="p">())</span>
    <span class="p">{</span>
        <span class="n">cnn</span><span class="p">.</span><span class="nf">Open</span><span class="p">();</span>
        <span class="n">customer</span><span class="p">.</span><span class="n">Id</span> <span class="p">=</span> <span class="n">cnn</span><span class="p">.</span><span class="n">Query</span><span class="p">&lt;</span><span class="kt">long</span><span class="p">&gt;(</span>
            <span class="s">@"INSERT INTO Customer
            ( FirstName, LastName, DateOfBirth ) VALUES
            ( @FirstName, @LastName, @DateOfBirth );
            select last_insert_rowid()"</span><span class="p">,</span> <span class="n">customer</span><span class="p">).</span><span class="nf">First</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">private</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">CreateDatabase</span><span class="p">()</span>
<span class="p">{</span>
    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">cnn</span> <span class="p">=</span> <span class="nf">SimpleDbConnection</span><span class="p">())</span>
    <span class="p">{</span>
        <span class="n">cnn</span><span class="p">.</span><span class="nf">Open</span><span class="p">();</span>
        <span class="n">cnn</span><span class="p">.</span><span class="nf">Execute</span><span class="p">(</span>
            <span class="s">@"create table Customer
                (
                    ID                                  integer identity primary key AUTOINCREMENT,
                    FirstName                           varchar(100) not null,
                    LastName                            varchar(100) not null,
                    DateOfBirth                         datetime not null
                )"</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Above Dapper maps our object to table field names in the query and also returns a long datatype with a newly inserted scoped identity. With SqLite scope identity has a different method last_insert_rowid() and we use that to get inserted customer id and assign it to our customer.</p>

<p>To retrieve customer we first check if database file exists first and then let dapper handle the rest.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="n">Customer</span> <span class="nf">GetCustomer</span><span class="p">(</span><span class="kt">long</span> <span class="n">id</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(!</span><span class="n">File</span><span class="p">.</span><span class="nf">Exists</span><span class="p">(</span><span class="n">DbFile</span><span class="p">))</span> <span class="k">return</span> <span class="k">null</span><span class="p">;</span>

    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">cnn</span> <span class="p">=</span> <span class="nf">SimpleDbConnection</span><span class="p">())</span>
    <span class="p">{</span>
        <span class="n">cnn</span><span class="p">.</span><span class="nf">Open</span><span class="p">();</span>
        <span class="n">Customer</span> <span class="n">result</span> <span class="p">=</span> <span class="n">cnn</span><span class="p">.</span><span class="n">Query</span><span class="p">&lt;</span><span class="n">Customer</span><span class="p">&gt;(</span>
            <span class="s">@"SELECT Id, FirstName, LastName, DateOfBirth
            FROM Customer
            WHERE Id = @id"</span><span class="p">,</span> <span class="k">new</span> <span class="p">{</span> <span class="n">id</span> <span class="p">}).</span><span class="nf">FirstOrDefault</span><span class="p">();</span>
        <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And there you have it, an easy way to have a single file database with a simple ORM in your repository layer.</p>

<h4 id="source-code">Source code</h4>

<p>Here is the link to the source code if you would like to run the solution and try it for yourself. <a href="https://github.com/mercury2269/SQLiteDemo">Source Code</a></p>


				<h3 id="summary">Summary</h3>

<p>SQLite is one of the little databases that you can use in your project when you don’t want to have a full blown database and want something simple, quick and awesome. It’s very easy to distribute or share with your team since it’s just a single file and can be checked into source control. Could be used as a development database, one off database for your desktop applications or just about anything else. It’s definitely nice to keep in your development tool belt.</p>

<h3 id="installation">Installation</h3>

<p>There is none, just add reference to SQLite C# drivers and it will create a database for your on first run. Simplest way is to go to Nuget package manager console and run:</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">Install-Package</span><span class="w"> </span><span class="nx">System.Data.SQLite</span><span class="w">
</span></code></pre></div></div>

<p>This will install both versions for x86 and x64 so you can build it for any CPU. There are also specific versions as well in case if you don’t want extra files <code class="language-plaintext highlighter-rouge">Install-Package System.Data.SQLite.x86 or System.Data.SQLite.x64</code>.</p>

<h3 id="model">Model</h3>

<p>In our sample we’ll save and retrieve customers from the database so we’ll create a folder “Model” and add a Customer class which will represent our data model.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">namespace</span> <span class="nn">SQLiteDemo.Model</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">class</span> <span class="nc">Customer</span>
    <span class="p">{</span>
        <span class="k">public</span> <span class="kt">int</span> <span class="n">Id</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
        <span class="k">public</span> <span class="kt">string</span> <span class="n">FirstName</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
        <span class="k">public</span> <span class="kt">string</span> <span class="n">LastName</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
        <span class="k">public</span> <span class="n">DateTime</span> <span class="n">DateOfBirth</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="simple-data-layer">Simple Data Layer</h3>

<p>For this demo I’ll use a console application and for simplicity sake I’ll create a folder “Data” for data access layer. In you production application you will most likely want to put your data access layer into a separate project.</p>

<p>We’ll also use a repository pattern for our Data Access Layer(DAL) since it’s the most commonly used and easily to understand.</p>

<p>We’ll add an interface <code class="language-plaintext highlighter-rouge">ICustomerRepository</code> which will have two methods to save and retrive customers and create a base class <code class="language-plaintext highlighter-rouge">SqLiteBaseRepository</code> which will handle common logic between our repositories like creating database connections.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">interface</span> <span class="nc">ICustomerRepository</span>
<span class="p">{</span>
    <span class="n">Customer</span> <span class="nf">GetCustomer</span><span class="p">(</span><span class="kt">long</span> <span class="n">id</span><span class="p">);</span>
    <span class="k">void</span> <span class="nf">SaveCustomer</span><span class="p">(</span><span class="n">Customer</span> <span class="n">customer</span><span class="p">);</span>
<span class="p">}</span>

<span class="k">public</span> <span class="k">class</span> <span class="nc">SqLiteBaseRepository</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">static</span> <span class="kt">string</span> <span class="n">DbFile</span>
    <span class="p">{</span>
        <span class="k">get</span> <span class="p">{</span> <span class="k">return</span> <span class="n">Environment</span><span class="p">.</span><span class="n">CurrentDirectory</span> <span class="p">+</span> <span class="s">"\\SimpleDb.sqlite"</span><span class="p">;</span> <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">static</span> <span class="n">SQLiteConnection</span> <span class="nf">SimpleDbConnection</span><span class="p">()</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="k">new</span> <span class="nf">SQLiteConnection</span><span class="p">(</span><span class="s">"Data Source="</span> <span class="p">+</span> <span class="n">DbFile</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="using-dapper-as-our-simple-object-relational-mapping-orm">Using Dapper as our simple Object-relational mapping (ORM)</h3>

<p>Dapper is easy to use, fast and fits well for our simple data access layer. It has a simple API on top of already familiar SQL statements.</p>

<p>In your package manager console</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">Install-Package</span><span class="w"> </span><span class="nx">Dapper</span><span class="w">
</span></code></pre></div></div>

<p>In Customer Repository implementation (SqlLiteCustomerRepository) “SaveCustomer” method will first check if database file already exists and execute a create table script which if nothing is found, it will output a file to the environment runtime directory where your executable is located.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">void</span> <span class="nf">SaveCustomer</span><span class="p">(</span><span class="n">Customer</span> <span class="n">customer</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(!</span><span class="n">File</span><span class="p">.</span><span class="nf">Exists</span><span class="p">(</span><span class="n">DbFile</span><span class="p">))</span>
    <span class="p">{</span>
        <span class="nf">CreateDatabase</span><span class="p">();</span>
    <span class="p">}</span>

    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">cnn</span> <span class="p">=</span> <span class="nf">SimpleDbConnection</span><span class="p">())</span>
    <span class="p">{</span>
        <span class="n">cnn</span><span class="p">.</span><span class="nf">Open</span><span class="p">();</span>
        <span class="n">customer</span><span class="p">.</span><span class="n">Id</span> <span class="p">=</span> <span class="n">cnn</span><span class="p">.</span><span class="n">Query</span><span class="p">&lt;</span><span class="kt">long</span><span class="p">&gt;(</span>
            <span class="s">@"INSERT INTO Customer
            ( FirstName, LastName, DateOfBirth ) VALUES
            ( @FirstName, @LastName, @DateOfBirth );
            select last_insert_rowid()"</span><span class="p">,</span> <span class="n">customer</span><span class="p">).</span><span class="nf">First</span><span class="p">();</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="k">private</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">CreateDatabase</span><span class="p">()</span>
<span class="p">{</span>
    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">cnn</span> <span class="p">=</span> <span class="nf">SimpleDbConnection</span><span class="p">())</span>
    <span class="p">{</span>
        <span class="n">cnn</span><span class="p">.</span><span class="nf">Open</span><span class="p">();</span>
        <span class="n">cnn</span><span class="p">.</span><span class="nf">Execute</span><span class="p">(</span>
            <span class="s">@"create table Customer
                (
                    ID                                  integer identity primary key AUTOINCREMENT,
                    FirstName                           varchar(100) not null,
                    LastName                            varchar(100) not null,
                    DateOfBirth                         datetime not null
                )"</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Above Dapper maps our object to table field names in the query and also returns a long datatype with a newly inserted scoped identity. With SqLite scope identity has a different method last_insert_rowid() and we use that to get inserted customer id and assign it to our customer.</p>

<p>To retrieve customer we first check if database file exists first and then let dapper handle the rest.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="n">Customer</span> <span class="nf">GetCustomer</span><span class="p">(</span><span class="kt">long</span> <span class="n">id</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span> <span class="p">(!</span><span class="n">File</span><span class="p">.</span><span class="nf">Exists</span><span class="p">(</span><span class="n">DbFile</span><span class="p">))</span> <span class="k">return</span> <span class="k">null</span><span class="p">;</span>

    <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">cnn</span> <span class="p">=</span> <span class="nf">SimpleDbConnection</span><span class="p">())</span>
    <span class="p">{</span>
        <span class="n">cnn</span><span class="p">.</span><span class="nf">Open</span><span class="p">();</span>
        <span class="n">Customer</span> <span class="n">result</span> <span class="p">=</span> <span class="n">cnn</span><span class="p">.</span><span class="n">Query</span><span class="p">&lt;</span><span class="n">Customer</span><span class="p">&gt;(</span>
            <span class="s">@"SELECT Id, FirstName, LastName, DateOfBirth
            FROM Customer
            WHERE Id = @id"</span><span class="p">,</span> <span class="k">new</span> <span class="p">{</span> <span class="n">id</span> <span class="p">}).</span><span class="nf">FirstOrDefault</span><span class="p">();</span>
        <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And there you have it, an easy way to have a single file database with a simple ORM in your repository layer.</p>

<h4 id="source-code">Source code</h4>

<p>Here is the link to the source code if you would like to run the solution and try it for yourself. <a href="https://github.com/mercury2269/SQLiteDemo">Source Code</a></p>


										
					<p>Posted in: asp.net</p>
						
				
					<p>Tagged with: dapper, sqlite, and asp.net</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/asp-net/sqlite-simple-database-with-dapper/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/asp-net/sqlite-simple-database-with-dapper/]]></guid>
		<pubDate>2012-11-18T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Cross Domain Javascript Heartbeat]]></title>
		<description>
			<![CDATA[
				<p>If you are working with a heartbeat or keep alive from client side that goes between protocols (http to https) you will soon discover that it’s not as straightforward as simply sending an ajax request due to cross domain browser policy restrictions. So if your https version of the site has a secure cookie when you send an ajax request from unsecure page your request won’t have any cookies in the header since browser blocks this communications.</p>

<p>One solution that I though was quickest and most effective was to replace Ajax call with creating of a hidden iframe that requests a page which then refreshes your secure session. Since we don’t need any data and this is a fire and forget situation we don’t really care about any communication from secure iframe to the unsecure page.</p>

<p>Below is the sample javascript that checks if the user has been active on the page (tracking hovering over links and textboxes and then creating a invisible iframe and attaching it to the body of the DOM.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">SM</span> <span class="o">=</span> <span class="nx">SM</span> <span class="o">||</span> <span class="p">{};</span>
<span class="nx">SM</span><span class="p">.</span><span class="nx">keepAlive</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
  <span class="kd">var</span> <span class="nx">aliveUrl</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">https://blog.maskalik.com/keep-me-alive.aspx</span><span class="dl">"</span><span class="p">,</span>
    <span class="nx">interval</span> <span class="o">=</span> <span class="mi">60</span> <span class="o">*</span> <span class="mi">1000</span> <span class="o">*</span> <span class="mi">10</span><span class="p">,</span>
    <span class="nx">that</span> <span class="o">=</span> <span class="p">{},</span>
    <span class="nx">alive</span> <span class="o">=</span> <span class="kc">false</span><span class="p">,</span>
    <span class="nx">timer</span> <span class="o">=</span> <span class="p">{};</span>

  <span class="nx">that</span><span class="p">.</span><span class="nx">isActive</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="nx">alive</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
  <span class="p">};</span>

  <span class="nx">that</span><span class="p">.</span><span class="nx">removeTrackingIframeIfPresent</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">frame</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="dl">"</span><span class="s2">keep-alive-iframe</span><span class="dl">"</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">frame</span><span class="p">)</span> <span class="p">{</span>
      <span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nx">removeChild</span><span class="p">(</span><span class="nx">frame</span><span class="p">);</span>
    <span class="p">}</span>
  <span class="p">};</span>
  <span class="nx">that</span><span class="p">.</span><span class="nx">sendKeepAlive</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">alive</span><span class="p">)</span> <span class="p">{</span>
      <span class="nx">that</span><span class="p">.</span><span class="nx">removeTrackingIframeIfPresent</span><span class="p">();</span>
      <span class="kd">var</span> <span class="nx">frame</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">createElement</span><span class="p">(</span><span class="dl">"</span><span class="s2">iframe</span><span class="dl">"</span><span class="p">);</span>
      <span class="nx">frame</span><span class="p">.</span><span class="nx">setAttribute</span><span class="p">(</span><span class="dl">"</span><span class="s2">src</span><span class="dl">"</span><span class="p">,</span> <span class="nx">aliveUrl</span><span class="p">);</span>
      <span class="nx">frame</span><span class="p">.</span><span class="nx">setAttribute</span><span class="p">(</span><span class="dl">"</span><span class="s2">id</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">keep-alive-iframe</span><span class="dl">"</span><span class="p">);</span>
      <span class="nx">frame</span><span class="p">.</span><span class="nx">setAttribute</span><span class="p">(</span><span class="dl">"</span><span class="s2">style</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">display:none</span><span class="dl">"</span><span class="p">);</span>
      <span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nx">appendChild</span><span class="p">(</span><span class="nx">frame</span><span class="p">);</span>

      <span class="nx">alive</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>
    <span class="p">}</span>
  <span class="p">};</span>

  <span class="nx">that</span><span class="p">.</span><span class="nx">start</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">allTextareas</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">textarea</span><span class="dl">"</span><span class="p">);</span>
    <span class="nx">allTextareas</span><span class="p">.</span><span class="nx">live</span><span class="p">(</span><span class="dl">"</span><span class="s2">keyup</span><span class="dl">"</span><span class="p">,</span> <span class="nx">that</span><span class="p">.</span><span class="nx">isActive</span><span class="p">);</span>

    <span class="kd">var</span> <span class="nx">allLinks</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">a</span><span class="dl">"</span><span class="p">);</span>
    <span class="nx">allLinks</span><span class="p">.</span><span class="nx">live</span><span class="p">(</span><span class="dl">"</span><span class="s2">click mouseover</span><span class="dl">"</span><span class="p">,</span> <span class="nx">that</span><span class="p">.</span><span class="nx">isActive</span><span class="p">);</span>

    <span class="nx">timer</span> <span class="o">=</span> <span class="nx">setInterval</span><span class="p">(</span><span class="nx">that</span><span class="p">.</span><span class="nx">sendKeepAlive</span><span class="p">,</span> <span class="nx">interval</span><span class="p">);</span>
  <span class="p">};</span>

  <span class="k">return</span> <span class="nx">that</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div></div>

<p>And you start it on your page load or when you need it.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">alive</span> <span class="o">=</span> <span class="nx">SM</span><span class="p">.</span><span class="nx">keepAlive</span><span class="p">();</span>
<span class="nx">alive</span><span class="p">.</span><span class="nx">start</span><span class="p">();</span>
</code></pre></div></div>

<p>Also don’t forget that your requests can also be cached by the browser so you keep alive could just be served from browser cache without extending your session. To fix that we can set HttpResponse to send no cache headers.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">SetNoStore</span><span class="p">();</span>
<span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">AppendCacheExtension</span><span class="p">(</span><span class="s">"no-cache"</span><span class="p">);</span>
</code></pre></div></div>

<p>And there you have it a simple solution to a somewhat common problem.</p>

				<p>If you are working with a heartbeat or keep alive from client side that goes between protocols (http to https) you will soon discover that it’s not as straightforward as simply sending an ajax request due to cross domain browser policy restrictions. So if your https version of the site has a secure cookie when you send an ajax request from unsecure page your request won’t have any cookies in the header since browser blocks this communications.</p>

<p>One solution that I though was quickest and most effective was to replace Ajax call with creating of a hidden iframe that requests a page which then refreshes your secure session. Since we don’t need any data and this is a fire and forget situation we don’t really care about any communication from secure iframe to the unsecure page.</p>

<p>Below is the sample javascript that checks if the user has been active on the page (tracking hovering over links and textboxes and then creating a invisible iframe and attaching it to the body of the DOM.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">SM</span> <span class="o">=</span> <span class="nx">SM</span> <span class="o">||</span> <span class="p">{};</span>
<span class="nx">SM</span><span class="p">.</span><span class="nx">keepAlive</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
  <span class="kd">var</span> <span class="nx">aliveUrl</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">https://blog.maskalik.com/keep-me-alive.aspx</span><span class="dl">"</span><span class="p">,</span>
    <span class="nx">interval</span> <span class="o">=</span> <span class="mi">60</span> <span class="o">*</span> <span class="mi">1000</span> <span class="o">*</span> <span class="mi">10</span><span class="p">,</span>
    <span class="nx">that</span> <span class="o">=</span> <span class="p">{},</span>
    <span class="nx">alive</span> <span class="o">=</span> <span class="kc">false</span><span class="p">,</span>
    <span class="nx">timer</span> <span class="o">=</span> <span class="p">{};</span>

  <span class="nx">that</span><span class="p">.</span><span class="nx">isActive</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="nx">alive</span> <span class="o">=</span> <span class="kc">true</span><span class="p">;</span>
  <span class="p">};</span>

  <span class="nx">that</span><span class="p">.</span><span class="nx">removeTrackingIframeIfPresent</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">frame</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">getElementById</span><span class="p">(</span><span class="dl">"</span><span class="s2">keep-alive-iframe</span><span class="dl">"</span><span class="p">);</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">frame</span><span class="p">)</span> <span class="p">{</span>
      <span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nx">removeChild</span><span class="p">(</span><span class="nx">frame</span><span class="p">);</span>
    <span class="p">}</span>
  <span class="p">};</span>
  <span class="nx">that</span><span class="p">.</span><span class="nx">sendKeepAlive</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">alive</span><span class="p">)</span> <span class="p">{</span>
      <span class="nx">that</span><span class="p">.</span><span class="nx">removeTrackingIframeIfPresent</span><span class="p">();</span>
      <span class="kd">var</span> <span class="nx">frame</span> <span class="o">=</span> <span class="nb">document</span><span class="p">.</span><span class="nx">createElement</span><span class="p">(</span><span class="dl">"</span><span class="s2">iframe</span><span class="dl">"</span><span class="p">);</span>
      <span class="nx">frame</span><span class="p">.</span><span class="nx">setAttribute</span><span class="p">(</span><span class="dl">"</span><span class="s2">src</span><span class="dl">"</span><span class="p">,</span> <span class="nx">aliveUrl</span><span class="p">);</span>
      <span class="nx">frame</span><span class="p">.</span><span class="nx">setAttribute</span><span class="p">(</span><span class="dl">"</span><span class="s2">id</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">keep-alive-iframe</span><span class="dl">"</span><span class="p">);</span>
      <span class="nx">frame</span><span class="p">.</span><span class="nx">setAttribute</span><span class="p">(</span><span class="dl">"</span><span class="s2">style</span><span class="dl">"</span><span class="p">,</span> <span class="dl">"</span><span class="s2">display:none</span><span class="dl">"</span><span class="p">);</span>
      <span class="nb">document</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nx">appendChild</span><span class="p">(</span><span class="nx">frame</span><span class="p">);</span>

      <span class="nx">alive</span> <span class="o">=</span> <span class="kc">false</span><span class="p">;</span>
    <span class="p">}</span>
  <span class="p">};</span>

  <span class="nx">that</span><span class="p">.</span><span class="nx">start</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">allTextareas</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">textarea</span><span class="dl">"</span><span class="p">);</span>
    <span class="nx">allTextareas</span><span class="p">.</span><span class="nx">live</span><span class="p">(</span><span class="dl">"</span><span class="s2">keyup</span><span class="dl">"</span><span class="p">,</span> <span class="nx">that</span><span class="p">.</span><span class="nx">isActive</span><span class="p">);</span>

    <span class="kd">var</span> <span class="nx">allLinks</span> <span class="o">=</span> <span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">a</span><span class="dl">"</span><span class="p">);</span>
    <span class="nx">allLinks</span><span class="p">.</span><span class="nx">live</span><span class="p">(</span><span class="dl">"</span><span class="s2">click mouseover</span><span class="dl">"</span><span class="p">,</span> <span class="nx">that</span><span class="p">.</span><span class="nx">isActive</span><span class="p">);</span>

    <span class="nx">timer</span> <span class="o">=</span> <span class="nx">setInterval</span><span class="p">(</span><span class="nx">that</span><span class="p">.</span><span class="nx">sendKeepAlive</span><span class="p">,</span> <span class="nx">interval</span><span class="p">);</span>
  <span class="p">};</span>

  <span class="k">return</span> <span class="nx">that</span><span class="p">;</span>
<span class="p">};</span>
</code></pre></div></div>

<p>And you start it on your page load or when you need it.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">alive</span> <span class="o">=</span> <span class="nx">SM</span><span class="p">.</span><span class="nx">keepAlive</span><span class="p">();</span>
<span class="nx">alive</span><span class="p">.</span><span class="nx">start</span><span class="p">();</span>
</code></pre></div></div>

<p>Also don’t forget that your requests can also be cached by the browser so you keep alive could just be served from browser cache without extending your session. To fix that we can set HttpResponse to send no cache headers.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">SetNoStore</span><span class="p">();</span>
<span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">AppendCacheExtension</span><span class="p">(</span><span class="s">"no-cache"</span><span class="p">);</span>
</code></pre></div></div>

<p>And there you have it a simple solution to a somewhat common problem.</p>

										
					<p>Posted in: javascript</p>
						
				
					<p>Tagged with: heartbeat and javascript</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/javascript/cross-domain-keep-me-alive/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/javascript/cross-domain-keep-me-alive/]]></guid>
		<pubDate>2012-11-12T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[ASP.NET: Passing Optional Parameters to WebMethod]]></title>
		<description>
			<![CDATA[
				<p>WebMethods are still very convenient when you are working with WebForms and need a quick way to return json to your client javascript application.</p>

<p>There is one caveat with webmethod arguments they cannot be nullable and you cannot make them optional. For example, method below would still expect limit argument and if you don’t pass anything it will return an error.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">.</span><span class="nx">ajax</span><span class="p">({</span>
    <span class="na">type</span><span class="p">:</span> <span class="dl">'</span><span class="s1">POST</span><span class="dl">'</span><span class="p">,</span>
    <span class="na">url</span><span class="p">:</span> <span class="dl">'</span><span class="s1">Default.aspx/TestNullableArgument</span><span class="dl">'</span><span class="p">,</span>
    <span class="o">**</span><span class="na">data</span><span class="p">:</span> <span class="dl">'</span><span class="s1">{}</span><span class="dl">'</span><span class="p">,</span><span class="o">**</span>
    <span class="na">contentType</span><span class="p">:</span> <span class="dl">'</span><span class="s1">application/json; charset=utf-8</span><span class="dl">'</span><span class="p">,</span>
    <span class="na">dataType</span><span class="p">:</span> <span class="dl">'</span><span class="s1">json</span><span class="dl">'</span><span class="p">,</span>
    <span class="na">success</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">msg</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">callback</span><span class="p">(</span><span class="nx">msg</span><span class="p">.</span><span class="nx">d</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">});</span>
</code></pre></div></div>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">WebMethod</span><span class="p">]</span>
<span class="k">public</span> <span class="k">static</span> <span class="kt">bool</span> <span class="nf">TestNullableArgument</span><span class="p">(</span><span class="kt">int</span><span class="p">?</span> <span class="n">limit</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="k">true</span><span class="p">;</span>
<span class="p">}</span>

</code></pre></div></div>

<p>Will result in:</p>

<blockquote>
  <p>Invalid web service call, missing
value for parameter</p>
</blockquote>

<p>One way we can fix is to add send a null parameter like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">$</span><span class="p">.</span><span class="nf">ajax</span><span class="p">({</span>
    <span class="n">type</span><span class="p">:</span> <span class="err">'</span><span class="n">POST</span><span class="err">'</span><span class="p">,</span>
    <span class="n">url</span><span class="p">:</span> <span class="err">'</span><span class="n">Default</span><span class="p">.</span><span class="n">aspx</span><span class="p">/</span><span class="n">TestNullableArgument</span><span class="err">'</span><span class="p">,</span>
    <span class="p">**</span><span class="n">data</span><span class="p">:</span> <span class="err">'</span><span class="p">{</span><span class="s">"limit"</span><span class="p">:</span><span class="k">null</span><span class="p">}</span><span class="err">'</span><span class="p">,**</span>
    <span class="n">contentType</span><span class="p">:</span> <span class="err">'</span><span class="n">application</span><span class="p">/</span><span class="n">json</span><span class="p">;</span> <span class="n">charset</span><span class="p">=</span><span class="n">utf</span><span class="p">-</span><span class="m">8</span><span class="err">'</span><span class="p">,</span>
    <span class="n">dataType</span><span class="p">:</span> <span class="err">'</span><span class="n">json</span><span class="err">'</span><span class="p">,</span>
    <span class="n">success</span><span class="p">:</span> <span class="nf">function</span> <span class="p">(</span><span class="n">msg</span><span class="p">)</span> <span class="p">{</span>
        <span class="nf">callback</span><span class="p">(</span><span class="n">msg</span><span class="p">.</span><span class="n">d</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">});</span>
</code></pre></div></div>

<p>However it still does not make <code class="language-plaintext highlighter-rouge">int? limit</code> argument optional and webmethod would always expect to have that parameter. A nice pattern if you need optional WebMethod arguements is to send argument data as serialized json object string and then de-serialize it in your webmethod.</p>

<p>For example we have a grid that needs to be searched, sorted and paged. However you don’t always want to send all those parameters as null. A lot of times you want it paged but not sorted or filtered and you don’t want to duplicate the code and overload all possible webmethod arguments. So by sending json string we create a dynamic parameters object which can have optional properties.</p>

<p>First we define our query object:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">GridQuery</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="kt">int</span><span class="p">?</span> <span class="n">Limit</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">int</span><span class="p">?</span> <span class="n">Offset</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">FilterType</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">FilterTypeValue</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="n">DateTime</span><span class="p">?</span> <span class="n">Start</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="n">DateTime</span><span class="p">?</span> <span class="n">End</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Modify our WebMethod to accept string gridQuery argument:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">WebMethod</span><span class="p">]</span>
<span class="k">public</span> <span class="k">static</span> <span class="n">Result</span> <span class="nf">GetGridData</span><span class="p">(</span><span class="kt">string</span> <span class="n">gridQuery</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">var</span> <span class="n">query</span> <span class="p">=</span> <span class="n">JsonConvert</span><span class="p">.</span><span class="n">DeserializeObject</span><span class="p">&lt;</span><span class="n">GridQuery</span><span class="p">&gt;(</span><span class="n">gridQuery</span><span class="p">);</span>
    <span class="p">...</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Now in our client javascript we can create a query object without having to specify all other options. And then send it as a serilized json parameter</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">params</span> <span class="o">=</span> <span class="p">{</span> <span class="na">limit</span><span class="p">:</span> <span class="mi">10</span><span class="p">,</span> <span class="na">offset</span><span class="p">:</span> <span class="mi">20</span> <span class="p">}</span>

<span class="nx">$</span><span class="p">.</span><span class="nx">ajax</span><span class="p">({</span>
    <span class="na">type</span><span class="p">:</span> <span class="dl">'</span><span class="s1">POST</span><span class="dl">'</span><span class="p">,</span>
    <span class="na">url</span><span class="p">:</span> <span class="dl">'</span><span class="s1">Default.aspx/GetGridData</span><span class="dl">'</span><span class="p">,</span>
    <span class="o">**</span><span class="na">data</span><span class="p">:</span> <span class="dl">"</span><span class="s2">{'gridQuery':'</span><span class="dl">"</span> <span class="o">+</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">params</span><span class="p">)</span> <span class="o">+</span> <span class="dl">"</span><span class="s2">'}</span><span class="dl">"</span><span class="p">,</span><span class="o">**</span>
    <span class="na">contentType</span><span class="p">:</span> <span class="dl">'</span><span class="s1">application/json; charset=utf-8</span><span class="dl">'</span><span class="p">,</span>
    <span class="na">dataType</span><span class="p">:</span> <span class="dl">'</span><span class="s1">json</span><span class="dl">'</span><span class="p">,</span>
    <span class="na">success</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">msg</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">msg</span><span class="p">.</span><span class="nx">d</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">});</span>
</code></pre></div></div>

<p>Now when our object gets deserialized we have optional arguments. Simple and effective.</p>

				<p>WebMethods are still very convenient when you are working with WebForms and need a quick way to return json to your client javascript application.</p>

<p>There is one caveat with webmethod arguments they cannot be nullable and you cannot make them optional. For example, method below would still expect limit argument and if you don’t pass anything it will return an error.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">.</span><span class="nx">ajax</span><span class="p">({</span>
    <span class="na">type</span><span class="p">:</span> <span class="dl">'</span><span class="s1">POST</span><span class="dl">'</span><span class="p">,</span>
    <span class="na">url</span><span class="p">:</span> <span class="dl">'</span><span class="s1">Default.aspx/TestNullableArgument</span><span class="dl">'</span><span class="p">,</span>
    <span class="o">**</span><span class="na">data</span><span class="p">:</span> <span class="dl">'</span><span class="s1">{}</span><span class="dl">'</span><span class="p">,</span><span class="o">**</span>
    <span class="na">contentType</span><span class="p">:</span> <span class="dl">'</span><span class="s1">application/json; charset=utf-8</span><span class="dl">'</span><span class="p">,</span>
    <span class="na">dataType</span><span class="p">:</span> <span class="dl">'</span><span class="s1">json</span><span class="dl">'</span><span class="p">,</span>
    <span class="na">success</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">msg</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">callback</span><span class="p">(</span><span class="nx">msg</span><span class="p">.</span><span class="nx">d</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">});</span>
</code></pre></div></div>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">WebMethod</span><span class="p">]</span>
<span class="k">public</span> <span class="k">static</span> <span class="kt">bool</span> <span class="nf">TestNullableArgument</span><span class="p">(</span><span class="kt">int</span><span class="p">?</span> <span class="n">limit</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="k">true</span><span class="p">;</span>
<span class="p">}</span>

</code></pre></div></div>

<p>Will result in:</p>

<blockquote>
  <p>Invalid web service call, missing
value for parameter</p>
</blockquote>

<p>One way we can fix is to add send a null parameter like this:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="err">$</span><span class="p">.</span><span class="nf">ajax</span><span class="p">({</span>
    <span class="n">type</span><span class="p">:</span> <span class="err">'</span><span class="n">POST</span><span class="err">'</span><span class="p">,</span>
    <span class="n">url</span><span class="p">:</span> <span class="err">'</span><span class="n">Default</span><span class="p">.</span><span class="n">aspx</span><span class="p">/</span><span class="n">TestNullableArgument</span><span class="err">'</span><span class="p">,</span>
    <span class="p">**</span><span class="n">data</span><span class="p">:</span> <span class="err">'</span><span class="p">{</span><span class="s">"limit"</span><span class="p">:</span><span class="k">null</span><span class="p">}</span><span class="err">'</span><span class="p">,**</span>
    <span class="n">contentType</span><span class="p">:</span> <span class="err">'</span><span class="n">application</span><span class="p">/</span><span class="n">json</span><span class="p">;</span> <span class="n">charset</span><span class="p">=</span><span class="n">utf</span><span class="p">-</span><span class="m">8</span><span class="err">'</span><span class="p">,</span>
    <span class="n">dataType</span><span class="p">:</span> <span class="err">'</span><span class="n">json</span><span class="err">'</span><span class="p">,</span>
    <span class="n">success</span><span class="p">:</span> <span class="nf">function</span> <span class="p">(</span><span class="n">msg</span><span class="p">)</span> <span class="p">{</span>
        <span class="nf">callback</span><span class="p">(</span><span class="n">msg</span><span class="p">.</span><span class="n">d</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">});</span>
</code></pre></div></div>

<p>However it still does not make <code class="language-plaintext highlighter-rouge">int? limit</code> argument optional and webmethod would always expect to have that parameter. A nice pattern if you need optional WebMethod arguements is to send argument data as serialized json object string and then de-serialize it in your webmethod.</p>

<p>For example we have a grid that needs to be searched, sorted and paged. However you don’t always want to send all those parameters as null. A lot of times you want it paged but not sorted or filtered and you don’t want to duplicate the code and overload all possible webmethod arguments. So by sending json string we create a dynamic parameters object which can have optional properties.</p>

<p>First we define our query object:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">GridQuery</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="kt">int</span><span class="p">?</span> <span class="n">Limit</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">int</span><span class="p">?</span> <span class="n">Offset</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">FilterType</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">FilterTypeValue</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="n">DateTime</span><span class="p">?</span> <span class="n">Start</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="n">DateTime</span><span class="p">?</span> <span class="n">End</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Modify our WebMethod to accept string gridQuery argument:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">WebMethod</span><span class="p">]</span>
<span class="k">public</span> <span class="k">static</span> <span class="n">Result</span> <span class="nf">GetGridData</span><span class="p">(</span><span class="kt">string</span> <span class="n">gridQuery</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">var</span> <span class="n">query</span> <span class="p">=</span> <span class="n">JsonConvert</span><span class="p">.</span><span class="n">DeserializeObject</span><span class="p">&lt;</span><span class="n">GridQuery</span><span class="p">&gt;(</span><span class="n">gridQuery</span><span class="p">);</span>
    <span class="p">...</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Now in our client javascript we can create a query object without having to specify all other options. And then send it as a serilized json parameter</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">params</span> <span class="o">=</span> <span class="p">{</span> <span class="na">limit</span><span class="p">:</span> <span class="mi">10</span><span class="p">,</span> <span class="na">offset</span><span class="p">:</span> <span class="mi">20</span> <span class="p">}</span>

<span class="nx">$</span><span class="p">.</span><span class="nx">ajax</span><span class="p">({</span>
    <span class="na">type</span><span class="p">:</span> <span class="dl">'</span><span class="s1">POST</span><span class="dl">'</span><span class="p">,</span>
    <span class="na">url</span><span class="p">:</span> <span class="dl">'</span><span class="s1">Default.aspx/GetGridData</span><span class="dl">'</span><span class="p">,</span>
    <span class="o">**</span><span class="na">data</span><span class="p">:</span> <span class="dl">"</span><span class="s2">{'gridQuery':'</span><span class="dl">"</span> <span class="o">+</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="nx">params</span><span class="p">)</span> <span class="o">+</span> <span class="dl">"</span><span class="s2">'}</span><span class="dl">"</span><span class="p">,</span><span class="o">**</span>
    <span class="na">contentType</span><span class="p">:</span> <span class="dl">'</span><span class="s1">application/json; charset=utf-8</span><span class="dl">'</span><span class="p">,</span>
    <span class="na">dataType</span><span class="p">:</span> <span class="dl">'</span><span class="s1">json</span><span class="dl">'</span><span class="p">,</span>
    <span class="na">success</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">msg</span><span class="p">)</span> <span class="p">{</span>
        <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="nx">msg</span><span class="p">.</span><span class="nx">d</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">});</span>
</code></pre></div></div>

<p>Now when our object gets deserialized we have optional arguments. Simple and effective.</p>

										
					<p>Posted in: asp.net</p>
						
				
					<p>Tagged with: asp.net and webmethod</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/asp-net/webmethod-optional-arguments-with-json/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/asp-net/webmethod-optional-arguments-with-json/]]></guid>
		<pubDate>2012-09-04T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[IE9 Redirect Caching Feature Might Cause Frustration]]></title>
		<description>
			<![CDATA[
				<p>If you have been doing web development for some time I’m sure you have come across internet explorer caching feature. A less known redirect caching feature that was released in IE9 has just caused me a day of frustration and hopefully it will save you a day of nightmare.</p>

<p>From msdn article on <a href="http://blogs.msdn.com/b/ie/archive/2010/07/14/caching-improvements-in-internet-explorer-9.aspx">caching improvements</a> in IE9</p>

<blockquote>
  <p>Internet Explorer 9 now supports
caching of HTTP redirect responses, as
described by RFC 2616. Responses with
Permanent Redirect status (301) are
cacheable unless there are headers
which forbid it (e.g. Cache-Control:
no-cache) and those with Temporary
Redirect status (302 or 307) are
cacheable if there are headers which
permit it (e.g. Cache-Control:
max-age=120).</p>
</blockquote>

<p>In that article it even warns developers that your “misconfigured” application might not work.</p>

<blockquote>
  <p>While this significantly improves
performance, web applications that are
misconfigured might not work as
expected</p>
</blockquote>

<p>So unless you are up to date on all msdn internet explorer blog posts you wouldn’t know that IE9 will cache your redirects unless you tell it not to. The problem with redirect caching is that if your server has some significant logic, like setting cookies on redirect it will no longer work in IE9, because the request will never be sent to the server.</p>

<p>What’s worse is that when you are trying to troubleshoot it present itself as bizarre behavior. You see redirect happening in the “Net” tab of developer tools but it never hits your server. Doesn’t hit any HttpModules or any part of asp.net request handling pipeline. And to add to insult Firefox works with no issues :) At one point you begin to imagine that maybe IE has some kind of a secret agreement with asp.net, but that’s just your brain looking for ridiculous ways to justify the problem.</p>

<p>So the rule of thumb: <strong>If you have a redirect that sets important cookies you will need to make sure that you tell IE not to cache the redirect.</strong> You can read more about <a href="http://blog.maskalik.com/asp-net/resolving-browser-back-button-with-caching-pages">caching headers</a> or to fix this problem simply add following lines to your redirect code.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">SetNoStore</span><span class="p">();</span>
<span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">AppendCacheExtension</span><span class="p">(</span><span class="s">"no-cache"</span><span class="p">);</span>
</code></pre></div></div>


				<p>If you have been doing web development for some time I’m sure you have come across internet explorer caching feature. A less known redirect caching feature that was released in IE9 has just caused me a day of frustration and hopefully it will save you a day of nightmare.</p>

<p>From msdn article on <a href="http://blogs.msdn.com/b/ie/archive/2010/07/14/caching-improvements-in-internet-explorer-9.aspx">caching improvements</a> in IE9</p>

<blockquote>
  <p>Internet Explorer 9 now supports
caching of HTTP redirect responses, as
described by RFC 2616. Responses with
Permanent Redirect status (301) are
cacheable unless there are headers
which forbid it (e.g. Cache-Control:
no-cache) and those with Temporary
Redirect status (302 or 307) are
cacheable if there are headers which
permit it (e.g. Cache-Control:
max-age=120).</p>
</blockquote>

<p>In that article it even warns developers that your “misconfigured” application might not work.</p>

<blockquote>
  <p>While this significantly improves
performance, web applications that are
misconfigured might not work as
expected</p>
</blockquote>

<p>So unless you are up to date on all msdn internet explorer blog posts you wouldn’t know that IE9 will cache your redirects unless you tell it not to. The problem with redirect caching is that if your server has some significant logic, like setting cookies on redirect it will no longer work in IE9, because the request will never be sent to the server.</p>

<p>What’s worse is that when you are trying to troubleshoot it present itself as bizarre behavior. You see redirect happening in the “Net” tab of developer tools but it never hits your server. Doesn’t hit any HttpModules or any part of asp.net request handling pipeline. And to add to insult Firefox works with no issues :) At one point you begin to imagine that maybe IE has some kind of a secret agreement with asp.net, but that’s just your brain looking for ridiculous ways to justify the problem.</p>

<p>So the rule of thumb: <strong>If you have a redirect that sets important cookies you will need to make sure that you tell IE not to cache the redirect.</strong> You can read more about <a href="http://blog.maskalik.com/asp-net/resolving-browser-back-button-with-caching-pages">caching headers</a> or to fix this problem simply add following lines to your redirect code.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">SetNoStore</span><span class="p">();</span>
<span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">AppendCacheExtension</span><span class="p">(</span><span class="s">"no-cache"</span><span class="p">);</span>
</code></pre></div></div>


										
					<p>Posted in: asp.net</p>
						
				
					<p>Tagged with: ie9, redirect, asp.net, and browser-cache</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/asp-net/ie9-redirect-caching-nightmare/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/asp-net/ie9-redirect-caching-nightmare/]]></guid>
		<pubDate>2012-08-21T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Setting Domain in HttpCookies Element in Web.Config Is Not a Silver Bullet.]]></title>
		<description>
			<![CDATA[
				<p>If you are using <code class="language-plaintext highlighter-rouge">&lt;httpCookies domain=".maskalik.com" /&gt;</code> element in your web.config you might think that all your cookies be default will have “.maskalik.com” domain set. I thought the same until I had to debug a weird problem where cookies were not being removed properly.</p>

<p>Let’s see if you can spot the problem, I certainly couldn’t at first. We are checking if cookie is already set and removing it if it is.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">[</span><span class="s">"Color"</span><span class="p">]</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">HttpCookie</span> <span class="n">colorCookie</span> <span class="p">=</span> <span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">[</span><span class="s">"Color"</span><span class="p">];</span>
    <span class="n">colorCookie</span><span class="p">.</span><span class="n">Expires</span> <span class="p">=</span> <span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">.</span><span class="nf">AddDays</span><span class="p">(-</span><span class="m">1</span><span class="p">);</span>
    <span class="n">Response</span><span class="p">.</span><span class="n">Cookies</span><span class="p">.</span><span class="nf">Set</span><span class="p">(</span><span class="n">colorCookie</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>By looking at the network tab in the internet explorer tools I can see that cookie that is being sent from the browser has a .maskalik.com domain. And server responds with expired cookie that has www.maskalik.com so the original cookie that browser sent does not match what the server sent therefore does not get removed. But how is that possible, all of our cookies should have domain specified by default. Apparently that’s not the case. If you look at the implementation of the System.Web.HttpCookie you can see that default values are only set when you create a cookie by using a constructor:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="nf">HttpCookie</span><span class="p">(</span><span class="kt">string</span> <span class="n">name</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">this</span><span class="p">.</span><span class="n">_name</span> <span class="p">=</span> <span class="n">name</span><span class="p">;</span>
    <span class="p">**</span><span class="k">this</span><span class="p">.</span><span class="nf">SetDefaultsFromConfig</span><span class="p">();**</span>
    <span class="k">this</span><span class="p">.</span><span class="n">_changed</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">public</span> <span class="nf">HttpCookie</span><span class="p">(</span><span class="kt">string</span> <span class="n">name</span><span class="p">,</span> <span class="kt">string</span> <span class="k">value</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">this</span><span class="p">.</span><span class="n">_name</span> <span class="p">=</span> <span class="n">name</span><span class="p">;</span>
    <span class="k">this</span><span class="p">.</span><span class="n">_stringValue</span> <span class="p">=</span> <span class="k">value</span><span class="p">;</span>
    <span class="p">**</span><span class="k">this</span><span class="p">.</span><span class="nf">SetDefaultsFromConfig</span><span class="p">();**</span>
    <span class="k">this</span><span class="p">.</span><span class="n">_changed</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>So when we read values from the Request.Cookies collection those values don’t have a domain set and we are expiring cookie with the different domain which doesn’t remove the original cookie.</p>

<p>So our fix would be pretty simple, instead of getting an existing cookie we create a new cookie with the same name that way the default domain is going to get properly set by HttpCookie constructor.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">[</span><span class="s">"Color"</span><span class="p">]</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">HttpCookie</span> <span class="n">colorCookie</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">HttpCookie</span><span class="p">(</span><span class="s">"Color"</span><span class="p">);</span>
    <span class="n">colorCookie</span><span class="p">.</span><span class="n">Expires</span> <span class="p">=</span> <span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">.</span><span class="nf">AddDays</span><span class="p">(-</span><span class="m">1</span><span class="p">);</span>
    <span class="n">Response</span><span class="p">.</span><span class="n">Cookies</span><span class="p">.</span><span class="nf">Set</span><span class="p">(</span><span class="n">colorCookie</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Lesson learned, hopefully it will help someone.</p>

				<p>If you are using <code class="language-plaintext highlighter-rouge">&lt;httpCookies domain=".maskalik.com" /&gt;</code> element in your web.config you might think that all your cookies be default will have “.maskalik.com” domain set. I thought the same until I had to debug a weird problem where cookies were not being removed properly.</p>

<p>Let’s see if you can spot the problem, I certainly couldn’t at first. We are checking if cookie is already set and removing it if it is.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">[</span><span class="s">"Color"</span><span class="p">]</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">HttpCookie</span> <span class="n">colorCookie</span> <span class="p">=</span> <span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">[</span><span class="s">"Color"</span><span class="p">];</span>
    <span class="n">colorCookie</span><span class="p">.</span><span class="n">Expires</span> <span class="p">=</span> <span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">.</span><span class="nf">AddDays</span><span class="p">(-</span><span class="m">1</span><span class="p">);</span>
    <span class="n">Response</span><span class="p">.</span><span class="n">Cookies</span><span class="p">.</span><span class="nf">Set</span><span class="p">(</span><span class="n">colorCookie</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>By looking at the network tab in the internet explorer tools I can see that cookie that is being sent from the browser has a .maskalik.com domain. And server responds with expired cookie that has www.maskalik.com so the original cookie that browser sent does not match what the server sent therefore does not get removed. But how is that possible, all of our cookies should have domain specified by default. Apparently that’s not the case. If you look at the implementation of the System.Web.HttpCookie you can see that default values are only set when you create a cookie by using a constructor:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="nf">HttpCookie</span><span class="p">(</span><span class="kt">string</span> <span class="n">name</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">this</span><span class="p">.</span><span class="n">_name</span> <span class="p">=</span> <span class="n">name</span><span class="p">;</span>
    <span class="p">**</span><span class="k">this</span><span class="p">.</span><span class="nf">SetDefaultsFromConfig</span><span class="p">();**</span>
    <span class="k">this</span><span class="p">.</span><span class="n">_changed</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">public</span> <span class="nf">HttpCookie</span><span class="p">(</span><span class="kt">string</span> <span class="n">name</span><span class="p">,</span> <span class="kt">string</span> <span class="k">value</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">this</span><span class="p">.</span><span class="n">_name</span> <span class="p">=</span> <span class="n">name</span><span class="p">;</span>
    <span class="k">this</span><span class="p">.</span><span class="n">_stringValue</span> <span class="p">=</span> <span class="k">value</span><span class="p">;</span>
    <span class="p">**</span><span class="k">this</span><span class="p">.</span><span class="nf">SetDefaultsFromConfig</span><span class="p">();**</span>
    <span class="k">this</span><span class="p">.</span><span class="n">_changed</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>So when we read values from the Request.Cookies collection those values don’t have a domain set and we are expiring cookie with the different domain which doesn’t remove the original cookie.</p>

<p>So our fix would be pretty simple, instead of getting an existing cookie we create a new cookie with the same name that way the default domain is going to get properly set by HttpCookie constructor.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">[</span><span class="s">"Color"</span><span class="p">]</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">HttpCookie</span> <span class="n">colorCookie</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">HttpCookie</span><span class="p">(</span><span class="s">"Color"</span><span class="p">);</span>
    <span class="n">colorCookie</span><span class="p">.</span><span class="n">Expires</span> <span class="p">=</span> <span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">.</span><span class="nf">AddDays</span><span class="p">(-</span><span class="m">1</span><span class="p">);</span>
    <span class="n">Response</span><span class="p">.</span><span class="n">Cookies</span><span class="p">.</span><span class="nf">Set</span><span class="p">(</span><span class="n">colorCookie</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Lesson learned, hopefully it will help someone.</p>

										
					<p>Posted in: asp.net</p>
						
				
					<p>Tagged with: asp.net, httpcookie, and webconfig</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/asp-net/httcookies-domain-web-config/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/asp-net/httcookies-domain-web-config/]]></guid>
		<pubDate>2012-08-21T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Javascript patterns]]></title>
		<description>
			<![CDATA[
				<h3 id="immediate-function">Immediate Function</h3>

<p>Execute function as soon as it’s defined, variables declared inside have local function scope. Can return values or other functions.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">sayHello</span> <span class="o">=</span> <span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
  <span class="kd">var</span> <span class="nx">sometext</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">Hello world</span><span class="dl">"</span><span class="p">;</span>
  <span class="k">return</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="k">return</span> <span class="nx">sometext</span><span class="p">;</span>
  <span class="p">};</span>
<span class="p">})();</span>
</code></pre></div></div>

<h3 id="privacy-module-pattern">Privacy, Module Pattern</h3>

<p>Private variables can be hidden within the scope of a function, in the case below foo is a private variable.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">foo</span> <span class="o">=</span> <span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
  <span class="c1">//private</span>
  <span class="kd">var</span> <span class="nx">bar</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">Hello I'm private</span><span class="dl">"</span><span class="p">;</span>

  <span class="c1">//public accessor</span>
  <span class="k">return</span> <span class="p">{</span>
    <span class="na">getBar</span><span class="p">:</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
      <span class="k">return</span> <span class="nx">bar</span><span class="p">;</span>
    <span class="p">},</span>
  <span class="p">};</span>
<span class="p">})();</span>
</code></pre></div></div>

<p>Since private variables will be recreated every time you can save memory by putting private variables into prototypes.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">Fast</span><span class="p">()</span> <span class="p">{}</span>

<span class="nx">Fast</span><span class="p">.</span><span class="nx">prototype</span> <span class="o">=</span> <span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
  <span class="c1">//private</span>
  <span class="kd">var</span> <span class="nx">fastFoo</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">Hello I'm fast private Foo</span><span class="dl">"</span><span class="p">;</span>
  <span class="c1">//public prototype</span>
  <span class="k">return</span> <span class="p">{</span>
    <span class="na">getFastFoo</span><span class="p">:</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
      <span class="k">return</span> <span class="nx">fastFoo</span><span class="p">;</span>
    <span class="p">},</span>
  <span class="p">};</span>
<span class="p">})();</span>
</code></pre></div></div>

				<h3 id="immediate-function">Immediate Function</h3>

<p>Execute function as soon as it’s defined, variables declared inside have local function scope. Can return values or other functions.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">sayHello</span> <span class="o">=</span> <span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
  <span class="kd">var</span> <span class="nx">sometext</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">Hello world</span><span class="dl">"</span><span class="p">;</span>
  <span class="k">return</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="k">return</span> <span class="nx">sometext</span><span class="p">;</span>
  <span class="p">};</span>
<span class="p">})();</span>
</code></pre></div></div>

<h3 id="privacy-module-pattern">Privacy, Module Pattern</h3>

<p>Private variables can be hidden within the scope of a function, in the case below foo is a private variable.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">foo</span> <span class="o">=</span> <span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
  <span class="c1">//private</span>
  <span class="kd">var</span> <span class="nx">bar</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">Hello I'm private</span><span class="dl">"</span><span class="p">;</span>

  <span class="c1">//public accessor</span>
  <span class="k">return</span> <span class="p">{</span>
    <span class="na">getBar</span><span class="p">:</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
      <span class="k">return</span> <span class="nx">bar</span><span class="p">;</span>
    <span class="p">},</span>
  <span class="p">};</span>
<span class="p">})();</span>
</code></pre></div></div>

<p>Since private variables will be recreated every time you can save memory by putting private variables into prototypes.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">Fast</span><span class="p">()</span> <span class="p">{}</span>

<span class="nx">Fast</span><span class="p">.</span><span class="nx">prototype</span> <span class="o">=</span> <span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
  <span class="c1">//private</span>
  <span class="kd">var</span> <span class="nx">fastFoo</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">Hello I'm fast private Foo</span><span class="dl">"</span><span class="p">;</span>
  <span class="c1">//public prototype</span>
  <span class="k">return</span> <span class="p">{</span>
    <span class="na">getFastFoo</span><span class="p">:</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
      <span class="k">return</span> <span class="nx">fastFoo</span><span class="p">;</span>
    <span class="p">},</span>
  <span class="p">};</span>
<span class="p">})();</span>
</code></pre></div></div>

										
					<p>Posted in: guides</p>
						
				
					<p>Tagged with: javascript</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/guides/javascript-patterns/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/guides/javascript-patterns/]]></guid>
		<pubDate>2012-08-08T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Creating Service Broker Status Dashboard With Knockoutjs]]></title>
		<description>
			<![CDATA[
				<h3 id="what-am-i-trying-to-solve">What am I trying to solve..</h3>

<p><em>If you are not familiar with Service Broker you can still use this as an example for Knockoutjs and ASP.NET Webmethods.</em></p>

<p>The biggest pain point with Service Broker (SB) is how long it takes to understand what exactly is happening when you a have a problem. In order to find a problem sometimes you need to execute good amount of queries, read through the results analyze them and eventually find out what the issue is. It becomes a lot more complicated when you have event notifications and queue monitors on your queues. And if you don’t always work with SB you will eventually forget how things work.</p>

<p>In this post we will have some fun building a color coded status page which will show status of our queues, events, messages and queue monitors. It should be as easy as glancing at the screen and if anything is red that means there is a problem. As a bonus you can also add internal activation on your own.</p>

<h3 id="create-a-health-status-query">Create a health status query</h3>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="o">*</span> <span class="k">FROM</span>
<span class="p">(</span>
<span class="k">SELECT</span> <span class="n">Q</span><span class="p">.</span><span class="n">Name</span>
    <span class="p">,</span><span class="k">CASE</span>
        <span class="k">WHEN</span> <span class="n">EN</span><span class="p">.</span><span class="n">name</span> <span class="k">LIKE</span> <span class="s1">'%QueueActivation'</span>
            <span class="k">THEN</span> <span class="s1">'Activation'</span>
        <span class="k">WHEN</span> <span class="n">EN</span><span class="p">.</span><span class="n">name</span> <span class="k">LIKE</span> <span class="s1">'%QueueDisabledEmail'</span>
            <span class="k">THEN</span> <span class="s1">'DisabledEmail'</span>
        <span class="k">WHEN</span> <span class="n">EN</span><span class="p">.</span><span class="n">name</span> <span class="k">LIKE</span> <span class="s1">'%QueueDisabled'</span>
            <span class="k">THEN</span> <span class="s1">'Resolve'</span>
    <span class="k">END</span> <span class="k">AS</span> <span class="n">EventLetter</span>
    <span class="p">,</span><span class="n">QM</span><span class="p">.</span><span class="k">state</span>
    <span class="p">,</span><span class="n">Q</span><span class="p">.</span><span class="n">is_enqueue_enabled</span> <span class="k">AS</span> <span class="p">[</span><span class="n">Enabled</span><span class="p">]</span>
    <span class="p">,</span><span class="n">po</span><span class="p">.</span><span class="k">rows</span> <span class="k">AS</span> <span class="n">MessageCount</span>
    <span class="p">,</span><span class="n">Q</span><span class="p">.</span><span class="n">is_activation_enabled</span> <span class="k">as</span> <span class="n">InternalActivationEnabled</span>
    <span class="p">,</span><span class="n">Q</span><span class="p">.</span><span class="n">activation_procedure</span>	<span class="k">as</span> <span class="n">InternalActivationProcedureName</span>
<span class="k">FROM</span> <span class="n">sys</span><span class="p">.</span><span class="n">service_queues</span> <span class="k">AS</span> <span class="n">Q</span>
    <span class="k">JOIN</span> <span class="n">sys</span><span class="p">.</span><span class="n">objects</span> <span class="k">AS</span> <span class="n">o</span> <span class="k">ON</span> <span class="n">o</span><span class="p">.</span><span class="n">parent_object_id</span> <span class="o">=</span> <span class="n">Q</span><span class="p">.</span><span class="n">object_id</span>
    <span class="k">JOIN</span> <span class="n">sys</span><span class="p">.</span><span class="n">partitions</span> <span class="k">AS</span> <span class="n">po</span> <span class="k">ON</span> <span class="n">po</span><span class="p">.</span><span class="n">object_id</span> <span class="o">=</span> <span class="n">o</span><span class="p">.</span><span class="n">object_id</span>
    <span class="k">JOIN</span> <span class="n">sys</span><span class="p">.</span><span class="n">objects</span> <span class="k">AS</span> <span class="n">qo</span> <span class="k">ON</span> <span class="n">o</span><span class="p">.</span><span class="n">parent_object_id</span> <span class="o">=</span> <span class="n">qo</span><span class="p">.</span><span class="n">object_id</span>
    <span class="k">LEFT</span> <span class="k">JOIN</span> <span class="n">sys</span><span class="p">.</span><span class="n">event_notifications</span> <span class="k">AS</span> <span class="n">EN</span> <span class="k">ON</span> <span class="n">Q</span><span class="p">.</span><span class="n">object_id</span> <span class="o">=</span> <span class="n">EN</span><span class="p">.</span><span class="n">parent_id</span>
    <span class="k">LEFT</span> <span class="k">JOIN</span> <span class="n">sys</span><span class="p">.</span><span class="n">dm_broker_queue_monitors</span> <span class="k">AS</span> <span class="n">QM</span> <span class="k">ON</span> <span class="n">Q</span><span class="p">.</span><span class="n">object_id</span> <span class="o">=</span> <span class="n">QM</span><span class="p">.</span><span class="n">queue_id</span>
<span class="k">WHERE</span> <span class="n">Q</span><span class="p">.</span><span class="n">is_ms_shipped</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">AND</span> <span class="n">po</span><span class="p">.</span><span class="n">index_id</span> <span class="o">=</span> <span class="mi">1</span><span class="p">)</span> <span class="n">DataTable</span> <span class="n">PIVOT</span>
    <span class="p">(</span> <span class="k">COUNT</span><span class="p">(</span><span class="n">EventLetter</span><span class="p">)</span> <span class="k">FOR</span> <span class="n">EventLetter</span> <span class="k">IN</span> <span class="p">(</span> <span class="p">[</span><span class="n">Activation</span><span class="p">],</span> <span class="p">[</span><span class="n">Resolve</span><span class="p">],</span> <span class="p">[</span><span class="n">DisabledEmail</span><span class="p">]</span> <span class="p">)</span>
<span class="p">)</span> <span class="k">AS</span> <span class="n">pvt</span>
</code></pre></div></div>

<p>To summarize we get all queues in the current database with their message count from partitions view. Btw this query has very low cpu cost on sql and executes in less than 10ms. We also left join event notifications and queue monitors since those are really important when you have external activation. I also pivot the event notifications and give them all similar name since they all represent same function but with different queue name. The result data looks like this:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;table&gt;</span>
  <span class="nt">&lt;tbody&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;th&gt;</span>Name<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>State<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Enabled<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>MessageCount<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>InternalActivation<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Activation<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Resolve<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>DisabledEmail<span class="nt">&lt;/th&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;td&gt;</span>SampleInitiatorQueue<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>INACTIVE<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;td&gt;</span>SampleTargetQueue<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>INACTIVE<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;td&gt;</span>SecondInitiatorQueue<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>INACTIVE<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;td&gt;</span>SecondTargetQueue<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>INACTIVE<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
  <span class="nt">&lt;/tbody&gt;</span>
<span class="nt">&lt;/table&gt;</span>
</code></pre></div></div>

<p>This gives us some information, but you still need to know if there is something wrong, that’s where we put knockoutjs to work and color code our results.</p>

<h3 id="create-view-model">Create View Model</h3>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">SM</span> <span class="o">=</span> <span class="nx">SM</span> <span class="o">||</span> <span class="p">{};</span>
<span class="nx">SM</span><span class="p">.</span><span class="nx">QueueHealthModel</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
  <span class="kd">var</span> <span class="nb">self</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span>
  <span class="c1">//Data</span>
  <span class="nb">self</span><span class="p">.</span><span class="nx">loadedHealthData</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
  <span class="nb">self</span><span class="p">.</span><span class="nx">ajaxErrors</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
  <span class="c1">//Behaviours</span>
  <span class="nb">self</span><span class="p">.</span><span class="nx">loadHealthData</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="nx">SM</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">getQueueHealthData</span><span class="p">(</span><span class="nb">self</span><span class="p">.</span><span class="nx">loadedHealthData</span><span class="p">);</span>
  <span class="p">};</span>

  <span class="nb">self</span><span class="p">.</span><span class="nx">loadHealthData</span><span class="p">();</span> <span class="c1">//execute on load</span>
<span class="p">};</span>
</code></pre></div></div>

<p>And required data function</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">SM</span><span class="p">.</span><span class="nx">data</span> <span class="o">=</span> <span class="p">{</span>
  <span class="na">getQueueHealthData</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">callback</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">$</span><span class="p">.</span><span class="nx">ajax</span><span class="p">({</span>
      <span class="na">type</span><span class="p">:</span> <span class="dl">"</span><span class="s2">POST</span><span class="dl">"</span><span class="p">,</span>
      <span class="na">url</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Default.aspx/GetAllQueueHealthStatus</span><span class="dl">"</span><span class="p">,</span>
      <span class="na">data</span><span class="p">:</span> <span class="dl">"</span><span class="s2">{}</span><span class="dl">"</span><span class="p">,</span>
      <span class="na">contentType</span><span class="p">:</span> <span class="dl">"</span><span class="s2">application/json; charset=utf-8</span><span class="dl">"</span><span class="p">,</span>
      <span class="na">dataType</span><span class="p">:</span> <span class="dl">"</span><span class="s2">json</span><span class="dl">"</span><span class="p">,</span>
      <span class="na">success</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">msg</span><span class="p">)</span> <span class="p">{</span>
        <span class="kd">var</span> <span class="nx">data</span> <span class="o">=</span> <span class="p">{</span> <span class="na">healthStatus</span><span class="p">:</span> <span class="nx">msg</span><span class="p">.</span><span class="nx">d</span> <span class="p">};</span>
        <span class="nx">callback</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
      <span class="p">},</span>
    <span class="p">});</span>
  <span class="p">},</span>
<span class="p">};</span>
</code></pre></div></div>

<h3 id="webmethod">Webmethod</h3>

<p>Use your favorite data access tool and return an array of data transfer objects</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">WebMethod</span><span class="p">]</span>
<span class="k">public</span> <span class="k">static</span> <span class="n">QueueHealthStatus</span><span class="p">[]</span> <span class="nf">GetAllQueueHealthStatus</span><span class="p">()</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="n">MyRepository</span><span class="p">.</span><span class="nf">GetAllQueueHealthStatus</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="html">Html</h3>

<p>Finally we’ll add our html markup with knockout bindings</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">&lt;!-- Errors --&gt;</span>
<span class="nt">&lt;div</span> <span class="na">data-bind=</span><span class="s">"visible: ajaxErrors"</span><span class="nt">&gt;</span>
  <span class="nt">&lt;h2</span> <span class="na">style=</span><span class="s">"margin: 10px 0;"</span><span class="nt">&gt;</span>
    Ajax communication error please check app layer
  <span class="nt">&lt;/h2&gt;</span>
  <span class="nt">&lt;p</span> <span class="na">style=</span><span class="s">"color: red"</span> <span class="na">data-bind=</span><span class="s">"text: ajaxErrors"</span><span class="nt">&gt;&lt;/p&gt;</span>
<span class="nt">&lt;/div&gt;</span>

<span class="c">&lt;!-- Health Status --&gt;</span>
<span class="nt">&lt;table</span> <span class="na">class=</span><span class="s">"queue-status newspaper-a"</span> <span class="na">data-bind=</span><span class="s">"with: loadedHealthData"</span><span class="nt">&gt;</span>
  <span class="nt">&lt;thead&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;th&gt;</span>Queue<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>State<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Enabled<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Message Count<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Internal Activation<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Activation<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Resolve<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Disabled Email<span class="nt">&lt;/th&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
  <span class="nt">&lt;/thead&gt;</span>
  <span class="nt">&lt;tbody</span> <span class="na">data-bind=</span><span class="s">"foreach: healthStatus"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: QueueName, click: $root.goToImportLog"</span>
        <span class="na">class=</span><span class="s">"pointer"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: State, style: { backgroundColor: SM.format.stateColor(State, QueueName) }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: Enabled, style: { backgroundColor: SM.format.queueEnabledColor(Enabled) }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: MessageCount, style: { backgroundColor: SM.format.messageCountColor(MessageCount), fontWeight: MessageCount &gt; 0 ? 'bold' : 'normal' }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: InternalActivationEnabled, style: { backgroundColor: DOM.format.internalActivationColor(QueueName,InternalActivationEnabled) }, attr: { title: InternalActivationProcedureName }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: ActivationEventEnabled, style: { backgroundColor: SM.format.activationColor(QueueName, ActivationEventEnabled) }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: ResolveEventEnabled, style: { backgroundColor: SM.format.resolveColor(QueueName, ResolveEventEnabled) }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: EmailOnDisabledEventEnabled, style: { backgroundColor: SM.format.disableEmailColor(QueueName, EmailOnDisabledEventEnabled) }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
  <span class="nt">&lt;/tbody&gt;</span>
<span class="nt">&lt;/table&gt;</span>
</code></pre></div></div>

<h3 id="color-utility-functions">Color utility functions</h3>

<p>To break down formatting:</p>

<ul>
  <li>If the queue manager is INACTIVE, it’s a normal state. NOTIFIED is yellow because it could be stuck in the notified state when activation is not working properly.</li>
  <li>If queue is disabled that automatic red.</li>
  <li>If message count is greater than 10, we set color to yellow.</li>
  <li>For each activation we have individual functions that look at queue name and the state of the activation and figure out if the state is correct. For example disabled email activation is valid on all queues, where activation notification is only valid on target queues.</li>
</ul>

<p>Format color functions used in knockoutjs bindings. We use immediate function to return an object with functions so the variables used inside don’t pollute global namespace and accessible to the internal functions.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">SM</span><span class="p">.</span><span class="nx">format</span> <span class="o">=</span> <span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">green</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">#9AFF9A</span><span class="dl">'</span><span class="p">,</span>
    <span class="nx">red</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">#FF6347</span><span class="dl">'</span><span class="p">,</span>
    <span class="nx">yellow</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">yellow</span><span class="dl">'</span><span class="p">;</span>
    <span class="k">return</span> <span class="p">{</span>
        <span class="na">stateColor</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">state</span><span class="p">,</span> <span class="nx">QueueName</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">QueueName</span> <span class="o">===</span> <span class="dl">'</span><span class="s1">ExternalActivationQueue</span><span class="dl">'</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="dl">'</span><span class="s1">white</span><span class="dl">'</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">state</span> <span class="o">===</span> <span class="kc">null</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">red</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">state</span> <span class="o">===</span> <span class="dl">'</span><span class="s1">NOTIFIED</span><span class="dl">'</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">yellow</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">state</span> <span class="o">===</span> <span class="dl">'</span><span class="s1">INACTIVE</span><span class="dl">'</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
            <span class="p">}</span>
        <span class="p">},</span>
        <span class="na">queueEnabledColor</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">value</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">value</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">return</span> <span class="nx">red</span><span class="p">;</span>
        <span class="p">},</span>
        <span class="na">messageCountColor</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">numberOfMessages</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">numberOfMessages</span> <span class="o">&gt;</span> <span class="mi">10</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">yellow</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
        <span class="p">},</span>
        <span class="na">activationColor</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">QueueName</span><span class="p">,</span> <span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">QueueName</span><span class="p">.</span><span class="nx">toLowerCase</span><span class="p">().</span><span class="nx">indexOf</span><span class="p">(</span><span class="dl">"</span><span class="s2">target</span><span class="dl">"</span><span class="p">)</span> <span class="o">!==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">if</span> <span class="p">(</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                    <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
                <span class="p">}</span>
                <span class="k">return</span> <span class="nx">red</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
            <span class="p">}</span>
        <span class="p">},</span>
        <span class="na">internalActivationColor</span> <span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">queueName</span><span class="p">,</span> <span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">queueName</span><span class="p">.</span><span class="nx">toLowerCase</span><span class="p">().</span><span class="nx">indexOf</span><span class="p">(</span><span class="dl">"</span><span class="s2">initiator</span><span class="dl">"</span><span class="p">)</span> <span class="o">!==</span> <span class="o">-</span><span class="mi">1</span> <span class="p">{</span>
                <span class="k">if</span> <span class="p">(</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                    <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
                <span class="p">}</span>
                <span class="k">return</span> <span class="nx">red</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
            <span class="p">}</span>
        <span class="p">},</span>
        <span class="na">resolveColor</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">QueueName</span><span class="p">,</span> <span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">QueueName</span><span class="p">.</span><span class="nx">toLowerCase</span><span class="p">().</span><span class="nx">indexOf</span><span class="p">(</span><span class="dl">"</span><span class="s2">target</span><span class="dl">"</span><span class="p">)</span> <span class="o">!==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">if</span> <span class="p">(</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                    <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
                <span class="p">}</span>
                <span class="k">return</span> <span class="nx">red</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
            <span class="p">}</span>
        <span class="p">},</span>
        <span class="na">disableEmailColor</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">QueueName</span><span class="p">,</span> <span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">return</span> <span class="nx">red</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">};</span>
<span class="p">}</span> <span class="p">());</span>
</code></pre></div></div>

<h3 id="error-handling-and-loading-indicator">Error handling and loading indicator</h3>

<p>There is an awesome jquery ajax global event handler that will catch all ajax exceptions, it’s especially useful when you have many queries running on the page and you don’t want to add error handling logic to each one.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">body</span><span class="dl">"</span><span class="p">).</span><span class="nx">ajaxError</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">event</span><span class="p">,</span> <span class="nx">request</span><span class="p">)</span> <span class="p">{</span>
  <span class="nx">model</span><span class="p">.</span><span class="nx">ajaxErrors</span><span class="p">(</span><span class="nx">request</span><span class="p">.</span><span class="nx">response</span><span class="p">);</span>
<span class="p">});</span>
</code></pre></div></div>

<p>There is also one for loading we can use like this.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">.loadingIndicator</span><span class="dl">"</span><span class="p">)</span>
  <span class="p">.</span><span class="nx">ajaxStart</span><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="nx">$</span><span class="p">(</span><span class="k">this</span><span class="p">).</span><span class="nx">fadeIn</span><span class="p">(</span><span class="dl">"</span><span class="s2">fast</span><span class="dl">"</span><span class="p">);</span>
  <span class="p">})</span>
  <span class="p">.</span><span class="nx">ajaxComplete</span><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="nx">$</span><span class="p">(</span><span class="k">this</span><span class="p">).</span><span class="nx">fadeOut</span><span class="p">(</span><span class="dl">"</span><span class="s2">fast</span><span class="dl">"</span><span class="p">);</span>
  <span class="p">});</span>
</code></pre></div></div>

<p>That’s it. Now when something is wrong with your service broker, it’s very easy to just glance at the screen to understand if something is wrong. You can get more creative and add timeout polling so you can watch how service broker works in real time. And you can also add tool tips on how to resolve issues and maybe even buttons that will fix issues directly from dashboard. Sky is the limit, and this is a good start in the right direction in my opinion.</p>

				<h3 id="what-am-i-trying-to-solve">What am I trying to solve..</h3>

<p><em>If you are not familiar with Service Broker you can still use this as an example for Knockoutjs and ASP.NET Webmethods.</em></p>

<p>The biggest pain point with Service Broker (SB) is how long it takes to understand what exactly is happening when you a have a problem. In order to find a problem sometimes you need to execute good amount of queries, read through the results analyze them and eventually find out what the issue is. It becomes a lot more complicated when you have event notifications and queue monitors on your queues. And if you don’t always work with SB you will eventually forget how things work.</p>

<p>In this post we will have some fun building a color coded status page which will show status of our queues, events, messages and queue monitors. It should be as easy as glancing at the screen and if anything is red that means there is a problem. As a bonus you can also add internal activation on your own.</p>

<h3 id="create-a-health-status-query">Create a health status query</h3>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="o">*</span> <span class="k">FROM</span>
<span class="p">(</span>
<span class="k">SELECT</span> <span class="n">Q</span><span class="p">.</span><span class="n">Name</span>
    <span class="p">,</span><span class="k">CASE</span>
        <span class="k">WHEN</span> <span class="n">EN</span><span class="p">.</span><span class="n">name</span> <span class="k">LIKE</span> <span class="s1">'%QueueActivation'</span>
            <span class="k">THEN</span> <span class="s1">'Activation'</span>
        <span class="k">WHEN</span> <span class="n">EN</span><span class="p">.</span><span class="n">name</span> <span class="k">LIKE</span> <span class="s1">'%QueueDisabledEmail'</span>
            <span class="k">THEN</span> <span class="s1">'DisabledEmail'</span>
        <span class="k">WHEN</span> <span class="n">EN</span><span class="p">.</span><span class="n">name</span> <span class="k">LIKE</span> <span class="s1">'%QueueDisabled'</span>
            <span class="k">THEN</span> <span class="s1">'Resolve'</span>
    <span class="k">END</span> <span class="k">AS</span> <span class="n">EventLetter</span>
    <span class="p">,</span><span class="n">QM</span><span class="p">.</span><span class="k">state</span>
    <span class="p">,</span><span class="n">Q</span><span class="p">.</span><span class="n">is_enqueue_enabled</span> <span class="k">AS</span> <span class="p">[</span><span class="n">Enabled</span><span class="p">]</span>
    <span class="p">,</span><span class="n">po</span><span class="p">.</span><span class="k">rows</span> <span class="k">AS</span> <span class="n">MessageCount</span>
    <span class="p">,</span><span class="n">Q</span><span class="p">.</span><span class="n">is_activation_enabled</span> <span class="k">as</span> <span class="n">InternalActivationEnabled</span>
    <span class="p">,</span><span class="n">Q</span><span class="p">.</span><span class="n">activation_procedure</span>	<span class="k">as</span> <span class="n">InternalActivationProcedureName</span>
<span class="k">FROM</span> <span class="n">sys</span><span class="p">.</span><span class="n">service_queues</span> <span class="k">AS</span> <span class="n">Q</span>
    <span class="k">JOIN</span> <span class="n">sys</span><span class="p">.</span><span class="n">objects</span> <span class="k">AS</span> <span class="n">o</span> <span class="k">ON</span> <span class="n">o</span><span class="p">.</span><span class="n">parent_object_id</span> <span class="o">=</span> <span class="n">Q</span><span class="p">.</span><span class="n">object_id</span>
    <span class="k">JOIN</span> <span class="n">sys</span><span class="p">.</span><span class="n">partitions</span> <span class="k">AS</span> <span class="n">po</span> <span class="k">ON</span> <span class="n">po</span><span class="p">.</span><span class="n">object_id</span> <span class="o">=</span> <span class="n">o</span><span class="p">.</span><span class="n">object_id</span>
    <span class="k">JOIN</span> <span class="n">sys</span><span class="p">.</span><span class="n">objects</span> <span class="k">AS</span> <span class="n">qo</span> <span class="k">ON</span> <span class="n">o</span><span class="p">.</span><span class="n">parent_object_id</span> <span class="o">=</span> <span class="n">qo</span><span class="p">.</span><span class="n">object_id</span>
    <span class="k">LEFT</span> <span class="k">JOIN</span> <span class="n">sys</span><span class="p">.</span><span class="n">event_notifications</span> <span class="k">AS</span> <span class="n">EN</span> <span class="k">ON</span> <span class="n">Q</span><span class="p">.</span><span class="n">object_id</span> <span class="o">=</span> <span class="n">EN</span><span class="p">.</span><span class="n">parent_id</span>
    <span class="k">LEFT</span> <span class="k">JOIN</span> <span class="n">sys</span><span class="p">.</span><span class="n">dm_broker_queue_monitors</span> <span class="k">AS</span> <span class="n">QM</span> <span class="k">ON</span> <span class="n">Q</span><span class="p">.</span><span class="n">object_id</span> <span class="o">=</span> <span class="n">QM</span><span class="p">.</span><span class="n">queue_id</span>
<span class="k">WHERE</span> <span class="n">Q</span><span class="p">.</span><span class="n">is_ms_shipped</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">AND</span> <span class="n">po</span><span class="p">.</span><span class="n">index_id</span> <span class="o">=</span> <span class="mi">1</span><span class="p">)</span> <span class="n">DataTable</span> <span class="n">PIVOT</span>
    <span class="p">(</span> <span class="k">COUNT</span><span class="p">(</span><span class="n">EventLetter</span><span class="p">)</span> <span class="k">FOR</span> <span class="n">EventLetter</span> <span class="k">IN</span> <span class="p">(</span> <span class="p">[</span><span class="n">Activation</span><span class="p">],</span> <span class="p">[</span><span class="n">Resolve</span><span class="p">],</span> <span class="p">[</span><span class="n">DisabledEmail</span><span class="p">]</span> <span class="p">)</span>
<span class="p">)</span> <span class="k">AS</span> <span class="n">pvt</span>
</code></pre></div></div>

<p>To summarize we get all queues in the current database with their message count from partitions view. Btw this query has very low cpu cost on sql and executes in less than 10ms. We also left join event notifications and queue monitors since those are really important when you have external activation. I also pivot the event notifications and give them all similar name since they all represent same function but with different queue name. The result data looks like this:</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;table&gt;</span>
  <span class="nt">&lt;tbody&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;th&gt;</span>Name<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>State<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Enabled<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>MessageCount<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>InternalActivation<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Activation<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Resolve<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>DisabledEmail<span class="nt">&lt;/th&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;td&gt;</span>SampleInitiatorQueue<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>INACTIVE<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;td&gt;</span>SampleTargetQueue<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>INACTIVE<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;td&gt;</span>SecondInitiatorQueue<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>INACTIVE<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;td&gt;</span>SecondTargetQueue<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>INACTIVE<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>0<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
      <span class="nt">&lt;td&gt;</span>1<span class="nt">&lt;/td&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
  <span class="nt">&lt;/tbody&gt;</span>
<span class="nt">&lt;/table&gt;</span>
</code></pre></div></div>

<p>This gives us some information, but you still need to know if there is something wrong, that’s where we put knockoutjs to work and color code our results.</p>

<h3 id="create-view-model">Create View Model</h3>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">SM</span> <span class="o">=</span> <span class="nx">SM</span> <span class="o">||</span> <span class="p">{};</span>
<span class="nx">SM</span><span class="p">.</span><span class="nx">QueueHealthModel</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
  <span class="kd">var</span> <span class="nb">self</span> <span class="o">=</span> <span class="k">this</span><span class="p">;</span>
  <span class="c1">//Data</span>
  <span class="nb">self</span><span class="p">.</span><span class="nx">loadedHealthData</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
  <span class="nb">self</span><span class="p">.</span><span class="nx">ajaxErrors</span> <span class="o">=</span> <span class="nx">ko</span><span class="p">.</span><span class="nx">observable</span><span class="p">();</span>
  <span class="c1">//Behaviours</span>
  <span class="nb">self</span><span class="p">.</span><span class="nx">loadHealthData</span> <span class="o">=</span> <span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="nx">SM</span><span class="p">.</span><span class="nx">data</span><span class="p">.</span><span class="nx">getQueueHealthData</span><span class="p">(</span><span class="nb">self</span><span class="p">.</span><span class="nx">loadedHealthData</span><span class="p">);</span>
  <span class="p">};</span>

  <span class="nb">self</span><span class="p">.</span><span class="nx">loadHealthData</span><span class="p">();</span> <span class="c1">//execute on load</span>
<span class="p">};</span>
</code></pre></div></div>

<p>And required data function</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">SM</span><span class="p">.</span><span class="nx">data</span> <span class="o">=</span> <span class="p">{</span>
  <span class="na">getQueueHealthData</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">callback</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">$</span><span class="p">.</span><span class="nx">ajax</span><span class="p">({</span>
      <span class="na">type</span><span class="p">:</span> <span class="dl">"</span><span class="s2">POST</span><span class="dl">"</span><span class="p">,</span>
      <span class="na">url</span><span class="p">:</span> <span class="dl">"</span><span class="s2">Default.aspx/GetAllQueueHealthStatus</span><span class="dl">"</span><span class="p">,</span>
      <span class="na">data</span><span class="p">:</span> <span class="dl">"</span><span class="s2">{}</span><span class="dl">"</span><span class="p">,</span>
      <span class="na">contentType</span><span class="p">:</span> <span class="dl">"</span><span class="s2">application/json; charset=utf-8</span><span class="dl">"</span><span class="p">,</span>
      <span class="na">dataType</span><span class="p">:</span> <span class="dl">"</span><span class="s2">json</span><span class="dl">"</span><span class="p">,</span>
      <span class="na">success</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">msg</span><span class="p">)</span> <span class="p">{</span>
        <span class="kd">var</span> <span class="nx">data</span> <span class="o">=</span> <span class="p">{</span> <span class="na">healthStatus</span><span class="p">:</span> <span class="nx">msg</span><span class="p">.</span><span class="nx">d</span> <span class="p">};</span>
        <span class="nx">callback</span><span class="p">(</span><span class="nx">data</span><span class="p">);</span>
      <span class="p">},</span>
    <span class="p">});</span>
  <span class="p">},</span>
<span class="p">};</span>
</code></pre></div></div>

<h3 id="webmethod">Webmethod</h3>

<p>Use your favorite data access tool and return an array of data transfer objects</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="n">WebMethod</span><span class="p">]</span>
<span class="k">public</span> <span class="k">static</span> <span class="n">QueueHealthStatus</span><span class="p">[]</span> <span class="nf">GetAllQueueHealthStatus</span><span class="p">()</span>
<span class="p">{</span>
    <span class="k">return</span> <span class="n">MyRepository</span><span class="p">.</span><span class="nf">GetAllQueueHealthStatus</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="html">Html</h3>

<p>Finally we’ll add our html markup with knockout bindings</p>

<div class="language-html highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c">&lt;!-- Errors --&gt;</span>
<span class="nt">&lt;div</span> <span class="na">data-bind=</span><span class="s">"visible: ajaxErrors"</span><span class="nt">&gt;</span>
  <span class="nt">&lt;h2</span> <span class="na">style=</span><span class="s">"margin: 10px 0;"</span><span class="nt">&gt;</span>
    Ajax communication error please check app layer
  <span class="nt">&lt;/h2&gt;</span>
  <span class="nt">&lt;p</span> <span class="na">style=</span><span class="s">"color: red"</span> <span class="na">data-bind=</span><span class="s">"text: ajaxErrors"</span><span class="nt">&gt;&lt;/p&gt;</span>
<span class="nt">&lt;/div&gt;</span>

<span class="c">&lt;!-- Health Status --&gt;</span>
<span class="nt">&lt;table</span> <span class="na">class=</span><span class="s">"queue-status newspaper-a"</span> <span class="na">data-bind=</span><span class="s">"with: loadedHealthData"</span><span class="nt">&gt;</span>
  <span class="nt">&lt;thead&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;th&gt;</span>Queue<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>State<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Enabled<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Message Count<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Internal Activation<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Activation<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Resolve<span class="nt">&lt;/th&gt;</span>
      <span class="nt">&lt;th&gt;</span>Disabled Email<span class="nt">&lt;/th&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
  <span class="nt">&lt;/thead&gt;</span>
  <span class="nt">&lt;tbody</span> <span class="na">data-bind=</span><span class="s">"foreach: healthStatus"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;tr&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: QueueName, click: $root.goToImportLog"</span>
        <span class="na">class=</span><span class="s">"pointer"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: State, style: { backgroundColor: SM.format.stateColor(State, QueueName) }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: Enabled, style: { backgroundColor: SM.format.queueEnabledColor(Enabled) }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: MessageCount, style: { backgroundColor: SM.format.messageCountColor(MessageCount), fontWeight: MessageCount &gt; 0 ? 'bold' : 'normal' }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: InternalActivationEnabled, style: { backgroundColor: DOM.format.internalActivationColor(QueueName,InternalActivationEnabled) }, attr: { title: InternalActivationProcedureName }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: ActivationEventEnabled, style: { backgroundColor: SM.format.activationColor(QueueName, ActivationEventEnabled) }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: ResolveEventEnabled, style: { backgroundColor: SM.format.resolveColor(QueueName, ResolveEventEnabled) }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
      <span class="nt">&lt;td</span>
        <span class="na">data-bind=</span><span class="s">"text: EmailOnDisabledEventEnabled, style: { backgroundColor: SM.format.disableEmailColor(QueueName, EmailOnDisabledEventEnabled) }"</span>
      <span class="nt">&gt;&lt;/td&gt;</span>
    <span class="nt">&lt;/tr&gt;</span>
  <span class="nt">&lt;/tbody&gt;</span>
<span class="nt">&lt;/table&gt;</span>
</code></pre></div></div>

<h3 id="color-utility-functions">Color utility functions</h3>

<p>To break down formatting:</p>

<ul>
  <li>If the queue manager is INACTIVE, it’s a normal state. NOTIFIED is yellow because it could be stuck in the notified state when activation is not working properly.</li>
  <li>If queue is disabled that automatic red.</li>
  <li>If message count is greater than 10, we set color to yellow.</li>
  <li>For each activation we have individual functions that look at queue name and the state of the activation and figure out if the state is correct. For example disabled email activation is valid on all queues, where activation notification is only valid on target queues.</li>
</ul>

<p>Format color functions used in knockoutjs bindings. We use immediate function to return an object with functions so the variables used inside don’t pollute global namespace and accessible to the internal functions.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">SM</span><span class="p">.</span><span class="nx">format</span> <span class="o">=</span> <span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">green</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">#9AFF9A</span><span class="dl">'</span><span class="p">,</span>
    <span class="nx">red</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">#FF6347</span><span class="dl">'</span><span class="p">,</span>
    <span class="nx">yellow</span> <span class="o">=</span> <span class="dl">'</span><span class="s1">yellow</span><span class="dl">'</span><span class="p">;</span>
    <span class="k">return</span> <span class="p">{</span>
        <span class="na">stateColor</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">state</span><span class="p">,</span> <span class="nx">QueueName</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">QueueName</span> <span class="o">===</span> <span class="dl">'</span><span class="s1">ExternalActivationQueue</span><span class="dl">'</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="dl">'</span><span class="s1">white</span><span class="dl">'</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">state</span> <span class="o">===</span> <span class="kc">null</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">red</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">state</span> <span class="o">===</span> <span class="dl">'</span><span class="s1">NOTIFIED</span><span class="dl">'</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">yellow</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">state</span> <span class="o">===</span> <span class="dl">'</span><span class="s1">INACTIVE</span><span class="dl">'</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
            <span class="p">}</span>
        <span class="p">},</span>
        <span class="na">queueEnabledColor</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">value</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">value</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">return</span> <span class="nx">red</span><span class="p">;</span>
        <span class="p">},</span>
        <span class="na">messageCountColor</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">numberOfMessages</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">numberOfMessages</span> <span class="o">&gt;</span> <span class="mi">10</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">yellow</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
        <span class="p">},</span>
        <span class="na">activationColor</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">QueueName</span><span class="p">,</span> <span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">QueueName</span><span class="p">.</span><span class="nx">toLowerCase</span><span class="p">().</span><span class="nx">indexOf</span><span class="p">(</span><span class="dl">"</span><span class="s2">target</span><span class="dl">"</span><span class="p">)</span> <span class="o">!==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">if</span> <span class="p">(</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                    <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
                <span class="p">}</span>
                <span class="k">return</span> <span class="nx">red</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
            <span class="p">}</span>
        <span class="p">},</span>
        <span class="na">internalActivationColor</span> <span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">queueName</span><span class="p">,</span> <span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">queueName</span><span class="p">.</span><span class="nx">toLowerCase</span><span class="p">().</span><span class="nx">indexOf</span><span class="p">(</span><span class="dl">"</span><span class="s2">initiator</span><span class="dl">"</span><span class="p">)</span> <span class="o">!==</span> <span class="o">-</span><span class="mi">1</span> <span class="p">{</span>
                <span class="k">if</span> <span class="p">(</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                    <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
                <span class="p">}</span>
                <span class="k">return</span> <span class="nx">red</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
            <span class="p">}</span>
        <span class="p">},</span>
        <span class="na">resolveColor</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">QueueName</span><span class="p">,</span> <span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">QueueName</span><span class="p">.</span><span class="nx">toLowerCase</span><span class="p">().</span><span class="nx">indexOf</span><span class="p">(</span><span class="dl">"</span><span class="s2">target</span><span class="dl">"</span><span class="p">)</span> <span class="o">!==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">if</span> <span class="p">(</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                    <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
                <span class="p">}</span>
                <span class="k">return</span> <span class="nx">red</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">if</span> <span class="p">(</span><span class="o">!</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
            <span class="p">}</span>
        <span class="p">},</span>
        <span class="na">disableEmailColor</span><span class="p">:</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">QueueName</span><span class="p">,</span> <span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">exists</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="nx">green</span><span class="p">;</span>
            <span class="p">}</span>
            <span class="k">return</span> <span class="nx">red</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">};</span>
<span class="p">}</span> <span class="p">());</span>
</code></pre></div></div>

<h3 id="error-handling-and-loading-indicator">Error handling and loading indicator</h3>

<p>There is an awesome jquery ajax global event handler that will catch all ajax exceptions, it’s especially useful when you have many queries running on the page and you don’t want to add error handling logic to each one.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">body</span><span class="dl">"</span><span class="p">).</span><span class="nx">ajaxError</span><span class="p">(</span><span class="kd">function</span> <span class="p">(</span><span class="nx">event</span><span class="p">,</span> <span class="nx">request</span><span class="p">)</span> <span class="p">{</span>
  <span class="nx">model</span><span class="p">.</span><span class="nx">ajaxErrors</span><span class="p">(</span><span class="nx">request</span><span class="p">.</span><span class="nx">response</span><span class="p">);</span>
<span class="p">});</span>
</code></pre></div></div>

<p>There is also one for loading we can use like this.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">.loadingIndicator</span><span class="dl">"</span><span class="p">)</span>
  <span class="p">.</span><span class="nx">ajaxStart</span><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="nx">$</span><span class="p">(</span><span class="k">this</span><span class="p">).</span><span class="nx">fadeIn</span><span class="p">(</span><span class="dl">"</span><span class="s2">fast</span><span class="dl">"</span><span class="p">);</span>
  <span class="p">})</span>
  <span class="p">.</span><span class="nx">ajaxComplete</span><span class="p">(</span><span class="kd">function</span> <span class="p">()</span> <span class="p">{</span>
    <span class="nx">$</span><span class="p">(</span><span class="k">this</span><span class="p">).</span><span class="nx">fadeOut</span><span class="p">(</span><span class="dl">"</span><span class="s2">fast</span><span class="dl">"</span><span class="p">);</span>
  <span class="p">});</span>
</code></pre></div></div>

<p>That’s it. Now when something is wrong with your service broker, it’s very easy to just glance at the screen to understand if something is wrong. You can get more creative and add timeout polling so you can watch how service broker works in real time. And you can also add tool tips on how to resolve issues and maybe even buttons that will fix issues directly from dashboard. Sky is the limit, and this is a good start in the right direction in my opinion.</p>

										
					<p>Posted in: sql-server-service-broker</p>
						
				
					<p>Tagged with: service-broker and knockoutjs</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/sql-server-service-broker/queue-health-status-dashboard/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/sql-server-service-broker/queue-health-status-dashboard/]]></guid>
		<pubDate>2012-08-07T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Service Broker: Setup Email Notifications On Disabled Queues]]></title>
		<description>
			<![CDATA[
				<p>It took me some time to figure our this part even though it should be trivial. So hopefully this guide will help someone in the future. I think the hardest part was to understand the security context under which internal stored procedures run when activated by service broker.</p>

<p>First thing you need to do is to create a DisabledQueueNotificationQueue. I know I know, it’s a little redundant name but what it means is that you have a queue that receives notifications when other queues get disabled, therefore redundant name.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">QUEUE</span> <span class="n">dbo</span><span class="p">.</span><span class="n">DisabledQueueNotificationQueue</span>
</code></pre></div></div>

<p>Create service endpoint with PostEventNotification message type</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">SERVICE</span> <span class="n">DisabledQueueNotificationService</span>
<span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">DisabledQueueNotificationQueue</span>
<span class="p">(</span>
	<span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">schemas</span><span class="p">.</span><span class="n">microsoft</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="k">SQL</span><span class="o">/</span><span class="n">Notifications</span><span class="o">/</span><span class="n">PostEventNotification</span><span class="p">]</span>
<span class="p">)</span>
<span class="k">GO</span>
</code></pre></div></div>

<p>Next is we need to setup a notification procedure which will execute msdb.dbo.sp_send_mail</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="k">PROCEDURE</span> <span class="p">[</span><span class="n">dbo</span><span class="p">].[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotification</span><span class="p">]</span>
<span class="k">WITH</span> <span class="k">EXECUTE</span> <span class="k">AS</span> <span class="k">OWNER</span>
<span class="k">AS</span>
	<span class="k">DECLARE</span> <span class="o">@</span><span class="n">ch</span> <span class="n">UNIQUEIDENTIFIER</span>
	<span class="k">DECLARE</span> <span class="o">@</span><span class="n">messagetypename</span> <span class="n">NVARCHAR</span><span class="p">(</span><span class="mi">256</span><span class="p">)</span>
	<span class="k">DECLARE</span>	<span class="o">@</span><span class="n">messagebody</span> <span class="n">XML</span>
	<span class="k">DECLARE</span> <span class="o">@</span><span class="n">queueName</span> <span class="nb">varchar</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
	<span class="k">DECLARE</span> <span class="o">@</span><span class="n">emailTo</span> <span class="nb">VARCHAR</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>


	<span class="k">SET</span> <span class="o">@</span><span class="n">emailTo</span> <span class="o">=</span> <span class="s1">'someaddress@yahoo.com'</span>

	<span class="n">WHILE</span> <span class="p">(</span><span class="mi">1</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
	<span class="k">BEGIN</span>
		<span class="k">BEGIN</span> <span class="n">TRY</span>
			<span class="k">BEGIN</span> <span class="n">TRANSACTION</span>

			<span class="n">WAITFOR</span> <span class="p">(</span>
				<span class="n">RECEIVE</span> <span class="n">TOP</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
					<span class="o">@</span><span class="n">ch</span> <span class="o">=</span> <span class="n">conversation_handle</span><span class="p">,</span>
					<span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="n">message_type_name</span><span class="p">,</span>
					<span class="o">@</span><span class="n">messagebody</span> <span class="o">=</span> <span class="k">CAST</span><span class="p">(</span><span class="n">message_body</span> <span class="k">AS</span> <span class="n">XML</span><span class="p">)</span>
				<span class="k">FROM</span> <span class="n">DisabledQueueNotificationQueue</span>
			<span class="p">),</span> <span class="n">TIMEOUT</span> <span class="mi">60000</span>

			<span class="n">IF</span> <span class="p">(</span><span class="o">@@</span><span class="n">ROWCOUNT</span> <span class="o">=</span> <span class="mi">0</span><span class="p">)</span>
			<span class="k">BEGIN</span>
				<span class="k">ROLLBACK</span> <span class="n">TRANSACTION</span>
				<span class="n">BREAK</span>
			<span class="k">END</span>

			<span class="n">IF</span> <span class="p">(</span><span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="s1">'http://schemas.microsoft.com/SQL/Notifications/EventNotification'</span><span class="p">)</span>
			<span class="k">BEGIN</span>
				<span class="k">SET</span> <span class="o">@</span><span class="n">queueName</span> <span class="o">=</span> <span class="s1">'Disabled queue: '</span> <span class="o">+</span> <span class="o">@</span><span class="n">messagebody</span><span class="p">.</span><span class="n">value</span><span class="p">(</span><span class="s1">'/EVENT_INSTANCE[1]/ObjectName[1]'</span><span class="p">,</span> <span class="s1">'VARCHAR(100)'</span><span class="p">);</span>

				<span class="k">EXEC</span> <span class="n">msdb</span><span class="p">.</span><span class="n">dbo</span><span class="p">.</span><span class="n">sp_send_dbmail</span>
					<span class="o">@</span><span class="n">profile_name</span> <span class="o">=</span> <span class="s1">'DBA_Notifications'</span><span class="p">,</span>
					<span class="o">@</span><span class="n">recipients</span> <span class="o">=</span> <span class="o">@</span><span class="n">emailTo</span><span class="p">,</span>
					<span class="o">@</span><span class="n">body</span> <span class="o">=</span> <span class="o">@</span><span class="n">queueName</span><span class="p">,</span>
					<span class="o">@</span><span class="n">subject</span> <span class="o">=</span> <span class="o">@</span><span class="n">queueName</span><span class="p">;</span>

			<span class="k">END</span>

			<span class="n">IF</span> <span class="p">(</span><span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="s1">'http://schemas.microsoft.com/SQL/ServiceBroker/Error'</span><span class="p">)</span>
			<span class="k">BEGIN</span>
					<span class="k">DECLARE</span> <span class="o">@</span><span class="n">errorcode</span> <span class="nb">INT</span>
					<span class="k">DECLARE</span> <span class="o">@</span><span class="n">errormessage</span> <span class="n">NVARCHAR</span><span class="p">(</span><span class="mi">3000</span><span class="p">)</span>
					<span class="c1">-- Extract the error information from the sent message</span>
					<span class="k">SET</span> <span class="o">@</span><span class="n">errorcode</span> <span class="o">=</span> <span class="p">(</span><span class="k">SELECT</span> <span class="o">@</span><span class="n">messagebody</span><span class="p">.</span><span class="n">value</span><span class="p">(</span>
						<span class="n">N</span><span class="s1">'declare namespace brokerns="http://schemas.microsoft.com/SQL/ServiceBroker/Error";
						(/brokerns:Error/brokerns:Code)[1]'</span><span class="p">,</span> <span class="s1">'int'</span><span class="p">));</span>
					<span class="k">SET</span> <span class="o">@</span><span class="n">errormessage</span> <span class="o">=</span> <span class="p">(</span><span class="k">SELECT</span> <span class="o">@</span><span class="n">messagebody</span><span class="p">.</span><span class="n">value</span><span class="p">(</span>
						<span class="s1">'declare namespace brokerns="http://schemas.microsoft.com/SQL/ServiceBroker/Error";
						(/brokerns:Error/brokerns:Description)[1]'</span><span class="p">,</span> <span class="s1">'nvarchar(3000)'</span><span class="p">));</span>

					<span class="c1">-- Log the error</span>

					<span class="c1">-- End the conversation on the initiator's side</span>
					<span class="k">END</span> <span class="n">CONVERSATION</span> <span class="o">@</span><span class="n">ch</span><span class="p">;</span>
			<span class="k">END</span>


			<span class="n">IF</span> <span class="p">(</span><span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="s1">'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog'</span><span class="p">)</span>
			<span class="k">BEGIN</span>
				<span class="c1">-- End the conversation</span>
				<span class="k">END</span> <span class="n">CONVERSATION</span> <span class="o">@</span><span class="n">ch</span><span class="p">;</span>
			<span class="k">END</span>

			<span class="k">COMMIT</span> <span class="n">TRANSACTION</span>
		<span class="k">END</span> <span class="n">TRY</span>
		<span class="k">BEGIN</span> <span class="n">CATCH</span>
			<span class="k">ROLLBACK</span> <span class="n">TRANSACTION</span>
			<span class="k">DECLARE</span> <span class="o">@</span><span class="n">ErrorNum</span> <span class="nb">INT</span>
			<span class="k">DECLARE</span> <span class="o">@</span><span class="n">ErrorMsg</span> <span class="n">NVARCHAR</span><span class="p">(</span><span class="mi">3000</span><span class="p">)</span>
			<span class="k">SELECT</span> <span class="o">@</span><span class="n">ErrorNum</span> <span class="o">=</span> <span class="n">ERROR_NUMBER</span><span class="p">(),</span> <span class="o">@</span><span class="n">ErrorMsg</span> <span class="o">=</span> <span class="n">ERROR_MESSAGE</span><span class="p">()</span>
			<span class="c1">-- log the error</span>
			<span class="n">BREAK</span>
		<span class="k">END</span> <span class="n">CATCH</span>
	<span class="k">END</span>
</code></pre></div></div>

<p>The important piece is that this procedure will execute as owner which will be a dbo schema when service broker activates the internal procedure.</p>

<p>Next we add the queue internal activation</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">ALTER</span> <span class="n">QUEUE</span> <span class="n">DisabledQueueNotificationQueue</span>
<span class="k">WITH</span> <span class="n">ACTIVATION</span>
<span class="p">(</span>
	<span class="n">PROCEDURE_NAME</span> <span class="o">=</span> <span class="n">dbo</span><span class="p">.</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotification</span><span class="p">,</span>
	<span class="n">STATUS</span> <span class="o">=</span> <span class="k">ON</span><span class="p">,</span>
	<span class="n">MAX_QUEUE_READERS</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span>
	<span class="k">EXECUTE</span> <span class="k">AS</span> <span class="k">OWNER</span>
<span class="p">)</span>
</code></pre></div></div>

<p>Finally we create an event notification to send messages when queue gets disabled into the DisabledQueueNotifiactionQueue</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">EVENT</span> <span class="n">NOTIFICATION</span> <span class="n">DisabledTargetQueueNotification</span>
	<span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">dbo</span><span class="p">.</span><span class="n">TargetQueue</span>
	<span class="k">FOR</span> <span class="n">BROKER_QUEUE_DISABLED</span>
	<span class="k">TO</span> <span class="n">SERVICE</span> <span class="s1">'DisabledQueueNotificationService'</span><span class="p">,</span> <span class="s1">'current database'</span><span class="p">;</span>
</code></pre></div></div>

<p>If we try to simulate a poison message and rollback receive 5 times the procedure won’t execute and will log an error:</p>

<blockquote>
  <p>The EXECUTE permission was denied on
the object ‘sp_send_dbmail’, database
‘msdb’, schema ‘dbo’.</p>
</blockquote>

<p>This is expected since the activated stored procedure is calling an msdb database and has no permissions since it is in the public context. Since I trust other database on my sql server I thought that enabling trustworthy would fix this problem: <code class="language-plaintext highlighter-rouge">ALTER DATABASE [msdb] SET TRUSTWORTHY ON</code>. But apparently the setup of my sql server would still not allow a public process to access system database. So the only one thing that was left to do is to create a certificate and sign the procedure so it would be trusted.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">CREATE</span> <span class="n">CERTIFICATE</span> <span class="n">spServiceBroker_SendDisabledQueueEmailNotificationCertificate</span>
    	<span class="n">ENCRYPTION</span> <span class="k">BY</span> <span class="n">PASSWORD</span> <span class="o">=</span> <span class="s1">'SommePass91'</span>
    	<span class="k">WITH</span> <span class="n">SUBJECT</span> <span class="o">=</span> <span class="s1">'spServiceBroker_SendDisabledQueueEmailNotification signing certificate'</span>
    <span class="k">GO</span>

    <span class="k">ADD</span> <span class="n">SIGNATURE</span> <span class="k">TO</span> <span class="k">OBJECT</span><span class="p">::[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotification</span><span class="p">]</span>
    	<span class="k">BY</span> <span class="n">CERTIFICATE</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationCertificate</span><span class="p">]</span>
    	<span class="k">WITH</span> <span class="n">PASSWORD</span> <span class="o">=</span> <span class="s1">'SommePass91'</span>
    <span class="k">GO</span>


    <span class="c1">--------------------------------------------------------------------------------</span>
    <span class="c1">-- We leave the private key so we can resign the procedure later if it changes.</span>
    <span class="c1">-- If we remove the certificate the whole thing will need to be recreated</span>
    <span class="c1">--------------------------------------------------------------------------------</span>
    <span class="c1">--ALTER CERTIFICATE spServiceBroker_SendDisabledQueueEmailNotificationCertificate</span>
    <span class="c1">--	REMOVE PRIVATE KEY</span>
    <span class="c1">--GO</span>

    <span class="n">BACKUP</span> <span class="n">CERTIFICATE</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationCertificate</span><span class="p">]</span>
    	<span class="k">TO</span> <span class="n">FILE</span> <span class="o">=</span> <span class="s1">'c:</span><span class="se">\s</span><span class="s1">pServiceBroker_SendDisabledQueueEmailNotificationCertificate.cert'</span>
    <span class="k">GO</span>

    <span class="n">USE</span> <span class="n">msdb</span>
    <span class="k">GO</span>

    <span class="k">CREATE</span> <span class="n">CERTIFICATE</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationCertificate</span><span class="p">]</span>
    	<span class="k">FROM</span> <span class="n">FILE</span> <span class="o">=</span> <span class="s1">'c:</span><span class="se">\s</span><span class="s1">pServiceBroker_SendDisabledQueueEmailNotificationCertificate.cert'</span>
    <span class="k">GO</span>


    <span class="k">CREATE</span> <span class="k">USER</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationUser</span><span class="p">]</span>
      <span class="k">FROM</span> <span class="n">CERTIFICATE</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationCertificate</span><span class="p">]</span>
    <span class="k">GO</span>

    <span class="k">GRANT</span> <span class="n">AUTHENTICATE</span> <span class="k">TO</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationUser</span><span class="p">]</span>

    <span class="k">GRANT</span> <span class="k">EXECUTE</span> <span class="k">ON</span> <span class="p">[</span><span class="n">sp_send_dbmail</span><span class="p">]</span> <span class="k">TO</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationUser</span><span class="p">];</span>
</code></pre></div></div>

<p>Now that the procedure has access to the <code class="language-plaintext highlighter-rouge">sp_send_dbmail</code> we have no issues and if you simulate poison message, you should receive an email notification with the name of the queue.</p>

				<p>It took me some time to figure our this part even though it should be trivial. So hopefully this guide will help someone in the future. I think the hardest part was to understand the security context under which internal stored procedures run when activated by service broker.</p>

<p>First thing you need to do is to create a DisabledQueueNotificationQueue. I know I know, it’s a little redundant name but what it means is that you have a queue that receives notifications when other queues get disabled, therefore redundant name.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">QUEUE</span> <span class="n">dbo</span><span class="p">.</span><span class="n">DisabledQueueNotificationQueue</span>
</code></pre></div></div>

<p>Create service endpoint with PostEventNotification message type</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">SERVICE</span> <span class="n">DisabledQueueNotificationService</span>
<span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">DisabledQueueNotificationQueue</span>
<span class="p">(</span>
	<span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">schemas</span><span class="p">.</span><span class="n">microsoft</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="k">SQL</span><span class="o">/</span><span class="n">Notifications</span><span class="o">/</span><span class="n">PostEventNotification</span><span class="p">]</span>
<span class="p">)</span>
<span class="k">GO</span>
</code></pre></div></div>

<p>Next is we need to setup a notification procedure which will execute msdb.dbo.sp_send_mail</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="k">PROCEDURE</span> <span class="p">[</span><span class="n">dbo</span><span class="p">].[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotification</span><span class="p">]</span>
<span class="k">WITH</span> <span class="k">EXECUTE</span> <span class="k">AS</span> <span class="k">OWNER</span>
<span class="k">AS</span>
	<span class="k">DECLARE</span> <span class="o">@</span><span class="n">ch</span> <span class="n">UNIQUEIDENTIFIER</span>
	<span class="k">DECLARE</span> <span class="o">@</span><span class="n">messagetypename</span> <span class="n">NVARCHAR</span><span class="p">(</span><span class="mi">256</span><span class="p">)</span>
	<span class="k">DECLARE</span>	<span class="o">@</span><span class="n">messagebody</span> <span class="n">XML</span>
	<span class="k">DECLARE</span> <span class="o">@</span><span class="n">queueName</span> <span class="nb">varchar</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
	<span class="k">DECLARE</span> <span class="o">@</span><span class="n">emailTo</span> <span class="nb">VARCHAR</span><span class="p">(</span><span class="mi">500</span><span class="p">)</span>


	<span class="k">SET</span> <span class="o">@</span><span class="n">emailTo</span> <span class="o">=</span> <span class="s1">'someaddress@yahoo.com'</span>

	<span class="n">WHILE</span> <span class="p">(</span><span class="mi">1</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
	<span class="k">BEGIN</span>
		<span class="k">BEGIN</span> <span class="n">TRY</span>
			<span class="k">BEGIN</span> <span class="n">TRANSACTION</span>

			<span class="n">WAITFOR</span> <span class="p">(</span>
				<span class="n">RECEIVE</span> <span class="n">TOP</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
					<span class="o">@</span><span class="n">ch</span> <span class="o">=</span> <span class="n">conversation_handle</span><span class="p">,</span>
					<span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="n">message_type_name</span><span class="p">,</span>
					<span class="o">@</span><span class="n">messagebody</span> <span class="o">=</span> <span class="k">CAST</span><span class="p">(</span><span class="n">message_body</span> <span class="k">AS</span> <span class="n">XML</span><span class="p">)</span>
				<span class="k">FROM</span> <span class="n">DisabledQueueNotificationQueue</span>
			<span class="p">),</span> <span class="n">TIMEOUT</span> <span class="mi">60000</span>

			<span class="n">IF</span> <span class="p">(</span><span class="o">@@</span><span class="n">ROWCOUNT</span> <span class="o">=</span> <span class="mi">0</span><span class="p">)</span>
			<span class="k">BEGIN</span>
				<span class="k">ROLLBACK</span> <span class="n">TRANSACTION</span>
				<span class="n">BREAK</span>
			<span class="k">END</span>

			<span class="n">IF</span> <span class="p">(</span><span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="s1">'http://schemas.microsoft.com/SQL/Notifications/EventNotification'</span><span class="p">)</span>
			<span class="k">BEGIN</span>
				<span class="k">SET</span> <span class="o">@</span><span class="n">queueName</span> <span class="o">=</span> <span class="s1">'Disabled queue: '</span> <span class="o">+</span> <span class="o">@</span><span class="n">messagebody</span><span class="p">.</span><span class="n">value</span><span class="p">(</span><span class="s1">'/EVENT_INSTANCE[1]/ObjectName[1]'</span><span class="p">,</span> <span class="s1">'VARCHAR(100)'</span><span class="p">);</span>

				<span class="k">EXEC</span> <span class="n">msdb</span><span class="p">.</span><span class="n">dbo</span><span class="p">.</span><span class="n">sp_send_dbmail</span>
					<span class="o">@</span><span class="n">profile_name</span> <span class="o">=</span> <span class="s1">'DBA_Notifications'</span><span class="p">,</span>
					<span class="o">@</span><span class="n">recipients</span> <span class="o">=</span> <span class="o">@</span><span class="n">emailTo</span><span class="p">,</span>
					<span class="o">@</span><span class="n">body</span> <span class="o">=</span> <span class="o">@</span><span class="n">queueName</span><span class="p">,</span>
					<span class="o">@</span><span class="n">subject</span> <span class="o">=</span> <span class="o">@</span><span class="n">queueName</span><span class="p">;</span>

			<span class="k">END</span>

			<span class="n">IF</span> <span class="p">(</span><span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="s1">'http://schemas.microsoft.com/SQL/ServiceBroker/Error'</span><span class="p">)</span>
			<span class="k">BEGIN</span>
					<span class="k">DECLARE</span> <span class="o">@</span><span class="n">errorcode</span> <span class="nb">INT</span>
					<span class="k">DECLARE</span> <span class="o">@</span><span class="n">errormessage</span> <span class="n">NVARCHAR</span><span class="p">(</span><span class="mi">3000</span><span class="p">)</span>
					<span class="c1">-- Extract the error information from the sent message</span>
					<span class="k">SET</span> <span class="o">@</span><span class="n">errorcode</span> <span class="o">=</span> <span class="p">(</span><span class="k">SELECT</span> <span class="o">@</span><span class="n">messagebody</span><span class="p">.</span><span class="n">value</span><span class="p">(</span>
						<span class="n">N</span><span class="s1">'declare namespace brokerns="http://schemas.microsoft.com/SQL/ServiceBroker/Error";
						(/brokerns:Error/brokerns:Code)[1]'</span><span class="p">,</span> <span class="s1">'int'</span><span class="p">));</span>
					<span class="k">SET</span> <span class="o">@</span><span class="n">errormessage</span> <span class="o">=</span> <span class="p">(</span><span class="k">SELECT</span> <span class="o">@</span><span class="n">messagebody</span><span class="p">.</span><span class="n">value</span><span class="p">(</span>
						<span class="s1">'declare namespace brokerns="http://schemas.microsoft.com/SQL/ServiceBroker/Error";
						(/brokerns:Error/brokerns:Description)[1]'</span><span class="p">,</span> <span class="s1">'nvarchar(3000)'</span><span class="p">));</span>

					<span class="c1">-- Log the error</span>

					<span class="c1">-- End the conversation on the initiator's side</span>
					<span class="k">END</span> <span class="n">CONVERSATION</span> <span class="o">@</span><span class="n">ch</span><span class="p">;</span>
			<span class="k">END</span>


			<span class="n">IF</span> <span class="p">(</span><span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="s1">'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog'</span><span class="p">)</span>
			<span class="k">BEGIN</span>
				<span class="c1">-- End the conversation</span>
				<span class="k">END</span> <span class="n">CONVERSATION</span> <span class="o">@</span><span class="n">ch</span><span class="p">;</span>
			<span class="k">END</span>

			<span class="k">COMMIT</span> <span class="n">TRANSACTION</span>
		<span class="k">END</span> <span class="n">TRY</span>
		<span class="k">BEGIN</span> <span class="n">CATCH</span>
			<span class="k">ROLLBACK</span> <span class="n">TRANSACTION</span>
			<span class="k">DECLARE</span> <span class="o">@</span><span class="n">ErrorNum</span> <span class="nb">INT</span>
			<span class="k">DECLARE</span> <span class="o">@</span><span class="n">ErrorMsg</span> <span class="n">NVARCHAR</span><span class="p">(</span><span class="mi">3000</span><span class="p">)</span>
			<span class="k">SELECT</span> <span class="o">@</span><span class="n">ErrorNum</span> <span class="o">=</span> <span class="n">ERROR_NUMBER</span><span class="p">(),</span> <span class="o">@</span><span class="n">ErrorMsg</span> <span class="o">=</span> <span class="n">ERROR_MESSAGE</span><span class="p">()</span>
			<span class="c1">-- log the error</span>
			<span class="n">BREAK</span>
		<span class="k">END</span> <span class="n">CATCH</span>
	<span class="k">END</span>
</code></pre></div></div>

<p>The important piece is that this procedure will execute as owner which will be a dbo schema when service broker activates the internal procedure.</p>

<p>Next we add the queue internal activation</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">ALTER</span> <span class="n">QUEUE</span> <span class="n">DisabledQueueNotificationQueue</span>
<span class="k">WITH</span> <span class="n">ACTIVATION</span>
<span class="p">(</span>
	<span class="n">PROCEDURE_NAME</span> <span class="o">=</span> <span class="n">dbo</span><span class="p">.</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotification</span><span class="p">,</span>
	<span class="n">STATUS</span> <span class="o">=</span> <span class="k">ON</span><span class="p">,</span>
	<span class="n">MAX_QUEUE_READERS</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span>
	<span class="k">EXECUTE</span> <span class="k">AS</span> <span class="k">OWNER</span>
<span class="p">)</span>
</code></pre></div></div>

<p>Finally we create an event notification to send messages when queue gets disabled into the DisabledQueueNotifiactionQueue</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">EVENT</span> <span class="n">NOTIFICATION</span> <span class="n">DisabledTargetQueueNotification</span>
	<span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">dbo</span><span class="p">.</span><span class="n">TargetQueue</span>
	<span class="k">FOR</span> <span class="n">BROKER_QUEUE_DISABLED</span>
	<span class="k">TO</span> <span class="n">SERVICE</span> <span class="s1">'DisabledQueueNotificationService'</span><span class="p">,</span> <span class="s1">'current database'</span><span class="p">;</span>
</code></pre></div></div>

<p>If we try to simulate a poison message and rollback receive 5 times the procedure won’t execute and will log an error:</p>

<blockquote>
  <p>The EXECUTE permission was denied on
the object ‘sp_send_dbmail’, database
‘msdb’, schema ‘dbo’.</p>
</blockquote>

<p>This is expected since the activated stored procedure is calling an msdb database and has no permissions since it is in the public context. Since I trust other database on my sql server I thought that enabling trustworthy would fix this problem: <code class="language-plaintext highlighter-rouge">ALTER DATABASE [msdb] SET TRUSTWORTHY ON</code>. But apparently the setup of my sql server would still not allow a public process to access system database. So the only one thing that was left to do is to create a certificate and sign the procedure so it would be trusted.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">CREATE</span> <span class="n">CERTIFICATE</span> <span class="n">spServiceBroker_SendDisabledQueueEmailNotificationCertificate</span>
    	<span class="n">ENCRYPTION</span> <span class="k">BY</span> <span class="n">PASSWORD</span> <span class="o">=</span> <span class="s1">'SommePass91'</span>
    	<span class="k">WITH</span> <span class="n">SUBJECT</span> <span class="o">=</span> <span class="s1">'spServiceBroker_SendDisabledQueueEmailNotification signing certificate'</span>
    <span class="k">GO</span>

    <span class="k">ADD</span> <span class="n">SIGNATURE</span> <span class="k">TO</span> <span class="k">OBJECT</span><span class="p">::[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotification</span><span class="p">]</span>
    	<span class="k">BY</span> <span class="n">CERTIFICATE</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationCertificate</span><span class="p">]</span>
    	<span class="k">WITH</span> <span class="n">PASSWORD</span> <span class="o">=</span> <span class="s1">'SommePass91'</span>
    <span class="k">GO</span>


    <span class="c1">--------------------------------------------------------------------------------</span>
    <span class="c1">-- We leave the private key so we can resign the procedure later if it changes.</span>
    <span class="c1">-- If we remove the certificate the whole thing will need to be recreated</span>
    <span class="c1">--------------------------------------------------------------------------------</span>
    <span class="c1">--ALTER CERTIFICATE spServiceBroker_SendDisabledQueueEmailNotificationCertificate</span>
    <span class="c1">--	REMOVE PRIVATE KEY</span>
    <span class="c1">--GO</span>

    <span class="n">BACKUP</span> <span class="n">CERTIFICATE</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationCertificate</span><span class="p">]</span>
    	<span class="k">TO</span> <span class="n">FILE</span> <span class="o">=</span> <span class="s1">'c:</span><span class="se">\s</span><span class="s1">pServiceBroker_SendDisabledQueueEmailNotificationCertificate.cert'</span>
    <span class="k">GO</span>

    <span class="n">USE</span> <span class="n">msdb</span>
    <span class="k">GO</span>

    <span class="k">CREATE</span> <span class="n">CERTIFICATE</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationCertificate</span><span class="p">]</span>
    	<span class="k">FROM</span> <span class="n">FILE</span> <span class="o">=</span> <span class="s1">'c:</span><span class="se">\s</span><span class="s1">pServiceBroker_SendDisabledQueueEmailNotificationCertificate.cert'</span>
    <span class="k">GO</span>


    <span class="k">CREATE</span> <span class="k">USER</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationUser</span><span class="p">]</span>
      <span class="k">FROM</span> <span class="n">CERTIFICATE</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationCertificate</span><span class="p">]</span>
    <span class="k">GO</span>

    <span class="k">GRANT</span> <span class="n">AUTHENTICATE</span> <span class="k">TO</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationUser</span><span class="p">]</span>

    <span class="k">GRANT</span> <span class="k">EXECUTE</span> <span class="k">ON</span> <span class="p">[</span><span class="n">sp_send_dbmail</span><span class="p">]</span> <span class="k">TO</span> <span class="p">[</span><span class="n">spServiceBroker_SendDisabledQueueEmailNotificationUser</span><span class="p">];</span>
</code></pre></div></div>

<p>Now that the procedure has access to the <code class="language-plaintext highlighter-rouge">sp_send_dbmail</code> we have no issues and if you simulate poison message, you should receive an email notification with the name of the queue.</p>

										
					<p>Posted in: sql-server-service-broker</p>
						
				
					<p>Tagged with: service-broker and sql-server</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/sql-server-service-broker/setup-disabled-queues-email-notification/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/sql-server-service-broker/setup-disabled-queues-email-notification/]]></guid>
		<pubDate>2012-07-21T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[SQL Server Service Broker troubleshooting external activation]]></title>
		<description>
			<![CDATA[
				<p>Since I’ve been working with Service Broker I realized how tricky it is to administer and hard to see overall picture. I still come across behaviors I don’t understand, and now sure how exactly to reproduce them, they just happen randomly. However I did make a lot of progress on troubleshooting and can get most things back up and running again.</p>

<h3 id="dialogs">Dialogs</h3>

<p>It’s important to know that dialogs are <strong>two way</strong> conversations. Before you send a message to the target you open a dialog conversation. And it will stay open until your target picks it up, calls end conversation and then your initiator side will end conversation as well. Only after your conversation will be closed. And <strong>closed conversation is a successful conversation</strong>. You have to monitor your conversations to make sure they all get closed properly during development and troubleshooting.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">--all going conversations</span>
<span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">sys</span><span class="p">.</span><span class="n">conversation_endpoints</span>
</code></pre></div></div>

<p>Clean up conversations, DON’T USE THIS IN PRODUCTION AS conversations will get deleted.</p>

<p><strong>Update 7/18/2012</strong>
Please note when you remove all conversations it will also disable all EventNotification and so your event notifictions will need to be dropped and created again.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">-- clean up all conversations, DEVELOPMENT ONLY</span>
<span class="k">declare</span> <span class="o">@</span><span class="n">conversation</span> <span class="n">uniqueidentifier</span>
<span class="n">while</span> <span class="k">exists</span> <span class="p">(</span><span class="k">select</span> <span class="mi">1</span> <span class="k">from</span> <span class="n">sys</span><span class="p">.</span><span class="n">conversation_endpoints</span> <span class="k">with</span> <span class="p">(</span><span class="n">nolock</span><span class="p">))</span>
<span class="k">begin</span>
<span class="k">set</span> <span class="o">@</span><span class="n">conversation</span> <span class="o">=</span> <span class="p">(</span><span class="k">select</span> <span class="n">top</span> <span class="mi">1</span> <span class="n">conversation_handle</span> <span class="k">from</span> <span class="n">sys</span><span class="p">.</span><span class="n">conversation_endpoints</span> <span class="k">with</span> <span class="p">(</span><span class="n">nolock</span><span class="p">)</span> <span class="p">)</span>
<span class="k">end</span> <span class="n">conversation</span> <span class="o">@</span><span class="n">conversation</span> <span class="k">with</span> <span class="n">cleanup</span>
<span class="k">end</span>
</code></pre></div></div>

<p>If you are building some kinda of a tool that will show the status of your messages you will probably want to save conversation handles and map it to the id of your message that way you can trace back to what’s going on with your message.</p>

<h3 id="event-notifications">Event notifications</h3>

<p>Event notifications add extra learning of how notifications work, and know how to fix them.</p>

<p>First thing you define your event notification</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">EVENT</span> <span class="n">NOTIFICATION</span> <span class="n">EventNotificationTargetQueue</span>
    <span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">dbo</span><span class="p">.</span><span class="n">TargetQueue</span>
    <span class="k">FOR</span> <span class="n">QUEUE_ACTIVATION</span>
    <span class="k">TO</span> <span class="n">SERVICE</span> <span class="s1">'ExternalActivatorService'</span><span class="p">,</span> <span class="s1">'E56C42F3-9885-0000-8983-7CA3B5C32362'</span><span class="p">;</span>
</code></pre></div></div>

<p>and you should see it in</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">--see event notifications</span>
<span class="k">SELECT</span> <span class="o">*</span> <span class="k">FROM</span> <span class="n">sys</span><span class="p">.</span><span class="n">event_notifications</span>
</code></pre></div></div>

<p>I found that if you clean up your conversations sometimes event notifications will disappear, so it’s a good idea to keep an eye on the sys.event_notifications if you activation is not being triggered.</p>

<p>Now we get to the fun part. After we have turned on activation on a queue and send a message, the queue will go into a NOTIFIED state. When queue goes into a notified state the external activation queue will receive a message saying that the queue has been activated. The question is, does the external activation queue receives an activation message for each message that goes into a queue, the answer is no. Only when a queue is not in NOTIFIED state then when you put a message into a queue it will trigger an activation queue message and put queue into NOTIFIED.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">--see queue monitors</span>
<span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">sys</span><span class="p">.</span><span class="n">dm_broker_queue_monitors</span> <span class="n">m</span> <span class="k">with</span> <span class="p">(</span><span class="n">nolock</span><span class="p">)</span>
<span class="k">join</span> <span class="n">sys</span><span class="p">.</span><span class="n">service_queues</span> <span class="n">q</span> <span class="k">with</span> <span class="p">(</span><span class="n">nolock</span><span class="p">)</span> <span class="k">on</span> <span class="n">m</span><span class="p">.</span><span class="n">queue_id</span> <span class="o">=</span> <span class="n">q</span><span class="p">.</span><span class="n">object_id</span>
</code></pre></div></div>

<p>And there are times when queue can get stuck in NOTIFIED state and you have no message in the queue. If that happens you will have to run this command</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">RECEIVE</span> <span class="n">TOP</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="o">*</span> <span class="k">FROM</span> <span class="n">TargetQueue</span><span class="p">;</span>
</code></pre></div></div>

<p>If the messages were cleared improperly this will fix the queue and set it back to INACTIVE state.</p>

<h3 id="event-notification-troubleshooting">Event notification troubleshooting</h3>

<p>It’s important to understand that every time you create an event notification that creates a queue monitor for your queue, you can view queue monitors:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">sys</span><span class="p">.</span><span class="n">dm_broker_queue_monitors</span> <span class="n">m</span> <span class="k">with</span> <span class="p">(</span><span class="n">nolock</span><span class="p">)</span>
<span class="k">join</span> <span class="n">sys</span><span class="p">.</span><span class="n">service_queues</span> <span class="n">q</span> <span class="k">with</span> <span class="p">(</span><span class="n">nolock</span><span class="p">)</span> <span class="k">on</span> <span class="n">m</span><span class="p">.</span><span class="n">queue_id</span> <span class="o">=</span> <span class="n">q</span><span class="p">.</span><span class="n">object_id</span>
</code></pre></div></div>

<p>So even if you can see your event notifications in <code class="language-plaintext highlighter-rouge">SELECT * FROM sys.event_notifications</code> it does not mean that your queue will activate an event. It must have both queue monitor and state of the queue monitor is not in NOTIFIED state.</p>

<p>In addition, conversations on event notifications are not meant to be closed by calling “end dialog”. They need to stay open or in “CONVERSING” to properly dispatch notifications. The conversation on event notification will only get ended when you drop your event notification.
If your queue in <code class="language-plaintext highlighter-rouge">sys.dm_broker_queue_monitors</code> is in the INACTIVE state and you see your event is in the sys.event_notifications, and your you still don’t receive activation messages, what happened is your conversation on the event notification got ended. To fix you can drop and create notification and it will work again.</p>

<p>That’s it for now, good luck troubleshooting external activation!</p>

				<p>Since I’ve been working with Service Broker I realized how tricky it is to administer and hard to see overall picture. I still come across behaviors I don’t understand, and now sure how exactly to reproduce them, they just happen randomly. However I did make a lot of progress on troubleshooting and can get most things back up and running again.</p>

<h3 id="dialogs">Dialogs</h3>

<p>It’s important to know that dialogs are <strong>two way</strong> conversations. Before you send a message to the target you open a dialog conversation. And it will stay open until your target picks it up, calls end conversation and then your initiator side will end conversation as well. Only after your conversation will be closed. And <strong>closed conversation is a successful conversation</strong>. You have to monitor your conversations to make sure they all get closed properly during development and troubleshooting.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">--all going conversations</span>
<span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">sys</span><span class="p">.</span><span class="n">conversation_endpoints</span>
</code></pre></div></div>

<p>Clean up conversations, DON’T USE THIS IN PRODUCTION AS conversations will get deleted.</p>

<p><strong>Update 7/18/2012</strong>
Please note when you remove all conversations it will also disable all EventNotification and so your event notifictions will need to be dropped and created again.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">-- clean up all conversations, DEVELOPMENT ONLY</span>
<span class="k">declare</span> <span class="o">@</span><span class="n">conversation</span> <span class="n">uniqueidentifier</span>
<span class="n">while</span> <span class="k">exists</span> <span class="p">(</span><span class="k">select</span> <span class="mi">1</span> <span class="k">from</span> <span class="n">sys</span><span class="p">.</span><span class="n">conversation_endpoints</span> <span class="k">with</span> <span class="p">(</span><span class="n">nolock</span><span class="p">))</span>
<span class="k">begin</span>
<span class="k">set</span> <span class="o">@</span><span class="n">conversation</span> <span class="o">=</span> <span class="p">(</span><span class="k">select</span> <span class="n">top</span> <span class="mi">1</span> <span class="n">conversation_handle</span> <span class="k">from</span> <span class="n">sys</span><span class="p">.</span><span class="n">conversation_endpoints</span> <span class="k">with</span> <span class="p">(</span><span class="n">nolock</span><span class="p">)</span> <span class="p">)</span>
<span class="k">end</span> <span class="n">conversation</span> <span class="o">@</span><span class="n">conversation</span> <span class="k">with</span> <span class="n">cleanup</span>
<span class="k">end</span>
</code></pre></div></div>

<p>If you are building some kinda of a tool that will show the status of your messages you will probably want to save conversation handles and map it to the id of your message that way you can trace back to what’s going on with your message.</p>

<h3 id="event-notifications">Event notifications</h3>

<p>Event notifications add extra learning of how notifications work, and know how to fix them.</p>

<p>First thing you define your event notification</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">EVENT</span> <span class="n">NOTIFICATION</span> <span class="n">EventNotificationTargetQueue</span>
    <span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">dbo</span><span class="p">.</span><span class="n">TargetQueue</span>
    <span class="k">FOR</span> <span class="n">QUEUE_ACTIVATION</span>
    <span class="k">TO</span> <span class="n">SERVICE</span> <span class="s1">'ExternalActivatorService'</span><span class="p">,</span> <span class="s1">'E56C42F3-9885-0000-8983-7CA3B5C32362'</span><span class="p">;</span>
</code></pre></div></div>

<p>and you should see it in</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">--see event notifications</span>
<span class="k">SELECT</span> <span class="o">*</span> <span class="k">FROM</span> <span class="n">sys</span><span class="p">.</span><span class="n">event_notifications</span>
</code></pre></div></div>

<p>I found that if you clean up your conversations sometimes event notifications will disappear, so it’s a good idea to keep an eye on the sys.event_notifications if you activation is not being triggered.</p>

<p>Now we get to the fun part. After we have turned on activation on a queue and send a message, the queue will go into a NOTIFIED state. When queue goes into a notified state the external activation queue will receive a message saying that the queue has been activated. The question is, does the external activation queue receives an activation message for each message that goes into a queue, the answer is no. Only when a queue is not in NOTIFIED state then when you put a message into a queue it will trigger an activation queue message and put queue into NOTIFIED.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">--see queue monitors</span>
<span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">sys</span><span class="p">.</span><span class="n">dm_broker_queue_monitors</span> <span class="n">m</span> <span class="k">with</span> <span class="p">(</span><span class="n">nolock</span><span class="p">)</span>
<span class="k">join</span> <span class="n">sys</span><span class="p">.</span><span class="n">service_queues</span> <span class="n">q</span> <span class="k">with</span> <span class="p">(</span><span class="n">nolock</span><span class="p">)</span> <span class="k">on</span> <span class="n">m</span><span class="p">.</span><span class="n">queue_id</span> <span class="o">=</span> <span class="n">q</span><span class="p">.</span><span class="n">object_id</span>
</code></pre></div></div>

<p>And there are times when queue can get stuck in NOTIFIED state and you have no message in the queue. If that happens you will have to run this command</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">RECEIVE</span> <span class="n">TOP</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span> <span class="o">*</span> <span class="k">FROM</span> <span class="n">TargetQueue</span><span class="p">;</span>
</code></pre></div></div>

<p>If the messages were cleared improperly this will fix the queue and set it back to INACTIVE state.</p>

<h3 id="event-notification-troubleshooting">Event notification troubleshooting</h3>

<p>It’s important to understand that every time you create an event notification that creates a queue monitor for your queue, you can view queue monitors:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">sys</span><span class="p">.</span><span class="n">dm_broker_queue_monitors</span> <span class="n">m</span> <span class="k">with</span> <span class="p">(</span><span class="n">nolock</span><span class="p">)</span>
<span class="k">join</span> <span class="n">sys</span><span class="p">.</span><span class="n">service_queues</span> <span class="n">q</span> <span class="k">with</span> <span class="p">(</span><span class="n">nolock</span><span class="p">)</span> <span class="k">on</span> <span class="n">m</span><span class="p">.</span><span class="n">queue_id</span> <span class="o">=</span> <span class="n">q</span><span class="p">.</span><span class="n">object_id</span>
</code></pre></div></div>

<p>So even if you can see your event notifications in <code class="language-plaintext highlighter-rouge">SELECT * FROM sys.event_notifications</code> it does not mean that your queue will activate an event. It must have both queue monitor and state of the queue monitor is not in NOTIFIED state.</p>

<p>In addition, conversations on event notifications are not meant to be closed by calling “end dialog”. They need to stay open or in “CONVERSING” to properly dispatch notifications. The conversation on event notification will only get ended when you drop your event notification.
If your queue in <code class="language-plaintext highlighter-rouge">sys.dm_broker_queue_monitors</code> is in the INACTIVE state and you see your event is in the sys.event_notifications, and your you still don’t receive activation messages, what happened is your conversation on the event notification got ended. To fix you can drop and create notification and it will work again.</p>

<p>That’s it for now, good luck troubleshooting external activation!</p>

										
					<p>Posted in: sql-server-service-broker</p>
						
				
					<p>Tagged with: service-broker and external-activation</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/sql-server-service-broker/troubleshooting-external-activation/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/sql-server-service-broker/troubleshooting-external-activation/]]></guid>
		<pubDate>2012-07-13T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[2 Legged OAuth with RestSharp]]></title>
		<description>
			<![CDATA[
				<p><a href="https://github.com/restsharp/">Restsharp</a> is a nice little library that abstracts calling webservices in .NET. It also provides ability to add authenticators to web requests which add required oauth signatures and tokens. At first I didn’t see the 2 Legged Oauth authenticator, but after almost going through the pain of making my own I’ve discovered that it does support 2 legged oauth. Here is how to create an authenticated 2 legged Oauth request.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="kt">var</span> <span class="n">client</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">RestClient</span><span class="p">(</span><span class="n">FactualApiUrl</span><span class="p">);</span>
    <span class="n">client</span><span class="p">.</span><span class="n">Authenticator</span> <span class="p">=</span> <span class="n">OAuth1Authenticator</span><span class="p">.</span><span class="nf">ForProtectedResource</span><span class="p">(</span><span class="n">oAuthKey</span><span class="p">,</span> <span class="n">oAuthSecret</span><span class="p">,</span> <span class="kt">string</span><span class="p">.</span><span class="n">Empty</span><span class="p">,</span> <span class="kt">string</span><span class="p">.</span><span class="n">Empty</span><span class="p">);</span>
    <span class="n">client</span><span class="p">.</span><span class="nf">Execute</span><span class="p">(</span><span class="n">request</span><span class="p">);</span>
</code></pre></div></div>

<p>Hopefully it will save you some time next time.</p>

<p>P.S. The latest .NET 4 version 103.1 in NuGet for some reason is missing the authenticators, so you can get a previous version or get latest from GitHub and compile and you shold have no problems.</p>


				<p><a href="https://github.com/restsharp/">Restsharp</a> is a nice little library that abstracts calling webservices in .NET. It also provides ability to add authenticators to web requests which add required oauth signatures and tokens. At first I didn’t see the 2 Legged Oauth authenticator, but after almost going through the pain of making my own I’ve discovered that it does support 2 legged oauth. Here is how to create an authenticated 2 legged Oauth request.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="kt">var</span> <span class="n">client</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">RestClient</span><span class="p">(</span><span class="n">FactualApiUrl</span><span class="p">);</span>
    <span class="n">client</span><span class="p">.</span><span class="n">Authenticator</span> <span class="p">=</span> <span class="n">OAuth1Authenticator</span><span class="p">.</span><span class="nf">ForProtectedResource</span><span class="p">(</span><span class="n">oAuthKey</span><span class="p">,</span> <span class="n">oAuthSecret</span><span class="p">,</span> <span class="kt">string</span><span class="p">.</span><span class="n">Empty</span><span class="p">,</span> <span class="kt">string</span><span class="p">.</span><span class="n">Empty</span><span class="p">);</span>
    <span class="n">client</span><span class="p">.</span><span class="nf">Execute</span><span class="p">(</span><span class="n">request</span><span class="p">);</span>
</code></pre></div></div>

<p>Hopefully it will save you some time next time.</p>

<p>P.S. The latest .NET 4 version 103.1 in NuGet for some reason is missing the authenticators, so you can get a previous version or get latest from GitHub and compile and you shold have no problems.</p>


										
					<p>Posted in: asp.net</p>
						
				
					<p>Tagged with: restsharp, oauth, and asp.net</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/asp-net/restsharp-2-legged-oath/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/asp-net/restsharp-2-legged-oath/]]></guid>
		<pubDate>2012-07-05T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Service Broker: Scalable Web Service Calls From SQL Database]]></title>
		<description>
			<![CDATA[
				<h3 id="what-can-service-broker-do-for-you">What can Service Broker do for you.</h3>

<p>You might not have heard of the Service Broker before, I know I haven’t up until a month ago and after learning what it can do, I think all .NET developers should at least be familiar with it. It comes free with SQL Server and no additional installation is required. Some of the highlights for me are asynchronous triggers, reliability, offloading of long running batch jobs or activating external applications that might call for example Web Services. And some other great but rarely used features like Sql Server notifying the application layer when the data has changed which can be combined with a caching layer to make a very efficient and fast application. In fact list goes on.</p>

<h4 id="asynchronous-triggers">Asynchronous triggers</h4>

<p>First of all triggers in the SQL database are synchronous and they do an implicit lock on the database tables when an operation on the table is happening. I’m not a big fan of triggers myself, but there are time when you have no choice but use them. For example if you have no control when table gets update from application layer and you need to have some sort of processing when record is modified, deleted or added. So Service Broker solves this problem by creating a message queue for items that need to be processed instead of processing them right away. That in result creates asynchronous triggers because messages are sent to be processed when resources are available.</p>

<h4 id="reliable-messaging">Reliable messaging</h4>

<p>Another great benefit of Service Broker is that it provides a reliable mechanism of a messaging queue. Message only gets de-queued when a processing application processes a message and commits a transaction and message can be taken off the queue. If your SQL Server shuts down all your messages stay in the queue as it works just like any other sql table. If processing fails, the message never leaves the queue and will get retried shortly.</p>

<h4 id="external-activation">External activation</h4>

<p>External activation might sound alien right now, but it’s not hard to understand. Basically when message arrives at the service broker queue you will need to provide an activation (or what is going to process that message). There are two types of activation internal or external. Internal activation is a stored procedure or a stored procedure calling a SQLCLR, it’s basically everything that happens inside of SQL server instance. External activation is when SQL notifies an external process (completely outside of sql) that some change is waiting to be processed. What external activation allows is to offload tasks that don’t belong inside of SQL server like calling Web Services or some kind of long running batch processes that communicate with other systems. In addition external activation does not require deployment of .NET assemblies inside of SQL Server and does not require SQLCLR.</p>

<h4 id="other">Other</h4>

<p>There are a lot of other features like a reliable replication between SQL Servers, scalable distributed messaging queues and many others. Many of which will most likely be handles by a SQL DBA. What got me started on Service Broker is figuring out how to asynchornously call Web Services from a database trigger and I think it does an awesome job of doing that. Also while reading the <a href="http://www.amazon.com/gp/product/1590599993/ref=as_li_ss_tl?ie=UTF8&amp;tag=sermassblo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1590599993">Pro Service Broker book</a> I found out that it can do manage code notifications that can for example invalidate cache in your application layer.</p>

<h3 id="no-more-theory-lets-implement-asynchornous-triggers-calling-web-services">No more theory, let’s implement asynchornous triggers calling web services!</h3>

<p>Service Broker is a part of the Microsoft SQL Server and doesn’t need to be installed separately, just enabled. like this:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="n">name</span><span class="p">,</span> <span class="n">is_broker_enabled</span> <span class="k">FROM</span> <span class="n">sys</span><span class="p">.</span><span class="n">databases</span>
<span class="k">ALTER</span> <span class="k">DATABASE</span> <span class="p">[</span><span class="o">&lt;</span><span class="n">dbname</span><span class="o">&gt;</span><span class="p">]</span> <span class="k">SET</span> <span class="n">ENABLE_BROKER</span> <span class="k">WITH</span> <span class="k">ROLLBACK</span> <span class="k">IMMEDIATE</span><span class="p">;</span>
</code></pre></div></div>

<p>After we need to setup SQL Service Broker with needed objects.</p>

<p>Message types, these define types of messages being sent and received, we’ll use well formed xml, and for type you want a unique name a url is used by convention:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">MESSAGE</span> <span class="k">TYPE</span> <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">RequestMessage</span><span class="p">]</span>
<span class="n">VALIDATION</span> <span class="o">=</span> <span class="n">WELL_FORMED_XML</span>

<span class="k">CREATE</span> <span class="n">MESSAGE</span> <span class="k">TYPE</span> <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">ResponseMessage</span><span class="p">]</span>
    <span class="n">VALIDATION</span> <span class="o">=</span> <span class="n">WELL_FORMED_XML</span>
</code></pre></div></div>

<p>Contract defines how messages are being sent:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">CONTRACT</span> <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">ImportContract</span><span class="p">]</span>
<span class="p">(</span>
    <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">OrderImportRequestMessage</span><span class="p">]</span> <span class="n">SENT</span> <span class="k">BY</span> <span class="n">INITIATOR</span><span class="p">,</span>
    <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">OrderImportResponseMessage</span><span class="p">]</span> <span class="n">SENT</span> <span class="k">BY</span> <span class="n">TARGET</span>
<span class="p">)</span>
</code></pre></div></div>

<p>Now we will need two queues to hold our target messages (messages which will be processed by an activation program) and response messages for initiator which we will get as a response from activation program and processed by initiator).</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">QUEUE</span> <span class="n">InitiatorQueue</span>
<span class="k">WITH</span> <span class="n">STATUS</span> <span class="o">=</span> <span class="k">ON</span>

<span class="k">CREATE</span> <span class="n">QUEUE</span> <span class="n">TargetQueue</span>
</code></pre></div></div>

<p>Here I need to point out that in order for service broker to be reliable it uses a concept of dialogs basically once conversation dialog is open <strong>both sides will need to close conversations on their ends</strong>. It also happens that messages only get’s de-queued when the conversation end is received from another party. It will make more sense later.</p>

<p>Next, we will need to create a services, which is basically a service that routes messages, you will need to specify a contract defined earlier, like this:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">SERVICE</span> <span class="n">InitiatorService</span>
<span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">InitiatorQueue</span>
<span class="p">(</span>
    <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">Contract</span><span class="p">]</span>
<span class="p">)</span>

<span class="k">CREATE</span> <span class="n">SERVICE</span> <span class="n">TargetService</span>
<span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">TargetQueue</span>
<span class="p">(</span>
    <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">Contract</span><span class="p">]</span>
<span class="p">)</span>
</code></pre></div></div>

<p>Since we will be using external application activation we need to disable internal activation on the target queue. To enable external activation Service Broker send a message to the external activation queue when a message arrives at the target queue. This allows for centralizing all external queue notification. And as my co-worker <a href="http://fordevsbydevs.blogspot.com">Vincent</a> pointed out this external queue can be used across databases, so there will be one central external notification queue for for all databases.</p>

<p>Let’s create that notification queue</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">QUEUE</span> <span class="n">ExternalActivatorQueue</span>
</code></pre></div></div>

<p>Then we will also need a service for that queue, as you see it uses a generic contract provided by microsoft for event notifications:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">SERVICE</span> <span class="n">ExternalActivatorService</span>
<span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">ExternalActivatorQueue</span>
<span class="p">(</span>
    <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">schemas</span><span class="p">.</span><span class="n">microsoft</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="k">SQL</span><span class="o">/</span><span class="n">Notifications</span><span class="o">/</span><span class="n">PostEventNotification</span><span class="p">]</span>
<span class="p">)</span>
</code></pre></div></div>

<p>Finally we subscribe to the internal QUEUE_ACTIVATION event on our “TargetQueue”, so that we will receive notification in our ExternalActivationQueue when the TargetQueue gets messages.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">EVENT</span> <span class="n">NOTIFICATION</span> <span class="n">EventNotificationTargetQueue</span>
    <span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">TargetQueue</span>
    <span class="k">FOR</span> <span class="n">QUEUE_ACTIVATION</span>
    <span class="k">TO</span> <span class="n">SERVICE</span> <span class="s1">'ExternalActivatorService'</span><span class="p">,</span> <span class="s1">'current database'</span><span class="p">;</span>
</code></pre></div></div>

<p>Here comes the time to create our SQL trigger which instead of doing a synchronous operation will quickly send a message to the queue for later instead of processing it. This is the concept of asynchronous triggers at work, we are firing and forgetting instead of waiting for response right away. The most important part is the <strong>SEND ON CONVERSATION @ch
MESSAGE TYPE <a href="@messageBody">http://blog.maskalik.com/RequestMessage</a>;</strong> this is where we send the message to the queue.
Creating a sample order table and a trigger which will send a message when a new order is inserted:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="p">[</span><span class="k">Order</span><span class="p">]</span>
<span class="p">(</span>
    <span class="n">ID</span> <span class="n">UNIQUEIDENTIFIER</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="n">Amount</span> <span class="n">MONEY</span> <span class="k">NOT</span> <span class="k">NULL</span>
<span class="p">)</span>

<span class="c1">-- Trigger will add a message into a ImportQueue</span>
<span class="k">CREATE</span> <span class="k">TRIGGER</span> <span class="n">OnOrderInserted</span> <span class="k">ON</span> <span class="p">[</span><span class="k">Order</span><span class="p">]</span> <span class="k">FOR</span> <span class="k">INSERT</span>
<span class="k">AS</span>
<span class="k">BEGIN</span>
    <span class="k">BEGIN</span> <span class="n">TRANSACTION</span><span class="p">;</span>
        <span class="k">DECLARE</span> <span class="o">@</span><span class="n">ch</span> <span class="n">UNIQUEIDENTIFIER</span>
        <span class="k">DECLARE</span> <span class="o">@</span><span class="n">messageBody</span> <span class="n">NVARCHAR</span><span class="p">(</span><span class="k">MAX</span><span class="p">);</span>

        <span class="k">BEGIN</span> <span class="n">DIALOG</span> <span class="n">CONVERSATION</span> <span class="o">@</span><span class="n">ch</span>
            <span class="k">FROM</span> <span class="n">SERVICE</span> <span class="p">[</span><span class="n">InitiatorService</span><span class="p">]</span>
            <span class="k">TO</span> <span class="n">SERVICE</span> <span class="s1">'TargetService'</span>
            <span class="k">ON</span> <span class="n">CONTRACT</span> <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">Contract</span><span class="p">]</span>
            <span class="k">WITH</span> <span class="n">ENCRYPTION</span> <span class="o">=</span> <span class="k">OFF</span><span class="p">;</span>

        <span class="c1">-- Construct the request message</span>
        <span class="k">SET</span> <span class="o">@</span><span class="n">messageBody</span> <span class="o">=</span> <span class="p">(</span><span class="k">SELECT</span> <span class="n">ID</span><span class="p">,</span> <span class="n">Amount</span> <span class="k">FROM</span> <span class="p">[</span><span class="k">Order</span><span class="p">]</span> <span class="k">FOR</span> <span class="n">XML</span> <span class="n">AUTO</span><span class="p">,</span> <span class="n">ELEMENTS</span><span class="p">);</span>

        <span class="c1">-- Send the message to the TargetService</span>
        <span class="p">;</span><span class="n">SEND</span> <span class="k">ON</span> <span class="n">CONVERSATION</span> <span class="o">@</span><span class="n">ch</span>
        <span class="n">MESSAGE</span> <span class="k">TYPE</span> <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">RequestMessage</span><span class="p">]</span> <span class="p">(</span><span class="o">@</span><span class="n">messageBody</span><span class="p">);</span>
    <span class="k">COMMIT</span><span class="p">;</span>
<span class="k">END</span>
<span class="k">GO</span>
</code></pre></div></div>

<p>So now when we add an order the trigger will send a message which will see it in our TargetQueue and ExternalActivationQueue. Target queue will wait for someone to process and ExternalActivationQueue will wait until external activation program will read that message.</p>

<p><img src="/uploads/12-06/QueuesAfterInsert.png" alt="Results from queues" /></p>

<p>What do I mean by external activation program… Well that’s the program that listens to the Activation Queue and basically reads messages and starts predefined application for that queue. And when application starts it knows that it has to read it’s designated queue and process messages in it. Luckily Microsoft already create that <a href="http://blogs.msdn.com/b/sql_service_broker/archive/2008/11/21/announcing-service-broker-external-activator.aspx">external activation service application</a> and it is available <a href="http://www.microsoft.com/en-us/download/details.aspx?id=16978">here</a>, scroll down and you will see Microsoft® SQL Server® Service Broker External Activator for SQL Server® 2008 R2.</p>

<p>After you install the service, you will need to read documentation and edit the config file. It’s pretty trivial to do, you will need to specify your database name where activation queue is, your targetqueue name and which executable file to run when a message comes to the targetqueue. If you are having problems take a look at the error log, that helped me to get it up and running. Once you have configuration done, start the service and it will run if there are no configuration issues. Also keep in mind that service is only designed to work in integrated security mode.</p>

<p>But before you start the service we need to create an app that will process our messages and notify the queue that we have successfully processes so it can end the conversation and de-queue the message. Here are the highlights of that app:</p>

<p>It’s a console application with a main <code class="language-plaintext highlighter-rouge">while (true)</code> loop that uses ADO.NET to send Service Broker Command to RECEIVE message on the specified queue. It receives a message, but still keeps it on the queue until commit is called.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">...</span>
<span class="n">broker</span><span class="p">.</span><span class="n">tran</span> <span class="p">=</span> <span class="n">broker</span><span class="p">.</span><span class="n">cnn</span><span class="p">.</span><span class="nf">BeginTransaction</span><span class="p">();</span>
<span class="n">broker</span><span class="p">.</span><span class="nf">Receive</span><span class="p">(</span><span class="s">"TargetQueue"</span><span class="p">,</span> <span class="k">out</span> <span class="n">msgType</span><span class="p">,</span> <span class="k">out</span> <span class="n">msg</span><span class="p">,</span> <span class="k">out</span> <span class="n">serviceInstance</span><span class="p">,</span> <span class="k">out</span> <span class="n">dialogHandle</span><span class="p">);</span>

<span class="k">if</span> <span class="p">(</span><span class="n">msg</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">broker</span><span class="p">.</span><span class="n">tran</span><span class="p">.</span><span class="nf">Commit</span><span class="p">();</span>
    <span class="k">break</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">switch</span> <span class="p">(</span><span class="n">msgType</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">case</span> <span class="s">"http://blog.maskalik.com/RequestMessage"</span><span class="p">:</span>
    <span class="p">{</span>
        <span class="c1">//right here we call a web service or whatever processing you do</span>
        <span class="c1">//also use T-SQL to parse @msg from the queue to get data</span>
        <span class="n">broker</span><span class="p">.</span><span class="nf">Send</span><span class="p">(</span><span class="n">dialogHandle</span><span class="p">,</span> <span class="s">"&lt;Response&gt;&lt;OrderId&gt;1&lt;/OrderId&gt;&lt;Status&gt;Processed&lt;/Status&gt;&lt;/Response&gt;"</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">case</span> <span class="s">"http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog"</span><span class="p">:</span>
    <span class="p">{</span>
            <span class="n">broker</span><span class="p">.</span><span class="nf">EndDialog</span><span class="p">(</span><span class="n">dialogHandle</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="n">broker</span><span class="p">.</span><span class="n">tran</span><span class="p">.</span><span class="nf">Commit</span><span class="p">();</span>
<span class="p">...</span>
</code></pre></div></div>

<p>Basically the transaction only gets committed when we process message and that deletes a message of the queue hence the reliability of the message processing. Also remember it is important to end conversations on both ends.</p>

<p>When reply is sent from an external .NET application we need to process it inside the SQL Server. For this we will use an internally activated service which will call a stored procedure which will simply take that message, parse xml and insert it into a table.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="k">PROCEDURE</span> <span class="n">ProcessResponseMessages</span>
<span class="k">AS</span>
<span class="k">BEGIN</span>
    <span class="k">DECLARE</span> <span class="o">@</span><span class="n">ch</span> <span class="n">UNIQUEIDENTIFIER</span><span class="p">;</span>
    <span class="k">DECLARE</span> <span class="o">@</span><span class="n">messagetypename</span> <span class="n">NVARCHAR</span><span class="p">(</span><span class="mi">256</span><span class="p">);</span>
    <span class="k">DECLARE</span>	<span class="o">@</span><span class="n">messagebody</span> <span class="n">XML</span><span class="p">;</span>
    <span class="k">DECLARE</span> <span class="o">@</span><span class="n">responsemessage</span> <span class="n">XML</span><span class="p">;</span>

    <span class="n">WHILE</span> <span class="p">(</span><span class="mi">1</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">BEGIN</span>
        <span class="k">BEGIN</span> <span class="n">TRANSACTION</span>

        <span class="n">WAITFOR</span> <span class="p">(</span>
            <span class="n">RECEIVE</span> <span class="n">TOP</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
                <span class="o">@</span><span class="n">ch</span> <span class="o">=</span> <span class="n">conversation_handle</span><span class="p">,</span>
                <span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="n">message_type_name</span><span class="p">,</span>
                <span class="o">@</span><span class="n">messagebody</span> <span class="o">=</span> <span class="k">CAST</span><span class="p">(</span><span class="n">message_body</span> <span class="k">AS</span> <span class="n">XML</span><span class="p">)</span>
            <span class="k">FROM</span>
                <span class="n">InitiatorQueue</span>
        <span class="p">),</span> <span class="n">TIMEOUT</span> <span class="mi">1000</span>

        <span class="n">IF</span> <span class="p">(</span><span class="o">@@</span><span class="n">ROWCOUNT</span> <span class="o">=</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">BEGIN</span>
            <span class="k">ROLLBACK</span> <span class="n">TRANSACTION</span>
            <span class="n">BREAK</span>
        <span class="k">END</span>

        <span class="n">IF</span> <span class="p">(</span><span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="s1">'http://blog.maskalik.com/ResponseMessage'</span><span class="p">)</span>
        <span class="k">BEGIN</span>
            <span class="k">INSERT</span> <span class="k">INTO</span> <span class="n">ProcessedOrders</span> <span class="p">(</span><span class="n">ID</span><span class="p">,</span> <span class="n">SentTime</span><span class="p">)</span> <span class="k">VALUES</span>
            <span class="p">(</span>
                <span class="o">@</span><span class="n">messagebody</span><span class="p">.</span><span class="n">value</span><span class="p">(</span><span class="s1">'/Response/OrderId[1]'</span><span class="p">,</span> <span class="s1">'INT'</span><span class="p">),</span>
                <span class="n">GETDATE</span><span class="p">()</span>
            <span class="p">)</span>
        <span class="k">END</span>

        <span class="n">IF</span> <span class="p">(</span><span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="s1">'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog'</span><span class="p">)</span>
        <span class="k">BEGIN</span>
            <span class="c1">-- End the conversation</span>
            <span class="k">END</span> <span class="n">CONVERSATION</span> <span class="o">@</span><span class="n">ch</span><span class="p">;</span>
        <span class="k">END</span>

        <span class="k">COMMIT</span> <span class="n">TRANSACTION</span>
    <span class="k">END</span>
<span class="k">END</span>
<span class="k">GO</span>
</code></pre></div></div>

<p>Finally we alter our InitiatorQueue to turn on internal activation with provided stored procedure.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">ALTER</span> <span class="n">QUEUE</span> <span class="n">InitiatorQueue</span>
<span class="k">WITH</span> <span class="n">ACTIVATION</span>
<span class="p">(</span>
    <span class="n">PROCEDURE_NAME</span> <span class="o">=</span> <span class="n">ProcessResponseMessages</span><span class="p">,</span>
    <span class="n">STATUS</span> <span class="o">=</span> <span class="k">ON</span><span class="p">,</span>
    <span class="n">MAX_QUEUE_READERS</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span>
    <span class="k">EXECUTE</span> <span class="k">AS</span> <span class="k">OWNER</span>
<span class="p">)</span>
</code></pre></div></div>

<h3 id="final-words">Final words</h3>

<p>It seems like a lot of configuration and setup, and it is. However what you do get is offloading of processing of your message outside of SQL Server which can call something like Web Services. You will also get reliability and scalability that service broker offers. And you don’t have to deploy assemblies into SQL and there is many other things you can do like paralel processeing, conversetion group locking and a ton of other things that you will need to read for yourself in <a href="http://www.amazon.com/gp/product/1590599993/ref=as_li_ss_tl?ie=UTF8&amp;tag=sermassblo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1590599993">Pro SQL Service Broker 2008 book</a>. Good luck!</p>


				<h3 id="what-can-service-broker-do-for-you">What can Service Broker do for you.</h3>

<p>You might not have heard of the Service Broker before, I know I haven’t up until a month ago and after learning what it can do, I think all .NET developers should at least be familiar with it. It comes free with SQL Server and no additional installation is required. Some of the highlights for me are asynchronous triggers, reliability, offloading of long running batch jobs or activating external applications that might call for example Web Services. And some other great but rarely used features like Sql Server notifying the application layer when the data has changed which can be combined with a caching layer to make a very efficient and fast application. In fact list goes on.</p>

<h4 id="asynchronous-triggers">Asynchronous triggers</h4>

<p>First of all triggers in the SQL database are synchronous and they do an implicit lock on the database tables when an operation on the table is happening. I’m not a big fan of triggers myself, but there are time when you have no choice but use them. For example if you have no control when table gets update from application layer and you need to have some sort of processing when record is modified, deleted or added. So Service Broker solves this problem by creating a message queue for items that need to be processed instead of processing them right away. That in result creates asynchronous triggers because messages are sent to be processed when resources are available.</p>

<h4 id="reliable-messaging">Reliable messaging</h4>

<p>Another great benefit of Service Broker is that it provides a reliable mechanism of a messaging queue. Message only gets de-queued when a processing application processes a message and commits a transaction and message can be taken off the queue. If your SQL Server shuts down all your messages stay in the queue as it works just like any other sql table. If processing fails, the message never leaves the queue and will get retried shortly.</p>

<h4 id="external-activation">External activation</h4>

<p>External activation might sound alien right now, but it’s not hard to understand. Basically when message arrives at the service broker queue you will need to provide an activation (or what is going to process that message). There are two types of activation internal or external. Internal activation is a stored procedure or a stored procedure calling a SQLCLR, it’s basically everything that happens inside of SQL server instance. External activation is when SQL notifies an external process (completely outside of sql) that some change is waiting to be processed. What external activation allows is to offload tasks that don’t belong inside of SQL server like calling Web Services or some kind of long running batch processes that communicate with other systems. In addition external activation does not require deployment of .NET assemblies inside of SQL Server and does not require SQLCLR.</p>

<h4 id="other">Other</h4>

<p>There are a lot of other features like a reliable replication between SQL Servers, scalable distributed messaging queues and many others. Many of which will most likely be handles by a SQL DBA. What got me started on Service Broker is figuring out how to asynchornously call Web Services from a database trigger and I think it does an awesome job of doing that. Also while reading the <a href="http://www.amazon.com/gp/product/1590599993/ref=as_li_ss_tl?ie=UTF8&amp;tag=sermassblo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1590599993">Pro Service Broker book</a> I found out that it can do manage code notifications that can for example invalidate cache in your application layer.</p>

<h3 id="no-more-theory-lets-implement-asynchornous-triggers-calling-web-services">No more theory, let’s implement asynchornous triggers calling web services!</h3>

<p>Service Broker is a part of the Microsoft SQL Server and doesn’t need to be installed separately, just enabled. like this:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="n">name</span><span class="p">,</span> <span class="n">is_broker_enabled</span> <span class="k">FROM</span> <span class="n">sys</span><span class="p">.</span><span class="n">databases</span>
<span class="k">ALTER</span> <span class="k">DATABASE</span> <span class="p">[</span><span class="o">&lt;</span><span class="n">dbname</span><span class="o">&gt;</span><span class="p">]</span> <span class="k">SET</span> <span class="n">ENABLE_BROKER</span> <span class="k">WITH</span> <span class="k">ROLLBACK</span> <span class="k">IMMEDIATE</span><span class="p">;</span>
</code></pre></div></div>

<p>After we need to setup SQL Service Broker with needed objects.</p>

<p>Message types, these define types of messages being sent and received, we’ll use well formed xml, and for type you want a unique name a url is used by convention:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">MESSAGE</span> <span class="k">TYPE</span> <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">RequestMessage</span><span class="p">]</span>
<span class="n">VALIDATION</span> <span class="o">=</span> <span class="n">WELL_FORMED_XML</span>

<span class="k">CREATE</span> <span class="n">MESSAGE</span> <span class="k">TYPE</span> <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">ResponseMessage</span><span class="p">]</span>
    <span class="n">VALIDATION</span> <span class="o">=</span> <span class="n">WELL_FORMED_XML</span>
</code></pre></div></div>

<p>Contract defines how messages are being sent:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">CONTRACT</span> <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">ImportContract</span><span class="p">]</span>
<span class="p">(</span>
    <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">OrderImportRequestMessage</span><span class="p">]</span> <span class="n">SENT</span> <span class="k">BY</span> <span class="n">INITIATOR</span><span class="p">,</span>
    <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">OrderImportResponseMessage</span><span class="p">]</span> <span class="n">SENT</span> <span class="k">BY</span> <span class="n">TARGET</span>
<span class="p">)</span>
</code></pre></div></div>

<p>Now we will need two queues to hold our target messages (messages which will be processed by an activation program) and response messages for initiator which we will get as a response from activation program and processed by initiator).</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">QUEUE</span> <span class="n">InitiatorQueue</span>
<span class="k">WITH</span> <span class="n">STATUS</span> <span class="o">=</span> <span class="k">ON</span>

<span class="k">CREATE</span> <span class="n">QUEUE</span> <span class="n">TargetQueue</span>
</code></pre></div></div>

<p>Here I need to point out that in order for service broker to be reliable it uses a concept of dialogs basically once conversation dialog is open <strong>both sides will need to close conversations on their ends</strong>. It also happens that messages only get’s de-queued when the conversation end is received from another party. It will make more sense later.</p>

<p>Next, we will need to create a services, which is basically a service that routes messages, you will need to specify a contract defined earlier, like this:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">SERVICE</span> <span class="n">InitiatorService</span>
<span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">InitiatorQueue</span>
<span class="p">(</span>
    <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">Contract</span><span class="p">]</span>
<span class="p">)</span>

<span class="k">CREATE</span> <span class="n">SERVICE</span> <span class="n">TargetService</span>
<span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">TargetQueue</span>
<span class="p">(</span>
    <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">Contract</span><span class="p">]</span>
<span class="p">)</span>
</code></pre></div></div>

<p>Since we will be using external application activation we need to disable internal activation on the target queue. To enable external activation Service Broker send a message to the external activation queue when a message arrives at the target queue. This allows for centralizing all external queue notification. And as my co-worker <a href="http://fordevsbydevs.blogspot.com">Vincent</a> pointed out this external queue can be used across databases, so there will be one central external notification queue for for all databases.</p>

<p>Let’s create that notification queue</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">QUEUE</span> <span class="n">ExternalActivatorQueue</span>
</code></pre></div></div>

<p>Then we will also need a service for that queue, as you see it uses a generic contract provided by microsoft for event notifications:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">SERVICE</span> <span class="n">ExternalActivatorService</span>
<span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">ExternalActivatorQueue</span>
<span class="p">(</span>
    <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">schemas</span><span class="p">.</span><span class="n">microsoft</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="k">SQL</span><span class="o">/</span><span class="n">Notifications</span><span class="o">/</span><span class="n">PostEventNotification</span><span class="p">]</span>
<span class="p">)</span>
</code></pre></div></div>

<p>Finally we subscribe to the internal QUEUE_ACTIVATION event on our “TargetQueue”, so that we will receive notification in our ExternalActivationQueue when the TargetQueue gets messages.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="n">EVENT</span> <span class="n">NOTIFICATION</span> <span class="n">EventNotificationTargetQueue</span>
    <span class="k">ON</span> <span class="n">QUEUE</span> <span class="n">TargetQueue</span>
    <span class="k">FOR</span> <span class="n">QUEUE_ACTIVATION</span>
    <span class="k">TO</span> <span class="n">SERVICE</span> <span class="s1">'ExternalActivatorService'</span><span class="p">,</span> <span class="s1">'current database'</span><span class="p">;</span>
</code></pre></div></div>

<p>Here comes the time to create our SQL trigger which instead of doing a synchronous operation will quickly send a message to the queue for later instead of processing it. This is the concept of asynchronous triggers at work, we are firing and forgetting instead of waiting for response right away. The most important part is the <strong>SEND ON CONVERSATION @ch
MESSAGE TYPE <a href="@messageBody">http://blog.maskalik.com/RequestMessage</a>;</strong> this is where we send the message to the queue.
Creating a sample order table and a trigger which will send a message when a new order is inserted:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="k">TABLE</span> <span class="p">[</span><span class="k">Order</span><span class="p">]</span>
<span class="p">(</span>
    <span class="n">ID</span> <span class="n">UNIQUEIDENTIFIER</span> <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="n">Amount</span> <span class="n">MONEY</span> <span class="k">NOT</span> <span class="k">NULL</span>
<span class="p">)</span>

<span class="c1">-- Trigger will add a message into a ImportQueue</span>
<span class="k">CREATE</span> <span class="k">TRIGGER</span> <span class="n">OnOrderInserted</span> <span class="k">ON</span> <span class="p">[</span><span class="k">Order</span><span class="p">]</span> <span class="k">FOR</span> <span class="k">INSERT</span>
<span class="k">AS</span>
<span class="k">BEGIN</span>
    <span class="k">BEGIN</span> <span class="n">TRANSACTION</span><span class="p">;</span>
        <span class="k">DECLARE</span> <span class="o">@</span><span class="n">ch</span> <span class="n">UNIQUEIDENTIFIER</span>
        <span class="k">DECLARE</span> <span class="o">@</span><span class="n">messageBody</span> <span class="n">NVARCHAR</span><span class="p">(</span><span class="k">MAX</span><span class="p">);</span>

        <span class="k">BEGIN</span> <span class="n">DIALOG</span> <span class="n">CONVERSATION</span> <span class="o">@</span><span class="n">ch</span>
            <span class="k">FROM</span> <span class="n">SERVICE</span> <span class="p">[</span><span class="n">InitiatorService</span><span class="p">]</span>
            <span class="k">TO</span> <span class="n">SERVICE</span> <span class="s1">'TargetService'</span>
            <span class="k">ON</span> <span class="n">CONTRACT</span> <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">Contract</span><span class="p">]</span>
            <span class="k">WITH</span> <span class="n">ENCRYPTION</span> <span class="o">=</span> <span class="k">OFF</span><span class="p">;</span>

        <span class="c1">-- Construct the request message</span>
        <span class="k">SET</span> <span class="o">@</span><span class="n">messageBody</span> <span class="o">=</span> <span class="p">(</span><span class="k">SELECT</span> <span class="n">ID</span><span class="p">,</span> <span class="n">Amount</span> <span class="k">FROM</span> <span class="p">[</span><span class="k">Order</span><span class="p">]</span> <span class="k">FOR</span> <span class="n">XML</span> <span class="n">AUTO</span><span class="p">,</span> <span class="n">ELEMENTS</span><span class="p">);</span>

        <span class="c1">-- Send the message to the TargetService</span>
        <span class="p">;</span><span class="n">SEND</span> <span class="k">ON</span> <span class="n">CONVERSATION</span> <span class="o">@</span><span class="n">ch</span>
        <span class="n">MESSAGE</span> <span class="k">TYPE</span> <span class="p">[</span><span class="n">http</span><span class="p">:</span><span class="o">//</span><span class="n">blog</span><span class="p">.</span><span class="n">maskalik</span><span class="p">.</span><span class="n">com</span><span class="o">/</span><span class="n">RequestMessage</span><span class="p">]</span> <span class="p">(</span><span class="o">@</span><span class="n">messageBody</span><span class="p">);</span>
    <span class="k">COMMIT</span><span class="p">;</span>
<span class="k">END</span>
<span class="k">GO</span>
</code></pre></div></div>

<p>So now when we add an order the trigger will send a message which will see it in our TargetQueue and ExternalActivationQueue. Target queue will wait for someone to process and ExternalActivationQueue will wait until external activation program will read that message.</p>

<p><img src="/uploads/12-06/QueuesAfterInsert.png" alt="Results from queues" /></p>

<p>What do I mean by external activation program… Well that’s the program that listens to the Activation Queue and basically reads messages and starts predefined application for that queue. And when application starts it knows that it has to read it’s designated queue and process messages in it. Luckily Microsoft already create that <a href="http://blogs.msdn.com/b/sql_service_broker/archive/2008/11/21/announcing-service-broker-external-activator.aspx">external activation service application</a> and it is available <a href="http://www.microsoft.com/en-us/download/details.aspx?id=16978">here</a>, scroll down and you will see Microsoft® SQL Server® Service Broker External Activator for SQL Server® 2008 R2.</p>

<p>After you install the service, you will need to read documentation and edit the config file. It’s pretty trivial to do, you will need to specify your database name where activation queue is, your targetqueue name and which executable file to run when a message comes to the targetqueue. If you are having problems take a look at the error log, that helped me to get it up and running. Once you have configuration done, start the service and it will run if there are no configuration issues. Also keep in mind that service is only designed to work in integrated security mode.</p>

<p>But before you start the service we need to create an app that will process our messages and notify the queue that we have successfully processes so it can end the conversation and de-queue the message. Here are the highlights of that app:</p>

<p>It’s a console application with a main <code class="language-plaintext highlighter-rouge">while (true)</code> loop that uses ADO.NET to send Service Broker Command to RECEIVE message on the specified queue. It receives a message, but still keeps it on the queue until commit is called.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">...</span>
<span class="n">broker</span><span class="p">.</span><span class="n">tran</span> <span class="p">=</span> <span class="n">broker</span><span class="p">.</span><span class="n">cnn</span><span class="p">.</span><span class="nf">BeginTransaction</span><span class="p">();</span>
<span class="n">broker</span><span class="p">.</span><span class="nf">Receive</span><span class="p">(</span><span class="s">"TargetQueue"</span><span class="p">,</span> <span class="k">out</span> <span class="n">msgType</span><span class="p">,</span> <span class="k">out</span> <span class="n">msg</span><span class="p">,</span> <span class="k">out</span> <span class="n">serviceInstance</span><span class="p">,</span> <span class="k">out</span> <span class="n">dialogHandle</span><span class="p">);</span>

<span class="k">if</span> <span class="p">(</span><span class="n">msg</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">broker</span><span class="p">.</span><span class="n">tran</span><span class="p">.</span><span class="nf">Commit</span><span class="p">();</span>
    <span class="k">break</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">switch</span> <span class="p">(</span><span class="n">msgType</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">case</span> <span class="s">"http://blog.maskalik.com/RequestMessage"</span><span class="p">:</span>
    <span class="p">{</span>
        <span class="c1">//right here we call a web service or whatever processing you do</span>
        <span class="c1">//also use T-SQL to parse @msg from the queue to get data</span>
        <span class="n">broker</span><span class="p">.</span><span class="nf">Send</span><span class="p">(</span><span class="n">dialogHandle</span><span class="p">,</span> <span class="s">"&lt;Response&gt;&lt;OrderId&gt;1&lt;/OrderId&gt;&lt;Status&gt;Processed&lt;/Status&gt;&lt;/Response&gt;"</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">case</span> <span class="s">"http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog"</span><span class="p">:</span>
    <span class="p">{</span>
            <span class="n">broker</span><span class="p">.</span><span class="nf">EndDialog</span><span class="p">(</span><span class="n">dialogHandle</span><span class="p">);</span>
            <span class="k">break</span><span class="p">;</span>
    <span class="p">}</span>
<span class="p">}</span>

<span class="n">broker</span><span class="p">.</span><span class="n">tran</span><span class="p">.</span><span class="nf">Commit</span><span class="p">();</span>
<span class="p">...</span>
</code></pre></div></div>

<p>Basically the transaction only gets committed when we process message and that deletes a message of the queue hence the reliability of the message processing. Also remember it is important to end conversations on both ends.</p>

<p>When reply is sent from an external .NET application we need to process it inside the SQL Server. For this we will use an internally activated service which will call a stored procedure which will simply take that message, parse xml and insert it into a table.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">CREATE</span> <span class="k">PROCEDURE</span> <span class="n">ProcessResponseMessages</span>
<span class="k">AS</span>
<span class="k">BEGIN</span>
    <span class="k">DECLARE</span> <span class="o">@</span><span class="n">ch</span> <span class="n">UNIQUEIDENTIFIER</span><span class="p">;</span>
    <span class="k">DECLARE</span> <span class="o">@</span><span class="n">messagetypename</span> <span class="n">NVARCHAR</span><span class="p">(</span><span class="mi">256</span><span class="p">);</span>
    <span class="k">DECLARE</span>	<span class="o">@</span><span class="n">messagebody</span> <span class="n">XML</span><span class="p">;</span>
    <span class="k">DECLARE</span> <span class="o">@</span><span class="n">responsemessage</span> <span class="n">XML</span><span class="p">;</span>

    <span class="n">WHILE</span> <span class="p">(</span><span class="mi">1</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
    <span class="k">BEGIN</span>
        <span class="k">BEGIN</span> <span class="n">TRANSACTION</span>

        <span class="n">WAITFOR</span> <span class="p">(</span>
            <span class="n">RECEIVE</span> <span class="n">TOP</span><span class="p">(</span><span class="mi">1</span><span class="p">)</span>
                <span class="o">@</span><span class="n">ch</span> <span class="o">=</span> <span class="n">conversation_handle</span><span class="p">,</span>
                <span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="n">message_type_name</span><span class="p">,</span>
                <span class="o">@</span><span class="n">messagebody</span> <span class="o">=</span> <span class="k">CAST</span><span class="p">(</span><span class="n">message_body</span> <span class="k">AS</span> <span class="n">XML</span><span class="p">)</span>
            <span class="k">FROM</span>
                <span class="n">InitiatorQueue</span>
        <span class="p">),</span> <span class="n">TIMEOUT</span> <span class="mi">1000</span>

        <span class="n">IF</span> <span class="p">(</span><span class="o">@@</span><span class="n">ROWCOUNT</span> <span class="o">=</span> <span class="mi">0</span><span class="p">)</span>
        <span class="k">BEGIN</span>
            <span class="k">ROLLBACK</span> <span class="n">TRANSACTION</span>
            <span class="n">BREAK</span>
        <span class="k">END</span>

        <span class="n">IF</span> <span class="p">(</span><span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="s1">'http://blog.maskalik.com/ResponseMessage'</span><span class="p">)</span>
        <span class="k">BEGIN</span>
            <span class="k">INSERT</span> <span class="k">INTO</span> <span class="n">ProcessedOrders</span> <span class="p">(</span><span class="n">ID</span><span class="p">,</span> <span class="n">SentTime</span><span class="p">)</span> <span class="k">VALUES</span>
            <span class="p">(</span>
                <span class="o">@</span><span class="n">messagebody</span><span class="p">.</span><span class="n">value</span><span class="p">(</span><span class="s1">'/Response/OrderId[1]'</span><span class="p">,</span> <span class="s1">'INT'</span><span class="p">),</span>
                <span class="n">GETDATE</span><span class="p">()</span>
            <span class="p">)</span>
        <span class="k">END</span>

        <span class="n">IF</span> <span class="p">(</span><span class="o">@</span><span class="n">messagetypename</span> <span class="o">=</span> <span class="s1">'http://schemas.microsoft.com/SQL/ServiceBroker/EndDialog'</span><span class="p">)</span>
        <span class="k">BEGIN</span>
            <span class="c1">-- End the conversation</span>
            <span class="k">END</span> <span class="n">CONVERSATION</span> <span class="o">@</span><span class="n">ch</span><span class="p">;</span>
        <span class="k">END</span>

        <span class="k">COMMIT</span> <span class="n">TRANSACTION</span>
    <span class="k">END</span>
<span class="k">END</span>
<span class="k">GO</span>
</code></pre></div></div>

<p>Finally we alter our InitiatorQueue to turn on internal activation with provided stored procedure.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">ALTER</span> <span class="n">QUEUE</span> <span class="n">InitiatorQueue</span>
<span class="k">WITH</span> <span class="n">ACTIVATION</span>
<span class="p">(</span>
    <span class="n">PROCEDURE_NAME</span> <span class="o">=</span> <span class="n">ProcessResponseMessages</span><span class="p">,</span>
    <span class="n">STATUS</span> <span class="o">=</span> <span class="k">ON</span><span class="p">,</span>
    <span class="n">MAX_QUEUE_READERS</span> <span class="o">=</span> <span class="mi">1</span><span class="p">,</span>
    <span class="k">EXECUTE</span> <span class="k">AS</span> <span class="k">OWNER</span>
<span class="p">)</span>
</code></pre></div></div>

<h3 id="final-words">Final words</h3>

<p>It seems like a lot of configuration and setup, and it is. However what you do get is offloading of processing of your message outside of SQL Server which can call something like Web Services. You will also get reliability and scalability that service broker offers. And you don’t have to deploy assemblies into SQL and there is many other things you can do like paralel processeing, conversetion group locking and a ton of other things that you will need to read for yourself in <a href="http://www.amazon.com/gp/product/1590599993/ref=as_li_ss_tl?ie=UTF8&amp;tag=sermassblo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=390957&amp;creativeASIN=1590599993">Pro SQL Service Broker 2008 book</a>. Good luck!</p>


										
					<p>Posted in: sql-server-service-broker</p>
						
				
					<p>Tagged with: asynchronous, trigger, sql-server, web-services, and service-broker</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/sql-server-service-broker/scalable-webservice-calls-from-database/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/sql-server-service-broker/scalable-webservice-calls-from-database/]]></guid>
		<pubDate>2012-06-25T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[What it means to be a good developer...]]></title>
		<description>
			<![CDATA[
				<p>Software development has definitely seen an exponential growth in the past decade. And along with that came an immense demand for good developers. With only few industries that are hiring today it’s not uncommon to meet with a developer candidate at an interview who has a wonderful resume, but when you ask them to write a simple algorithm or even a nested for loop they really have a hard time. While I believe it’s the best job ever, it’s not for everyone. With this post I’d like to spell out what it means to be a good developer.</p>

<h3 id="good-developer">Good developer</h3>
<p>But what do I mean by that illusive term “good developer”. Aren’t all programmers who know how to write code good? Well, absolutely not. I think an average computer science student with a descent understanding of concepts can write code but that does not make him a good developer.</p>

<blockquote>
  <p>Any fool can write code that a
computer can understand. Good
programmers write code that humans can
understand.
-Martin Fowler et al, Refactoring: Improving the Design of Existing Code,
1999</p>
</blockquote>

<p>There is a lot of meaning in that simple phrase and a lot of learning that is required in order to make code human readable. I think first thing is a real understanding and practice of object oriented principles. I’m not talking about creating instances of the classes or calling methods on object but the object oriented design principles that were introduced to break down the complexity of the  business domain. Concepts like <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">single responsibly principle</a> , <a href="http://en.wikipedia.org/wiki/Open/closed_principle">open/closed principle</a>, low <a href="http://en.wikipedia.org/wiki/Coupling_(computer_programming)">coupling</a> and high cohesion and etc. should be a second nature to a good developer. In addition knowing and practicing concepts like Test Driven Development (<a href="http://www.amazon.com/gp/product/0321146530/ref=as_li_qf_sp_asin_tl?ie=UTF8&amp;tag=sermassblo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321146530">TDD</a>) and Domain Driven Design (<a href="http://www.amazon.com/gp/product/0321125215/ref=as_li_tf_tl?ie=UTF8&amp;tag=sermassblo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321125215">DDD</a>) will help you transition from an average developer into a good developer. Another very important skill every good developer knows is how to take a spaghetti code and make it better, that concept is called <a href="http://www.amazon.com/gp/product/0201485672?ie=UTF8&amp;tag=sermassblo-20&amp;linkCode=xm2&amp;camp=1789&amp;creativeASIN=0201485672">refactoring</a> and a big part of being developer is maintaining existing code which will most likely was written by an average developer. I think learning and becoming good at the concepts above alone would take a significant amount of time probably few years and a lot of reading of fundamental books. That brings us to next topic, continuous learning.</p>

<h3 id="learning">Learning</h3>

<p>To be a good developer is to love learning. In fact continuous learning is what makes a developer better as time goes on. A lot of average developers don’t read books and don’t become better at their craft. I think it’s like that with many other professions. For example, I’m sure you don’t want to go to mediocre dentist because if he messes up it will cause an infection or some other problem down the line, so I’m sure you want to go the good dentist who is a master of his craft. Once a good developer has a grasp of design principles his learning doesn’t stop there, there is always going to be new frameworks new technologies other design principles, different programming language and he or she will need to take time to constantly learn them. So if you felt like college was too much learning then this career is not for you because it you will be constantly learning for the rest of your life.</p>

<h3 id="passion">Passion</h3>

<p>Just like with anything else if you love what you do then you will get good at it. If it’s just another job then there is no way you are going to go home and read a book on the weekend, write a blog post, experiment with the new and shiny technology or build a project.</p>

<blockquote>
  <p>Your work is going to fill a large
part of your life, and the only way to
be truly satisfied is to do what you
believe is great work. And the only
way to do great work is to love what
you do.you do…</p>

  <p>Your time is limited, so don’t waste it living someone else’s life. Don’t be trapped by dogma — which is living with the results of other people’s thinking. Don’t let the noise of others’ opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. They somehow already know what you truly want to become. Everything else is secondary.” 
-Steve Jobs</p>
</blockquote>

<p>Why waste your time and be mediocre at something when you can live a fulfilling life and be the best you can be.</p>

<h3 id="learn-from-others-and-pass-your-knowledge">Learn from others and pass your knowledge</h3>

<p>I strongly believe that a good developer must have a twitter account, follow other developers and learn what others like you are working on. Once you have something good to share do so. I think building up your circle will get your more exposure and keep you up to the latest and greatest things that are happening. But also don’t let twitter destruct you and unfollow those that you think add noise to your stream. You can start by picking developers from my <a href="https://twitter.com/#!/mercury2269/following">followers list</a>.</p>

<p>Next on the list is a <a href="http://stackoverflow.com/">stackoverflow</a> account. You will come across a problem that you cannot find an answer for sooner or later, and you can learn from others. As a bonus try answering other people’s questions.</p>

<p>Start writing a blog. I wish I started much earlier but it’s better late than never. When you are developing you always come up with some clever solutions to the problem or something that took you long time to figure out. If you take some time and share it, you can use it as your diary and when you forgot something, you can look it up from your own blog and other developers will appreciate it. I believe  if you give something you will get it back in return.</p>

<p>Get a github account and follow great developers/project, learn from code they have written. It’s a wealth of knowledge for free.</p>

<p>Get a google reader, subscribe to developer blogs and read interesting articles once in a while.</p>

<p>Watch videos from conferences sometimes they have gems like a recent talk from <a href="http://channel9.msdn.com/Events/TechDays/Techdays-2012-the-Netherlands/2159">Steven Sanderson on single page applications</a></p>

<p>Start your own project that uses latest exciting technology. As for me, right now I’m working on exciting single page application project that uses knockoutjs and ASP.NET Web API. I’m very excited about working with latest and learning new frameworks.</p>

<h3 id="finally">Finally</h3>
<p>If you do all of the above while working your regular programming job you will no doubt become a good developer and be on the road to greatness!  And remember it’s not the destination it’s the journey, and you gotta love the journey that’s all it matters :)</p>

<p>So do you still want to be a developer? Did I miss something, please let me know your thoughts.</p>


				<p>Software development has definitely seen an exponential growth in the past decade. And along with that came an immense demand for good developers. With only few industries that are hiring today it’s not uncommon to meet with a developer candidate at an interview who has a wonderful resume, but when you ask them to write a simple algorithm or even a nested for loop they really have a hard time. While I believe it’s the best job ever, it’s not for everyone. With this post I’d like to spell out what it means to be a good developer.</p>

<h3 id="good-developer">Good developer</h3>
<p>But what do I mean by that illusive term “good developer”. Aren’t all programmers who know how to write code good? Well, absolutely not. I think an average computer science student with a descent understanding of concepts can write code but that does not make him a good developer.</p>

<blockquote>
  <p>Any fool can write code that a
computer can understand. Good
programmers write code that humans can
understand.
-Martin Fowler et al, Refactoring: Improving the Design of Existing Code,
1999</p>
</blockquote>

<p>There is a lot of meaning in that simple phrase and a lot of learning that is required in order to make code human readable. I think first thing is a real understanding and practice of object oriented principles. I’m not talking about creating instances of the classes or calling methods on object but the object oriented design principles that were introduced to break down the complexity of the  business domain. Concepts like <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">single responsibly principle</a> , <a href="http://en.wikipedia.org/wiki/Open/closed_principle">open/closed principle</a>, low <a href="http://en.wikipedia.org/wiki/Coupling_(computer_programming)">coupling</a> and high cohesion and etc. should be a second nature to a good developer. In addition knowing and practicing concepts like Test Driven Development (<a href="http://www.amazon.com/gp/product/0321146530/ref=as_li_qf_sp_asin_tl?ie=UTF8&amp;tag=sermassblo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321146530">TDD</a>) and Domain Driven Design (<a href="http://www.amazon.com/gp/product/0321125215/ref=as_li_tf_tl?ie=UTF8&amp;tag=sermassblo-20&amp;linkCode=as2&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0321125215">DDD</a>) will help you transition from an average developer into a good developer. Another very important skill every good developer knows is how to take a spaghetti code and make it better, that concept is called <a href="http://www.amazon.com/gp/product/0201485672?ie=UTF8&amp;tag=sermassblo-20&amp;linkCode=xm2&amp;camp=1789&amp;creativeASIN=0201485672">refactoring</a> and a big part of being developer is maintaining existing code which will most likely was written by an average developer. I think learning and becoming good at the concepts above alone would take a significant amount of time probably few years and a lot of reading of fundamental books. That brings us to next topic, continuous learning.</p>

<h3 id="learning">Learning</h3>

<p>To be a good developer is to love learning. In fact continuous learning is what makes a developer better as time goes on. A lot of average developers don’t read books and don’t become better at their craft. I think it’s like that with many other professions. For example, I’m sure you don’t want to go to mediocre dentist because if he messes up it will cause an infection or some other problem down the line, so I’m sure you want to go the good dentist who is a master of his craft. Once a good developer has a grasp of design principles his learning doesn’t stop there, there is always going to be new frameworks new technologies other design principles, different programming language and he or she will need to take time to constantly learn them. So if you felt like college was too much learning then this career is not for you because it you will be constantly learning for the rest of your life.</p>

<h3 id="passion">Passion</h3>

<p>Just like with anything else if you love what you do then you will get good at it. If it’s just another job then there is no way you are going to go home and read a book on the weekend, write a blog post, experiment with the new and shiny technology or build a project.</p>

<blockquote>
  <p>Your work is going to fill a large
part of your life, and the only way to
be truly satisfied is to do what you
believe is great work. And the only
way to do great work is to love what
you do.you do…</p>

  <p>Your time is limited, so don’t waste it living someone else’s life. Don’t be trapped by dogma — which is living with the results of other people’s thinking. Don’t let the noise of others’ opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. They somehow already know what you truly want to become. Everything else is secondary.” 
-Steve Jobs</p>
</blockquote>

<p>Why waste your time and be mediocre at something when you can live a fulfilling life and be the best you can be.</p>

<h3 id="learn-from-others-and-pass-your-knowledge">Learn from others and pass your knowledge</h3>

<p>I strongly believe that a good developer must have a twitter account, follow other developers and learn what others like you are working on. Once you have something good to share do so. I think building up your circle will get your more exposure and keep you up to the latest and greatest things that are happening. But also don’t let twitter destruct you and unfollow those that you think add noise to your stream. You can start by picking developers from my <a href="https://twitter.com/#!/mercury2269/following">followers list</a>.</p>

<p>Next on the list is a <a href="http://stackoverflow.com/">stackoverflow</a> account. You will come across a problem that you cannot find an answer for sooner or later, and you can learn from others. As a bonus try answering other people’s questions.</p>

<p>Start writing a blog. I wish I started much earlier but it’s better late than never. When you are developing you always come up with some clever solutions to the problem or something that took you long time to figure out. If you take some time and share it, you can use it as your diary and when you forgot something, you can look it up from your own blog and other developers will appreciate it. I believe  if you give something you will get it back in return.</p>

<p>Get a github account and follow great developers/project, learn from code they have written. It’s a wealth of knowledge for free.</p>

<p>Get a google reader, subscribe to developer blogs and read interesting articles once in a while.</p>

<p>Watch videos from conferences sometimes they have gems like a recent talk from <a href="http://channel9.msdn.com/Events/TechDays/Techdays-2012-the-Netherlands/2159">Steven Sanderson on single page applications</a></p>

<p>Start your own project that uses latest exciting technology. As for me, right now I’m working on exciting single page application project that uses knockoutjs and ASP.NET Web API. I’m very excited about working with latest and learning new frameworks.</p>

<h3 id="finally">Finally</h3>
<p>If you do all of the above while working your regular programming job you will no doubt become a good developer and be on the road to greatness!  And remember it’s not the destination it’s the journey, and you gotta love the journey that’s all it matters :)</p>

<p>So do you still want to be a developer? Did I miss something, please let me know your thoughts.</p>


						
				
					<p>Tagged with: thoughts</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/part-of-being-a-good-developer/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/part-of-being-a-good-developer/]]></guid>
		<pubDate>2012-04-26T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[JSON.NET Implementing Custom Serialization]]></title>
		<description>
			<![CDATA[
				<p>JSON.NET is a great library for serializing objects to and from json strings. In case you need to have a more control of how your object is being serialized this post covers creation of custom json converter. For instance, I came across a scenario where a json result had to have a property name starting with a $(dollar sign) like “$and” and as you may guess properties in .NET cannot start with a dollar sign. So that’s where we would need a custom json converter.</p>

<h3 id="setup">Setup</h3>

<p>First thing you need to do is to create a custom class the derives from JsonConverter, and override 3 methods. In the CanConvert method we check if the passed in type can be assigned to our target type WeirdName.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">WeirdNameSerializer</span> <span class="p">:</span> <span class="n">JsonConverter</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">WriteJson</span><span class="p">(</span><span class="n">JsonWriter</span> <span class="n">writer</span><span class="p">,</span> <span class="kt">object</span> <span class="k">value</span><span class="p">,</span> <span class="n">JsonSerializer</span> <span class="n">serializer</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nf">NotImplementedException</span><span class="p">();</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">override</span> <span class="kt">object</span> <span class="nf">ReadJson</span><span class="p">(</span><span class="n">JsonReader</span> <span class="n">reader</span><span class="p">,</span> <span class="n">Type</span> <span class="n">objectType</span><span class="p">,</span> <span class="kt">object</span> <span class="n">existingValue</span><span class="p">,</span> <span class="n">JsonSerializer</span> <span class="n">serializer</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nf">NotImplementedException</span><span class="p">();</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">override</span> <span class="kt">bool</span> <span class="nf">CanConvert</span><span class="p">(</span><span class="n">Type</span> <span class="n">objectType</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="k">typeof</span><span class="p">(</span><span class="n">WeirdName</span><span class="p">).</span><span class="nf">IsAssignableFrom</span><span class="p">(</span><span class="n">objectType</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Next is you need to decorate your class which will be serialized with the attribute of a newly created type</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="nf">JsonConverter</span><span class="p">(</span><span class="k">typeof</span><span class="p">(</span><span class="n">WeirdNameSerializer</span><span class="p">))]</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">WeirdName</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">Name</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">Value</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="custom-writing">Custom Writing</h3>

<p>Now in your WriteJson method we will cast the value object to your serilized class so we can access properties and do our custom serialization on them.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">WriteJson</span><span class="p">(</span><span class="n">JsonWriter</span> <span class="n">writer</span><span class="p">,</span> <span class="kt">object</span> <span class="k">value</span><span class="p">,</span> <span class="n">JsonSerializer</span> <span class="n">serializer</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">var</span> <span class="n">name</span> <span class="p">=</span> <span class="k">value</span> <span class="k">as</span> <span class="n">WeirdName</span><span class="p">;</span>
    <span class="n">writer</span><span class="p">.</span><span class="nf">WriteStartObject</span><span class="p">();</span>
    <span class="n">writer</span><span class="p">.</span><span class="nf">WritePropertyName</span><span class="p">(</span><span class="s">"$"</span> <span class="p">+</span> <span class="n">name</span><span class="p">.</span><span class="n">Name</span><span class="p">);</span>
    <span class="n">serializer</span><span class="p">.</span><span class="nf">Serialize</span><span class="p">(</span><span class="n">writer</span><span class="p">,</span> <span class="n">name</span><span class="p">.</span><span class="n">Value</span><span class="p">);</span>
    <span class="n">writer</span><span class="p">.</span><span class="nf">WriteEndObject</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>You can also nest objects within other objects</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">name</span> <span class="p">=</span> <span class="k">value</span> <span class="k">as</span> <span class="n">WeirdName</span><span class="p">;</span>
<span class="n">writer</span><span class="p">.</span><span class="nf">WriteStartObject</span><span class="p">();</span>
<span class="n">writer</span><span class="p">.</span><span class="nf">WritePropertyName</span><span class="p">(</span><span class="s">"$"</span> <span class="p">+</span> <span class="n">name</span><span class="p">.</span><span class="n">Name</span><span class="p">);</span>
<span class="n">writer</span><span class="p">.</span><span class="nf">WriteStartObject</span><span class="p">();</span>
<span class="n">writer</span><span class="p">.</span><span class="nf">WritePropertyName</span><span class="p">(</span><span class="s">"nested"</span><span class="p">);</span>
<span class="n">serializer</span><span class="p">.</span><span class="nf">Serialize</span><span class="p">(</span><span class="n">writer</span><span class="p">,</span> <span class="n">name</span><span class="p">.</span><span class="n">Value</span><span class="p">);</span>
<span class="n">writer</span><span class="p">.</span><span class="nf">WriteEndObject</span><span class="p">();</span>
<span class="n">writer</span><span class="p">.</span><span class="nf">WriteEndObject</span><span class="p">();</span>
</code></pre></div></div>

<h3 id="custom-reading">Custom Reading</h3>

<p>First thing is you need to load the json reader into a JObject. Then you can access fields if you know the key of the property with jsonObject[“fieldName”]. If the schema is the same you can use</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">name</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">WeirdName</span><span class="p">();</span>
<span class="n">serializer</span><span class="p">.</span><span class="nf">Populate</span><span class="p">(</span><span class="n">jObject</span><span class="p">.</span><span class="nf">CreateReader</span><span class="p">(),</span> <span class="n">name</span><span class="p">);</span>
</code></pre></div></div>

<p>to populate properties automatically. However in our case our property name is not standard so we’ll have to manually get it from list of properties.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">override</span> <span class="kt">object</span> <span class="nf">ReadJson</span><span class="p">(</span><span class="n">JsonReader</span> <span class="n">reader</span><span class="p">,</span> <span class="n">Type</span> <span class="n">objectType</span><span class="p">,</span>
<span class="kt">object</span> <span class="n">existingValue</span><span class="p">,</span> <span class="n">JsonSerializer</span> <span class="n">serializer</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">JObject</span> <span class="n">jsonObject</span> <span class="p">=</span> <span class="n">JObject</span><span class="p">.</span><span class="nf">Load</span><span class="p">(</span><span class="n">reader</span><span class="p">);</span>
    <span class="kt">var</span> <span class="n">properties</span> <span class="p">=</span> <span class="n">jsonObject</span><span class="p">.</span><span class="nf">Properties</span><span class="p">().</span><span class="nf">ToList</span><span class="p">();</span>
    <span class="k">return</span> <span class="k">new</span> <span class="n">WeirdName</span> <span class="p">{</span>
                            <span class="n">Name</span> <span class="p">=</span> <span class="n">properties</span><span class="p">[</span><span class="m">0</span><span class="p">].</span><span class="n">Name</span><span class="p">.</span><span class="nf">Replace</span><span class="p">(</span><span class="s">"$"</span><span class="p">,</span><span class="s">""</span><span class="p">),</span>
                            <span class="n">Value</span> <span class="p">=</span> <span class="p">(</span><span class="kt">string</span><span class="p">)</span><span class="n">properties</span><span class="p">[</span><span class="m">0</span><span class="p">].</span><span class="n">Value</span>
                            <span class="p">};</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="testing-our-custom-serializer">Testing our custom serializer</h3>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Arrange</span>
<span class="kt">var</span> <span class="n">weird</span> <span class="p">=</span> <span class="k">new</span> <span class="n">WeirdName</span> <span class="p">{</span><span class="n">Name</span> <span class="p">=</span> <span class="s">"first"</span><span class="p">,</span> <span class="n">Value</span> <span class="p">=</span> <span class="s">"Sergey"</span><span class="p">};</span>

<span class="c1">// Act</span>
<span class="c1">// weird gets serialized into "{\"$first\":\"Sergey\"}"</span>
<span class="kt">var</span> <span class="n">result</span> <span class="p">=</span> <span class="n">JsonConvert</span><span class="p">.</span><span class="nf">SerializeObject</span><span class="p">(</span><span class="n">weird</span><span class="p">);</span>

<span class="kt">var</span> <span class="n">test</span> <span class="p">=</span> <span class="n">JsonConvert</span><span class="p">.</span><span class="n">DeserializeObject</span><span class="p">&lt;</span><span class="n">WeirdName</span><span class="p">&gt;(</span><span class="n">result</span><span class="p">);</span>

<span class="c1">// Assert</span>
<span class="n">Assert</span><span class="p">.</span><span class="nf">AreEqual</span><span class="p">(</span><span class="n">weird</span><span class="p">.</span><span class="n">Name</span><span class="p">,</span><span class="n">test</span><span class="p">.</span><span class="n">Name</span><span class="p">);</span>
<span class="n">Assert</span><span class="p">.</span><span class="nf">AreEqual</span><span class="p">(</span><span class="n">weird</span><span class="p">.</span><span class="n">Value</span><span class="p">,</span><span class="n">test</span><span class="p">.</span><span class="n">Value</span><span class="p">);</span>
</code></pre></div></div>

<p>And that’s it, now you should have an idea of how to implement custom json serializers. Please post if you have any questions.</p>

				<p>JSON.NET is a great library for serializing objects to and from json strings. In case you need to have a more control of how your object is being serialized this post covers creation of custom json converter. For instance, I came across a scenario where a json result had to have a property name starting with a $(dollar sign) like “$and” and as you may guess properties in .NET cannot start with a dollar sign. So that’s where we would need a custom json converter.</p>

<h3 id="setup">Setup</h3>

<p>First thing you need to do is to create a custom class the derives from JsonConverter, and override 3 methods. In the CanConvert method we check if the passed in type can be assigned to our target type WeirdName.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">WeirdNameSerializer</span> <span class="p">:</span> <span class="n">JsonConverter</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">WriteJson</span><span class="p">(</span><span class="n">JsonWriter</span> <span class="n">writer</span><span class="p">,</span> <span class="kt">object</span> <span class="k">value</span><span class="p">,</span> <span class="n">JsonSerializer</span> <span class="n">serializer</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nf">NotImplementedException</span><span class="p">();</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">override</span> <span class="kt">object</span> <span class="nf">ReadJson</span><span class="p">(</span><span class="n">JsonReader</span> <span class="n">reader</span><span class="p">,</span> <span class="n">Type</span> <span class="n">objectType</span><span class="p">,</span> <span class="kt">object</span> <span class="n">existingValue</span><span class="p">,</span> <span class="n">JsonSerializer</span> <span class="n">serializer</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nf">NotImplementedException</span><span class="p">();</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">override</span> <span class="kt">bool</span> <span class="nf">CanConvert</span><span class="p">(</span><span class="n">Type</span> <span class="n">objectType</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">return</span> <span class="k">typeof</span><span class="p">(</span><span class="n">WeirdName</span><span class="p">).</span><span class="nf">IsAssignableFrom</span><span class="p">(</span><span class="n">objectType</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Next is you need to decorate your class which will be serialized with the attribute of a newly created type</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">[</span><span class="nf">JsonConverter</span><span class="p">(</span><span class="k">typeof</span><span class="p">(</span><span class="n">WeirdNameSerializer</span><span class="p">))]</span>
<span class="k">public</span> <span class="k">class</span> <span class="nc">WeirdName</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">Name</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">Value</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="custom-writing">Custom Writing</h3>

<p>Now in your WriteJson method we will cast the value object to your serilized class so we can access properties and do our custom serialization on them.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">WriteJson</span><span class="p">(</span><span class="n">JsonWriter</span> <span class="n">writer</span><span class="p">,</span> <span class="kt">object</span> <span class="k">value</span><span class="p">,</span> <span class="n">JsonSerializer</span> <span class="n">serializer</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">var</span> <span class="n">name</span> <span class="p">=</span> <span class="k">value</span> <span class="k">as</span> <span class="n">WeirdName</span><span class="p">;</span>
    <span class="n">writer</span><span class="p">.</span><span class="nf">WriteStartObject</span><span class="p">();</span>
    <span class="n">writer</span><span class="p">.</span><span class="nf">WritePropertyName</span><span class="p">(</span><span class="s">"$"</span> <span class="p">+</span> <span class="n">name</span><span class="p">.</span><span class="n">Name</span><span class="p">);</span>
    <span class="n">serializer</span><span class="p">.</span><span class="nf">Serialize</span><span class="p">(</span><span class="n">writer</span><span class="p">,</span> <span class="n">name</span><span class="p">.</span><span class="n">Value</span><span class="p">);</span>
    <span class="n">writer</span><span class="p">.</span><span class="nf">WriteEndObject</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>You can also nest objects within other objects</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">name</span> <span class="p">=</span> <span class="k">value</span> <span class="k">as</span> <span class="n">WeirdName</span><span class="p">;</span>
<span class="n">writer</span><span class="p">.</span><span class="nf">WriteStartObject</span><span class="p">();</span>
<span class="n">writer</span><span class="p">.</span><span class="nf">WritePropertyName</span><span class="p">(</span><span class="s">"$"</span> <span class="p">+</span> <span class="n">name</span><span class="p">.</span><span class="n">Name</span><span class="p">);</span>
<span class="n">writer</span><span class="p">.</span><span class="nf">WriteStartObject</span><span class="p">();</span>
<span class="n">writer</span><span class="p">.</span><span class="nf">WritePropertyName</span><span class="p">(</span><span class="s">"nested"</span><span class="p">);</span>
<span class="n">serializer</span><span class="p">.</span><span class="nf">Serialize</span><span class="p">(</span><span class="n">writer</span><span class="p">,</span> <span class="n">name</span><span class="p">.</span><span class="n">Value</span><span class="p">);</span>
<span class="n">writer</span><span class="p">.</span><span class="nf">WriteEndObject</span><span class="p">();</span>
<span class="n">writer</span><span class="p">.</span><span class="nf">WriteEndObject</span><span class="p">();</span>
</code></pre></div></div>

<h3 id="custom-reading">Custom Reading</h3>

<p>First thing is you need to load the json reader into a JObject. Then you can access fields if you know the key of the property with jsonObject[“fieldName”]. If the schema is the same you can use</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">name</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">WeirdName</span><span class="p">();</span>
<span class="n">serializer</span><span class="p">.</span><span class="nf">Populate</span><span class="p">(</span><span class="n">jObject</span><span class="p">.</span><span class="nf">CreateReader</span><span class="p">(),</span> <span class="n">name</span><span class="p">);</span>
</code></pre></div></div>

<p>to populate properties automatically. However in our case our property name is not standard so we’ll have to manually get it from list of properties.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">override</span> <span class="kt">object</span> <span class="nf">ReadJson</span><span class="p">(</span><span class="n">JsonReader</span> <span class="n">reader</span><span class="p">,</span> <span class="n">Type</span> <span class="n">objectType</span><span class="p">,</span>
<span class="kt">object</span> <span class="n">existingValue</span><span class="p">,</span> <span class="n">JsonSerializer</span> <span class="n">serializer</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">JObject</span> <span class="n">jsonObject</span> <span class="p">=</span> <span class="n">JObject</span><span class="p">.</span><span class="nf">Load</span><span class="p">(</span><span class="n">reader</span><span class="p">);</span>
    <span class="kt">var</span> <span class="n">properties</span> <span class="p">=</span> <span class="n">jsonObject</span><span class="p">.</span><span class="nf">Properties</span><span class="p">().</span><span class="nf">ToList</span><span class="p">();</span>
    <span class="k">return</span> <span class="k">new</span> <span class="n">WeirdName</span> <span class="p">{</span>
                            <span class="n">Name</span> <span class="p">=</span> <span class="n">properties</span><span class="p">[</span><span class="m">0</span><span class="p">].</span><span class="n">Name</span><span class="p">.</span><span class="nf">Replace</span><span class="p">(</span><span class="s">"$"</span><span class="p">,</span><span class="s">""</span><span class="p">),</span>
                            <span class="n">Value</span> <span class="p">=</span> <span class="p">(</span><span class="kt">string</span><span class="p">)</span><span class="n">properties</span><span class="p">[</span><span class="m">0</span><span class="p">].</span><span class="n">Value</span>
                            <span class="p">};</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="testing-our-custom-serializer">Testing our custom serializer</h3>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Arrange</span>
<span class="kt">var</span> <span class="n">weird</span> <span class="p">=</span> <span class="k">new</span> <span class="n">WeirdName</span> <span class="p">{</span><span class="n">Name</span> <span class="p">=</span> <span class="s">"first"</span><span class="p">,</span> <span class="n">Value</span> <span class="p">=</span> <span class="s">"Sergey"</span><span class="p">};</span>

<span class="c1">// Act</span>
<span class="c1">// weird gets serialized into "{\"$first\":\"Sergey\"}"</span>
<span class="kt">var</span> <span class="n">result</span> <span class="p">=</span> <span class="n">JsonConvert</span><span class="p">.</span><span class="nf">SerializeObject</span><span class="p">(</span><span class="n">weird</span><span class="p">);</span>

<span class="kt">var</span> <span class="n">test</span> <span class="p">=</span> <span class="n">JsonConvert</span><span class="p">.</span><span class="n">DeserializeObject</span><span class="p">&lt;</span><span class="n">WeirdName</span><span class="p">&gt;(</span><span class="n">result</span><span class="p">);</span>

<span class="c1">// Assert</span>
<span class="n">Assert</span><span class="p">.</span><span class="nf">AreEqual</span><span class="p">(</span><span class="n">weird</span><span class="p">.</span><span class="n">Name</span><span class="p">,</span><span class="n">test</span><span class="p">.</span><span class="n">Name</span><span class="p">);</span>
<span class="n">Assert</span><span class="p">.</span><span class="nf">AreEqual</span><span class="p">(</span><span class="n">weird</span><span class="p">.</span><span class="n">Value</span><span class="p">,</span><span class="n">test</span><span class="p">.</span><span class="n">Value</span><span class="p">);</span>
</code></pre></div></div>

<p>And that’s it, now you should have an idea of how to implement custom json serializers. Please post if you have any questions.</p>

										
					<p>Posted in: asp.net</p>
						
				
					<p>Tagged with: asp.net, json.net, and serialization</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/asp-net/json-net-implement-custom-serialization/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/asp-net/json-net-implement-custom-serialization/]]></guid>
		<pubDate>2012-04-24T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Factual Driver .NET Client Library Documentation]]></title>
		<description>
			<![CDATA[
				<h3 id="update-08072012">Update 08/07/2012</h3>

<p>For latest documentation please see [factual-csharp-project][1] on github.</p>

<h3 id="introduction">Introduction</h3>

<p>FactualDriver is a .NET client library for consuming Factual API. It abstracts creation of queries, oAuth header signing and synchronous web request/response process. It’s easy to use and you can get a response from factual in 2 lines of code. It also exposes a generic access to signed HttpWebRequest if you need more granular control or if you decide that you need to call Factual in asynchronous matter.</p>

<h3 id="getting-started">Getting started</h3>

<p>From you nuget package manager console install FactualDriver package</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">PM</span><span class="err">&gt;</span><span class="w"> </span><span class="nx">Install-Package</span><span class="w"> </span><span class="nx">FactualDriver</span><span class="w">
</span></code></pre></div></div>

<p>Next, you create an instance of the factual driver with your consumer key and consumer secret key that you received from Factual. And the simplest way to get data is to use a RawQuery function which will take table name as the first parameter and your raw url query and return you a json result string.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Factual</span> <span class="n">client</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">Factual</span><span class="p">(</span><span class="s">"YourConstumerKey"</span><span class="p">,</span><span class="s">"YourConsumerSecret"</span><span class="p">);</span>
<span class="kt">string</span> <span class="n">jsonResponse</span> <span class="p">=</span> <span class="n">client</span><span class="p">.</span><span class="nf">RawQuery</span><span class="p">(</span><span class="s">""</span><span class="n">t</span><span class="p">/</span><span class="k">global</span><span class="s">", "</span><span class="n">filters</span><span class="p">={</span><span class="err">\</span><span class="s">"name\":\"Star\"}"</span><span class="p">);</span>
</code></pre></div></div>

<p>As an option you can use included JSON.NET parser to convert response into a C# dynamic object.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">dynamic</span> <span class="n">json</span> <span class="p">=</span> <span class="n">JsonConvert</span><span class="p">.</span><span class="nf">DeserializeObject</span><span class="p">(</span><span class="n">jsonResponse</span><span class="p">);</span>
<span class="kt">string</span> <span class="n">status</span> <span class="p">=</span> <span class="p">(</span><span class="kt">string</span><span class="p">)</span><span class="n">json</span><span class="p">.</span><span class="n">status</span><span class="p">;</span>
</code></pre></div></div>

<h3 id="filters">Filters</h3>

<p>Building query string by hand is error prone, hard to maintain and just not pretty. As you might have noticed, Factual API uses json serialized object in the query string for filters, and uses a simple key value pair for other parameters like limit, or include_count. You can see a full list of parameters [here][2].</p>

<p>Rather than hacking string together, driver provides an object oriented way of creating parameters. IFilter classes provide a structure for parameters and are flexible enough to work with future api changes. Let’s take a look at first filter..</p>

<h4 id="rowfilter">RowFilter</h4>

<p>Constructor Signature:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">RowFilter</span><span class="p">(</span><span class="kt">string</span> <span class="n">fieldName</span><span class="p">,</span> <span class="kt">string</span> <span class="n">comparisonOperator</span><span class="p">,</span> <span class="kt">object</span> <span class="n">compareToValue</span><span class="p">)</span>
</code></pre></div></div>

<p>You create a row filter by providing a field name, operator and an object value. The reason compareToValue is an object is because you should be able to provide a simple type like integer as well as an array that will get serialized into json. For a list of field and operators see factual [documentation][3].</p>

<p>Here is how we create a row filter that instructs api to return all record where locality is not Los Angeles and Northridge and execute a query.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">filter</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">RowFilter</span><span class="p">(</span><span class="s">"locality"</span><span class="p">,</span> <span class="s">"$nin"</span><span class="p">,</span> <span class="k">new</span> <span class="p">[]</span> <span class="p">{</span> <span class="s">"Los Angeles"</span><span class="p">,</span> <span class="s">"Northridge"</span><span class="p">});</span>
<span class="kt">string</span> <span class="n">result</span> <span class="p">=</span> <span class="n">Factual</span><span class="p">.</span><span class="nf">Query</span><span class="p">(</span><span class="s">"t/global"</span><span class="p">,</span> <span class="n">filter</span><span class="p">);</span>
</code></pre></div></div>

<p>The query will get serialized into <code class="language-plaintext highlighter-rouge">{"locality":{"$nin":["Los Angeles","Santa Monica"]}}</code>, and you have compiler checking,intellisense, and no hacking together curly braces.</p>

<p>If you filter is a simple equal you can use a shorthand constructor:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="nf">RowFilter</span><span class="p">(</span><span class="kt">string</span> <span class="n">fieldName</span><span class="p">,</span> <span class="kt">object</span> <span class="n">compareToValue</span><span class="p">).</span>
</code></pre></div></div>

<p>Which will result in something like this {“region”:”CA”}, which is acceptable shorthand according to factual documentation.</p>

<p>Let’s see another example where use string rather than array to filter data.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">filter</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">RowFilter</span><span class="p">(</span><span class="s">"name"</span><span class="p">,</span> <span class="s">"$search"</span><span class="p">,</span> <span class="s">"Charles"</span><span class="p">);</span>
</code></pre></div></div>

<p>Outputs:<code class="language-plaintext highlighter-rouge">{"name":{"$search":"Charles"}}</code></p>

<h4 id="geofilter">GeoFilter</h4>

<p>Geofilter is very similar in terms of usage to RowFilter, except you provide different parameters of latitude and longitude along with radius distance in meters.</p>

<p>Signature:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">GeoFilter</span><span class="p">(</span><span class="kt">decimal</span> <span class="n">latitude</span><span class="p">,</span> <span class="kt">decimal</span> <span class="n">longitude</span><span class="p">,</span> <span class="kt">int</span> <span class="n">distance</span><span class="p">)</span>
</code></pre></div></div>

<p>Usage:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">geoFilter</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">GeoFilter</span><span class="p">(</span><span class="m">34.06018</span><span class="n">m</span><span class="p">,</span> <span class="p">-</span><span class="m">118.41835</span><span class="n">m</span><span class="p">,</span> <span class="m">5000</span><span class="p">);</span>
<span class="kt">string</span> <span class="n">result</span> <span class="p">=</span> <span class="n">Factual</span><span class="p">.</span><span class="nf">Query</span><span class="p">(</span><span class="s">"t/restaurants-us"</span><span class="p">,</span> <span class="n">geoFilter</span><span class="p">);</span>
</code></pre></div></div>

<p>You also have an option to override shape of the filter, the default shape is $circle by setting GetFilter’s Shape property. As well as override distance units by setting DistanceUnits property. However according to the [documentation][4] there are no other shapes available as of yet, so this might be useful in the future.</p>

<h4 id="searchfilter">SearchFilter</h4>

<p>Search filter only takes one parameter which is the search string. Here is an example:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">filter</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">SearchFilter</span><span class="p">(</span><span class="s">"Vegan,Los Angeles"</span><span class="p">);</span>
<span class="kt">string</span> <span class="n">result</span> <span class="p">=</span> <span class="n">Factual</span><span class="p">.</span><span class="nf">Query</span><span class="p">(</span><span class="s">"t/restaurants-us"</span><span class="p">,</span> <span class="n">filter</span><span class="p">);</span>
</code></pre></div></div>

<h4 id="filter---other-parameters---combining-filters">Filter - Other parameters - Combining FIlters</h4>

<p>There are other parameters like limit and offset and sort etc. Those are sent to factual as basic key value pair and not a serialized json object. There is also a wrapper for those properties, Filter. Here is an example of setting a limit on the query and combining it with RowFilter.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">limitFilter</span><span class="p">=</span> <span class="k">new</span> <span class="nf">Filter</span><span class="p">(</span><span class="s">"limit"</span><span class="p">,</span> <span class="s">"20"</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">rowFilter</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">RowFilter</span><span class="p">(</span><span class="s">"name"</span><span class="p">,</span> <span class="s">"$bw"</span><span class="p">,</span> <span class="s">"Star"</span><span class="p">);</span>
<span class="kt">string</span> <span class="n">result</span> <span class="p">=</span> <span class="n">Factual</span><span class="p">.</span><span class="nf">Query</span><span class="p">(</span><span class="s">"t/restaurants-us"</span><span class="p">,</span> <span class="n">rowFilter</span><span class="p">,</span> <span class="n">limitFilter</span><span class="p">);</span>
<span class="err">```</span>

<span class="err">####</span> <span class="n">ConditionalRowFilter</span>

<span class="n">There</span> <span class="k">is</span> <span class="n">also</span> <span class="n">a</span> <span class="n">conditional</span> <span class="n">operators</span> <span class="n">that</span> <span class="n">allows</span> <span class="n">you</span> <span class="n">to</span> <span class="k">set</span> <span class="n">AND</span> <span class="n">or</span> <span class="n">OR</span> <span class="k">operator</span> <span class="n">and</span> <span class="k">group</span> <span class="n">your</span> <span class="n">row</span> <span class="n">filters</span> <span class="n">together</span><span class="p">.</span>
<span class="err">```</span><span class="n">csharp</span>
<span class="kt">var</span> <span class="n">filter</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">ConditionalRowFilter</span><span class="p">(</span><span class="s">"$and"</span><span class="p">,</span> <span class="k">new</span><span class="p">[]</span>
    <span class="p">{</span>
    <span class="k">new</span> <span class="nf">RowFilter</span><span class="p">(</span><span class="s">"name"</span><span class="p">,</span> <span class="s">"$search"</span><span class="p">,</span> <span class="s">"McDonald's"</span><span class="p">),</span>
    <span class="k">new</span> <span class="nf">RowFilter</span><span class="p">(</span><span class="s">"category"</span><span class="p">,</span> <span class="s">"$bw"</span><span class="p">,</span> <span class="s">"Food &amp; Beverage"</span><span class="p">)</span>
    <span class="p">});</span>
<span class="err">```</span>

<span class="n">First</span> <span class="n">parameter</span> <span class="n">takes</span> <span class="n">a</span> <span class="kt">string</span> <span class="k">operator</span> <span class="k">value</span> <span class="err">$</span><span class="n">and</span> <span class="n">or</span> <span class="err">$</span><span class="n">or</span> <span class="n">and</span> <span class="n">second</span> <span class="n">takes</span> <span class="n">a</span> <span class="n">collection</span> <span class="n">of</span> <span class="n">RowFilter</span> <span class="n">types</span><span class="p">.</span> <span class="n">Result</span> <span class="n">will</span> <span class="k">get</span> <span class="n">serialized</span> <span class="k">into</span> <span class="n">an</span> <span class="n">api</span> <span class="n">query</span> <span class="n">like</span> <span class="k">this</span><span class="p">:</span>
<span class="err">```</span>
<span class="s">"filters={\"$and\":[{\"name\":{\"$search\":\"McDonald's\"}},{\"category\":{\"$bw\":\"Food &amp; Beverage\"}}]}"</span>
<span class="err">```</span>
<span class="err">#</span><span class="n">HttpWebRequest</span>
<span class="n">Factual</span><span class="p">.</span><span class="n">Query</span> <span class="n">or</span> <span class="n">Factual</span><span class="p">.</span><span class="n">RawQuery</span> <span class="n">will</span> <span class="n">create</span> <span class="n">a</span> <span class="n">synchronous</span> <span class="n">web</span> <span class="n">request</span> <span class="n">and</span> <span class="n">will</span> <span class="n">also</span> <span class="n">synchronously</span> <span class="k">get</span> <span class="n">a</span> <span class="n">response</span> <span class="n">back</span> <span class="k">from</span> <span class="n">factual</span><span class="p">,</span> <span class="n">read</span> <span class="n">it</span> <span class="k">as</span> <span class="n">a</span> <span class="kt">string</span> <span class="n">and</span> <span class="k">return</span> <span class="n">to</span> <span class="n">the</span> <span class="n">caller</span><span class="p">.</span> <span class="n">If</span> <span class="n">you</span> <span class="n">have</span> <span class="n">a</span> <span class="n">high</span> <span class="n">traffic</span> <span class="n">environment</span> <span class="n">that</span><span class="err">'</span><span class="n">s</span> <span class="n">probably</span> <span class="n">not</span> <span class="n">what</span> <span class="n">you</span> <span class="n">going</span> <span class="n">to</span> <span class="n">want</span> <span class="n">because</span> <span class="n">the</span> <span class="n">number</span> <span class="n">of</span> <span class="n">process</span> <span class="n">threads</span> <span class="k">is</span> <span class="n">limited</span> <span class="n">and</span> <span class="n">when</span> <span class="n">you</span> <span class="n">call</span> <span class="n">outside</span> <span class="n">service</span> <span class="n">synchronously</span> <span class="n">it</span> <span class="n">uses</span> <span class="n">it</span> <span class="n">up</span> <span class="n">a</span> <span class="n">thread</span><span class="p">,</span> <span class="n">and</span> <span class="k">if</span> <span class="n">you</span> <span class="n">have</span> <span class="n">more</span> <span class="n">users</span> <span class="n">than</span> <span class="n">your</span> <span class="n">threads</span> <span class="n">then</span> <span class="n">your</span> <span class="n">application</span> <span class="n">will</span> <span class="n">come</span> <span class="n">to</span> <span class="n">a</span> <span class="n">screeching</span> <span class="n">halt</span><span class="p">.</span> <span class="n">So</span> <span class="k">if</span> <span class="n">you</span> <span class="n">are</span> <span class="n">planning</span> <span class="k">on</span> <span class="n">experiencing</span> <span class="n">a</span> <span class="n">very</span> <span class="n">high</span> <span class="n">traffic</span><span class="p">,</span> <span class="n">you</span> <span class="n">want</span> <span class="n">to</span> <span class="n">call</span> <span class="n">factual</span> <span class="n">api</span> <span class="n">asynchronously</span><span class="p">.</span> <span class="n">And</span> <span class="n">you</span> <span class="n">can</span> <span class="k">do</span> <span class="n">that</span> <span class="k">by</span> <span class="n">getting</span> <span class="n">an</span> <span class="n">HttpWebRequest</span> <span class="kt">object</span> <span class="n">directly</span> <span class="k">from</span> <span class="n">Factual</span><span class="p">.</span><span class="nf">CreateWebRequest</span><span class="p">(</span><span class="kt">string</span> <span class="n">query</span><span class="p">)</span> <span class="n">and</span> <span class="n">then</span> <span class="n">executing</span> <span class="n">the</span> <span class="n">request</span> <span class="n">asynchronously</span><span class="p">.</span>

<span class="n">CreateWebRequest</span> <span class="n">accepts</span> <span class="n">a</span> <span class="n">raw</span> <span class="n">url</span> <span class="n">query</span> <span class="n">but</span> <span class="n">you</span> <span class="n">are</span> <span class="n">also</span> <span class="n">not</span> <span class="k">on</span> <span class="n">your</span> <span class="n">own</span> <span class="n">here</span><span class="p">.</span> <span class="n">You</span> <span class="n">can</span> <span class="n">create</span> <span class="n">your</span> <span class="n">filters</span> <span class="n">and</span> <span class="n">then</span> <span class="n">call</span> <span class="n">JsonUtil</span><span class="p">.</span><span class="n">ToQueryString</span> <span class="n">and</span> <span class="n">it</span> <span class="n">will</span> <span class="n">serialize</span> <span class="n">a</span> <span class="n">collection</span> <span class="n">of</span> <span class="n">filters</span> <span class="k">into</span> <span class="n">correct</span> <span class="n">json</span> <span class="n">query</span> <span class="kt">string</span><span class="p">.</span>

<span class="n">That</span><span class="err">'</span><span class="n">s</span> <span class="n">it</span> <span class="k">for</span> <span class="n">now</span><span class="p">,</span> <span class="n">please</span> <span class="k">let</span> <span class="n">me</span> <span class="n">know</span> <span class="k">if</span> <span class="n">you</span> <span class="n">have</span> <span class="n">any</span> <span class="n">questions</span> <span class="n">or</span> <span class="k">if</span> <span class="n">something</span> <span class="n">I</span> <span class="n">missed</span><span class="p">.</span>

<span class="p">[</span><span class="m">1</span><span class="p">]:</span> <span class="n">https</span><span class="p">:</span><span class="c1">//github.com/Factual/factual-csharp-driver</span>
<span class="p">[</span><span class="m">2</span><span class="p">]:</span> <span class="n">http</span><span class="p">:</span><span class="c1">//developer.factual.com/display/docs/Core+API+-+Read#CoreAPI-Read-OptionalParameters</span>
<span class="p">[</span><span class="m">3</span><span class="p">]:</span> <span class="n">http</span><span class="p">:</span><span class="c1">//developer.factual.com/display/docs/Core+API+-+Row+Filters</span>
<span class="p">[</span><span class="m">4</span><span class="p">]:</span> <span class="n">http</span><span class="p">:</span><span class="c1">//developer.factual.com/display/docs/Core+API+-+Geo+Filters</span>
</code></pre></div></div>

				<h3 id="update-08072012">Update 08/07/2012</h3>

<p>For latest documentation please see [factual-csharp-project][1] on github.</p>

<h3 id="introduction">Introduction</h3>

<p>FactualDriver is a .NET client library for consuming Factual API. It abstracts creation of queries, oAuth header signing and synchronous web request/response process. It’s easy to use and you can get a response from factual in 2 lines of code. It also exposes a generic access to signed HttpWebRequest if you need more granular control or if you decide that you need to call Factual in asynchronous matter.</p>

<h3 id="getting-started">Getting started</h3>

<p>From you nuget package manager console install FactualDriver package</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">PM</span><span class="err">&gt;</span><span class="w"> </span><span class="nx">Install-Package</span><span class="w"> </span><span class="nx">FactualDriver</span><span class="w">
</span></code></pre></div></div>

<p>Next, you create an instance of the factual driver with your consumer key and consumer secret key that you received from Factual. And the simplest way to get data is to use a RawQuery function which will take table name as the first parameter and your raw url query and return you a json result string.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Factual</span> <span class="n">client</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">Factual</span><span class="p">(</span><span class="s">"YourConstumerKey"</span><span class="p">,</span><span class="s">"YourConsumerSecret"</span><span class="p">);</span>
<span class="kt">string</span> <span class="n">jsonResponse</span> <span class="p">=</span> <span class="n">client</span><span class="p">.</span><span class="nf">RawQuery</span><span class="p">(</span><span class="s">""</span><span class="n">t</span><span class="p">/</span><span class="k">global</span><span class="s">", "</span><span class="n">filters</span><span class="p">={</span><span class="err">\</span><span class="s">"name\":\"Star\"}"</span><span class="p">);</span>
</code></pre></div></div>

<p>As an option you can use included JSON.NET parser to convert response into a C# dynamic object.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">dynamic</span> <span class="n">json</span> <span class="p">=</span> <span class="n">JsonConvert</span><span class="p">.</span><span class="nf">DeserializeObject</span><span class="p">(</span><span class="n">jsonResponse</span><span class="p">);</span>
<span class="kt">string</span> <span class="n">status</span> <span class="p">=</span> <span class="p">(</span><span class="kt">string</span><span class="p">)</span><span class="n">json</span><span class="p">.</span><span class="n">status</span><span class="p">;</span>
</code></pre></div></div>

<h3 id="filters">Filters</h3>

<p>Building query string by hand is error prone, hard to maintain and just not pretty. As you might have noticed, Factual API uses json serialized object in the query string for filters, and uses a simple key value pair for other parameters like limit, or include_count. You can see a full list of parameters [here][2].</p>

<p>Rather than hacking string together, driver provides an object oriented way of creating parameters. IFilter classes provide a structure for parameters and are flexible enough to work with future api changes. Let’s take a look at first filter..</p>

<h4 id="rowfilter">RowFilter</h4>

<p>Constructor Signature:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">RowFilter</span><span class="p">(</span><span class="kt">string</span> <span class="n">fieldName</span><span class="p">,</span> <span class="kt">string</span> <span class="n">comparisonOperator</span><span class="p">,</span> <span class="kt">object</span> <span class="n">compareToValue</span><span class="p">)</span>
</code></pre></div></div>

<p>You create a row filter by providing a field name, operator and an object value. The reason compareToValue is an object is because you should be able to provide a simple type like integer as well as an array that will get serialized into json. For a list of field and operators see factual [documentation][3].</p>

<p>Here is how we create a row filter that instructs api to return all record where locality is not Los Angeles and Northridge and execute a query.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">filter</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">RowFilter</span><span class="p">(</span><span class="s">"locality"</span><span class="p">,</span> <span class="s">"$nin"</span><span class="p">,</span> <span class="k">new</span> <span class="p">[]</span> <span class="p">{</span> <span class="s">"Los Angeles"</span><span class="p">,</span> <span class="s">"Northridge"</span><span class="p">});</span>
<span class="kt">string</span> <span class="n">result</span> <span class="p">=</span> <span class="n">Factual</span><span class="p">.</span><span class="nf">Query</span><span class="p">(</span><span class="s">"t/global"</span><span class="p">,</span> <span class="n">filter</span><span class="p">);</span>
</code></pre></div></div>

<p>The query will get serialized into <code class="language-plaintext highlighter-rouge">{"locality":{"$nin":["Los Angeles","Santa Monica"]}}</code>, and you have compiler checking,intellisense, and no hacking together curly braces.</p>

<p>If you filter is a simple equal you can use a shorthand constructor:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="nf">RowFilter</span><span class="p">(</span><span class="kt">string</span> <span class="n">fieldName</span><span class="p">,</span> <span class="kt">object</span> <span class="n">compareToValue</span><span class="p">).</span>
</code></pre></div></div>

<p>Which will result in something like this {“region”:”CA”}, which is acceptable shorthand according to factual documentation.</p>

<p>Let’s see another example where use string rather than array to filter data.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">filter</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">RowFilter</span><span class="p">(</span><span class="s">"name"</span><span class="p">,</span> <span class="s">"$search"</span><span class="p">,</span> <span class="s">"Charles"</span><span class="p">);</span>
</code></pre></div></div>

<p>Outputs:<code class="language-plaintext highlighter-rouge">{"name":{"$search":"Charles"}}</code></p>

<h4 id="geofilter">GeoFilter</h4>

<p>Geofilter is very similar in terms of usage to RowFilter, except you provide different parameters of latitude and longitude along with radius distance in meters.</p>

<p>Signature:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">GeoFilter</span><span class="p">(</span><span class="kt">decimal</span> <span class="n">latitude</span><span class="p">,</span> <span class="kt">decimal</span> <span class="n">longitude</span><span class="p">,</span> <span class="kt">int</span> <span class="n">distance</span><span class="p">)</span>
</code></pre></div></div>

<p>Usage:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">geoFilter</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">GeoFilter</span><span class="p">(</span><span class="m">34.06018</span><span class="n">m</span><span class="p">,</span> <span class="p">-</span><span class="m">118.41835</span><span class="n">m</span><span class="p">,</span> <span class="m">5000</span><span class="p">);</span>
<span class="kt">string</span> <span class="n">result</span> <span class="p">=</span> <span class="n">Factual</span><span class="p">.</span><span class="nf">Query</span><span class="p">(</span><span class="s">"t/restaurants-us"</span><span class="p">,</span> <span class="n">geoFilter</span><span class="p">);</span>
</code></pre></div></div>

<p>You also have an option to override shape of the filter, the default shape is $circle by setting GetFilter’s Shape property. As well as override distance units by setting DistanceUnits property. However according to the [documentation][4] there are no other shapes available as of yet, so this might be useful in the future.</p>

<h4 id="searchfilter">SearchFilter</h4>

<p>Search filter only takes one parameter which is the search string. Here is an example:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">filter</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">SearchFilter</span><span class="p">(</span><span class="s">"Vegan,Los Angeles"</span><span class="p">);</span>
<span class="kt">string</span> <span class="n">result</span> <span class="p">=</span> <span class="n">Factual</span><span class="p">.</span><span class="nf">Query</span><span class="p">(</span><span class="s">"t/restaurants-us"</span><span class="p">,</span> <span class="n">filter</span><span class="p">);</span>
</code></pre></div></div>

<h4 id="filter---other-parameters---combining-filters">Filter - Other parameters - Combining FIlters</h4>

<p>There are other parameters like limit and offset and sort etc. Those are sent to factual as basic key value pair and not a serialized json object. There is also a wrapper for those properties, Filter. Here is an example of setting a limit on the query and combining it with RowFilter.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">limitFilter</span><span class="p">=</span> <span class="k">new</span> <span class="nf">Filter</span><span class="p">(</span><span class="s">"limit"</span><span class="p">,</span> <span class="s">"20"</span><span class="p">);</span>
<span class="kt">var</span> <span class="n">rowFilter</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">RowFilter</span><span class="p">(</span><span class="s">"name"</span><span class="p">,</span> <span class="s">"$bw"</span><span class="p">,</span> <span class="s">"Star"</span><span class="p">);</span>
<span class="kt">string</span> <span class="n">result</span> <span class="p">=</span> <span class="n">Factual</span><span class="p">.</span><span class="nf">Query</span><span class="p">(</span><span class="s">"t/restaurants-us"</span><span class="p">,</span> <span class="n">rowFilter</span><span class="p">,</span> <span class="n">limitFilter</span><span class="p">);</span>
<span class="err">```</span>

<span class="err">####</span> <span class="n">ConditionalRowFilter</span>

<span class="n">There</span> <span class="k">is</span> <span class="n">also</span> <span class="n">a</span> <span class="n">conditional</span> <span class="n">operators</span> <span class="n">that</span> <span class="n">allows</span> <span class="n">you</span> <span class="n">to</span> <span class="k">set</span> <span class="n">AND</span> <span class="n">or</span> <span class="n">OR</span> <span class="k">operator</span> <span class="n">and</span> <span class="k">group</span> <span class="n">your</span> <span class="n">row</span> <span class="n">filters</span> <span class="n">together</span><span class="p">.</span>
<span class="err">```</span><span class="n">csharp</span>
<span class="kt">var</span> <span class="n">filter</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">ConditionalRowFilter</span><span class="p">(</span><span class="s">"$and"</span><span class="p">,</span> <span class="k">new</span><span class="p">[]</span>
    <span class="p">{</span>
    <span class="k">new</span> <span class="nf">RowFilter</span><span class="p">(</span><span class="s">"name"</span><span class="p">,</span> <span class="s">"$search"</span><span class="p">,</span> <span class="s">"McDonald's"</span><span class="p">),</span>
    <span class="k">new</span> <span class="nf">RowFilter</span><span class="p">(</span><span class="s">"category"</span><span class="p">,</span> <span class="s">"$bw"</span><span class="p">,</span> <span class="s">"Food &amp; Beverage"</span><span class="p">)</span>
    <span class="p">});</span>
<span class="err">```</span>

<span class="n">First</span> <span class="n">parameter</span> <span class="n">takes</span> <span class="n">a</span> <span class="kt">string</span> <span class="k">operator</span> <span class="k">value</span> <span class="err">$</span><span class="n">and</span> <span class="n">or</span> <span class="err">$</span><span class="n">or</span> <span class="n">and</span> <span class="n">second</span> <span class="n">takes</span> <span class="n">a</span> <span class="n">collection</span> <span class="n">of</span> <span class="n">RowFilter</span> <span class="n">types</span><span class="p">.</span> <span class="n">Result</span> <span class="n">will</span> <span class="k">get</span> <span class="n">serialized</span> <span class="k">into</span> <span class="n">an</span> <span class="n">api</span> <span class="n">query</span> <span class="n">like</span> <span class="k">this</span><span class="p">:</span>
<span class="err">```</span>
<span class="s">"filters={\"$and\":[{\"name\":{\"$search\":\"McDonald's\"}},{\"category\":{\"$bw\":\"Food &amp; Beverage\"}}]}"</span>
<span class="err">```</span>
<span class="err">#</span><span class="n">HttpWebRequest</span>
<span class="n">Factual</span><span class="p">.</span><span class="n">Query</span> <span class="n">or</span> <span class="n">Factual</span><span class="p">.</span><span class="n">RawQuery</span> <span class="n">will</span> <span class="n">create</span> <span class="n">a</span> <span class="n">synchronous</span> <span class="n">web</span> <span class="n">request</span> <span class="n">and</span> <span class="n">will</span> <span class="n">also</span> <span class="n">synchronously</span> <span class="k">get</span> <span class="n">a</span> <span class="n">response</span> <span class="n">back</span> <span class="k">from</span> <span class="n">factual</span><span class="p">,</span> <span class="n">read</span> <span class="n">it</span> <span class="k">as</span> <span class="n">a</span> <span class="kt">string</span> <span class="n">and</span> <span class="k">return</span> <span class="n">to</span> <span class="n">the</span> <span class="n">caller</span><span class="p">.</span> <span class="n">If</span> <span class="n">you</span> <span class="n">have</span> <span class="n">a</span> <span class="n">high</span> <span class="n">traffic</span> <span class="n">environment</span> <span class="n">that</span><span class="err">'</span><span class="n">s</span> <span class="n">probably</span> <span class="n">not</span> <span class="n">what</span> <span class="n">you</span> <span class="n">going</span> <span class="n">to</span> <span class="n">want</span> <span class="n">because</span> <span class="n">the</span> <span class="n">number</span> <span class="n">of</span> <span class="n">process</span> <span class="n">threads</span> <span class="k">is</span> <span class="n">limited</span> <span class="n">and</span> <span class="n">when</span> <span class="n">you</span> <span class="n">call</span> <span class="n">outside</span> <span class="n">service</span> <span class="n">synchronously</span> <span class="n">it</span> <span class="n">uses</span> <span class="n">it</span> <span class="n">up</span> <span class="n">a</span> <span class="n">thread</span><span class="p">,</span> <span class="n">and</span> <span class="k">if</span> <span class="n">you</span> <span class="n">have</span> <span class="n">more</span> <span class="n">users</span> <span class="n">than</span> <span class="n">your</span> <span class="n">threads</span> <span class="n">then</span> <span class="n">your</span> <span class="n">application</span> <span class="n">will</span> <span class="n">come</span> <span class="n">to</span> <span class="n">a</span> <span class="n">screeching</span> <span class="n">halt</span><span class="p">.</span> <span class="n">So</span> <span class="k">if</span> <span class="n">you</span> <span class="n">are</span> <span class="n">planning</span> <span class="k">on</span> <span class="n">experiencing</span> <span class="n">a</span> <span class="n">very</span> <span class="n">high</span> <span class="n">traffic</span><span class="p">,</span> <span class="n">you</span> <span class="n">want</span> <span class="n">to</span> <span class="n">call</span> <span class="n">factual</span> <span class="n">api</span> <span class="n">asynchronously</span><span class="p">.</span> <span class="n">And</span> <span class="n">you</span> <span class="n">can</span> <span class="k">do</span> <span class="n">that</span> <span class="k">by</span> <span class="n">getting</span> <span class="n">an</span> <span class="n">HttpWebRequest</span> <span class="kt">object</span> <span class="n">directly</span> <span class="k">from</span> <span class="n">Factual</span><span class="p">.</span><span class="nf">CreateWebRequest</span><span class="p">(</span><span class="kt">string</span> <span class="n">query</span><span class="p">)</span> <span class="n">and</span> <span class="n">then</span> <span class="n">executing</span> <span class="n">the</span> <span class="n">request</span> <span class="n">asynchronously</span><span class="p">.</span>

<span class="n">CreateWebRequest</span> <span class="n">accepts</span> <span class="n">a</span> <span class="n">raw</span> <span class="n">url</span> <span class="n">query</span> <span class="n">but</span> <span class="n">you</span> <span class="n">are</span> <span class="n">also</span> <span class="n">not</span> <span class="k">on</span> <span class="n">your</span> <span class="n">own</span> <span class="n">here</span><span class="p">.</span> <span class="n">You</span> <span class="n">can</span> <span class="n">create</span> <span class="n">your</span> <span class="n">filters</span> <span class="n">and</span> <span class="n">then</span> <span class="n">call</span> <span class="n">JsonUtil</span><span class="p">.</span><span class="n">ToQueryString</span> <span class="n">and</span> <span class="n">it</span> <span class="n">will</span> <span class="n">serialize</span> <span class="n">a</span> <span class="n">collection</span> <span class="n">of</span> <span class="n">filters</span> <span class="k">into</span> <span class="n">correct</span> <span class="n">json</span> <span class="n">query</span> <span class="kt">string</span><span class="p">.</span>

<span class="n">That</span><span class="err">'</span><span class="n">s</span> <span class="n">it</span> <span class="k">for</span> <span class="n">now</span><span class="p">,</span> <span class="n">please</span> <span class="k">let</span> <span class="n">me</span> <span class="n">know</span> <span class="k">if</span> <span class="n">you</span> <span class="n">have</span> <span class="n">any</span> <span class="n">questions</span> <span class="n">or</span> <span class="k">if</span> <span class="n">something</span> <span class="n">I</span> <span class="n">missed</span><span class="p">.</span>

<span class="p">[</span><span class="m">1</span><span class="p">]:</span> <span class="n">https</span><span class="p">:</span><span class="c1">//github.com/Factual/factual-csharp-driver</span>
<span class="p">[</span><span class="m">2</span><span class="p">]:</span> <span class="n">http</span><span class="p">:</span><span class="c1">//developer.factual.com/display/docs/Core+API+-+Read#CoreAPI-Read-OptionalParameters</span>
<span class="p">[</span><span class="m">3</span><span class="p">]:</span> <span class="n">http</span><span class="p">:</span><span class="c1">//developer.factual.com/display/docs/Core+API+-+Row+Filters</span>
<span class="p">[</span><span class="m">4</span><span class="p">]:</span> <span class="n">http</span><span class="p">:</span><span class="c1">//developer.factual.com/display/docs/Core+API+-+Geo+Filters</span>
</code></pre></div></div>

										
					<p>Posted in: factual-asp-net-driver</p>
						
				
					<p>Tagged with: asp.net, factual, and factual-driver</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/factual-asp-net-driver/documentation/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/factual-asp-net-driver/documentation/]]></guid>
		<pubDate>2012-04-21T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Prevent back button to serve cached content with ASP.NET]]></title>
		<description>
			<![CDATA[
				<p>Browsers cache pages by default in order to quickly serve the content when back button is clicked. There are times however when you don’t want that functionality. For example if your user logs out you don’t want them to be able to press back button and navigate back to member page again. Or other scenarios where javascript updates shopping cart on the page, but when you hit back button on the page browser serves up content from cache which doesn’t have the new item count in the cart.</p>

<p>Originally I’ve stumbled upon method below, but soon to discovered that it only works for some browsers including Internet Explorer.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Page</span><span class="p">.</span><span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">SetCacheability</span><span class="p">(</span><span class="n">HttpCacheability</span><span class="p">.</span><span class="n">ServerAndNoCache</span><span class="p">);</span>
</code></pre></div></div>

<p>Which results in the following header attribute, which is enough for IE but not enough for other browsers like Firefox and Chrome.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Cache-Control:no-cache
</code></pre></div></div>

<p>After doing more research on the browser cache headers I found <a href="http://palpapers.plynt.com/issues/2008Jul/cache-control-attributes/">this comprehensive guide</a> that explains that no-cache does not necessarily tells the browser not to cache results:</p>

<blockquote>
  <p>The “no-cache” directive, according to
the RFC, tells the browser that it
should revalidate with the server
before serving the page from the
cache. … In practice, IE and
Firefox have started treating the
no-cache directive as if it instructs
the browser not to even cache the
page. We started observing this
behavior about a year ago. We suspect
that this change was prompted by the
widespread (and incorrect) use of this
directive to prevent caching.directive to prevent caching.</p>
</blockquote>

<p>We have used that header incorrectly just like the article said. And that’s why we are seeing the random results for different browsers because originally the “no-cache” header is not the correct one to instruct browser not to cache the content. I’m guilty of this myself since when I first encountered this problem I quickly found the solution online and was happy to move on with my life, without trying to fully understand the intent of the Cache Control headers.</p>

<p>After reading through and understanding what each header suppose to do it was clear that the correct header to instruct browsers not to cache pages is the <strong>Cache Control: No-store</strong>. In addition it’s a good practice to include Cache Control: No-cache just to be on the safe side. And for sensitive content I think it’s also good to tell proxies not to cache the http result for example account areas. And to do that we need to set <strong>Cache-Control: private</strong>.</p>

<p>In ASP.NET we have the following method</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">SetNoStore</span><span class="p">();</span>
</code></pre></div></div>

<p>Which sets headers to <strong>Cache-Control:private, no-store</strong>. That takes care almost everything and the only thing left to do is to append the recommended no-cache to be on the safe side</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">AppendCacheExtension</span><span class="p">(</span><span class="s">"no-cache"</span><span class="p">);</span>
</code></pre></div></div>

<p>And now we have the desired headers: <strong>Cache-Control:private, no-store, no-cache</strong></p>

<p>Please let me know if you find any situations where above code doesn’t work. I’d like nail this problem once and for all.</p>

<p>Cheers</p>

<p><strong>Update 04-12-2012</strong></p>

<p>I’ve read another <a href="http://www.mnot.net/cache_docs/">good resource</a> on caching and think that adding expires header would also be beneficial for some other edge cases. So it wouldn’t hurt to add to this to your code as well:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Response</span><span class="p">.</span><span class="n">Expires</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span>
</code></pre></div></div>

<p>That brings us up to the three call that we need to make to make sure the page is not being cached:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">SetNoStore</span><span class="p">();</span>
<span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">AppendCacheExtension</span><span class="p">(</span><span class="s">"no-cache"</span><span class="p">);</span>
<span class="n">Response</span><span class="p">.</span><span class="n">Expires</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span>
</code></pre></div></div>


				<p>Browsers cache pages by default in order to quickly serve the content when back button is clicked. There are times however when you don’t want that functionality. For example if your user logs out you don’t want them to be able to press back button and navigate back to member page again. Or other scenarios where javascript updates shopping cart on the page, but when you hit back button on the page browser serves up content from cache which doesn’t have the new item count in the cart.</p>

<p>Originally I’ve stumbled upon method below, but soon to discovered that it only works for some browsers including Internet Explorer.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Page</span><span class="p">.</span><span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">SetCacheability</span><span class="p">(</span><span class="n">HttpCacheability</span><span class="p">.</span><span class="n">ServerAndNoCache</span><span class="p">);</span>
</code></pre></div></div>

<p>Which results in the following header attribute, which is enough for IE but not enough for other browsers like Firefox and Chrome.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Cache-Control:no-cache
</code></pre></div></div>

<p>After doing more research on the browser cache headers I found <a href="http://palpapers.plynt.com/issues/2008Jul/cache-control-attributes/">this comprehensive guide</a> that explains that no-cache does not necessarily tells the browser not to cache results:</p>

<blockquote>
  <p>The “no-cache” directive, according to
the RFC, tells the browser that it
should revalidate with the server
before serving the page from the
cache. … In practice, IE and
Firefox have started treating the
no-cache directive as if it instructs
the browser not to even cache the
page. We started observing this
behavior about a year ago. We suspect
that this change was prompted by the
widespread (and incorrect) use of this
directive to prevent caching.directive to prevent caching.</p>
</blockquote>

<p>We have used that header incorrectly just like the article said. And that’s why we are seeing the random results for different browsers because originally the “no-cache” header is not the correct one to instruct browser not to cache the content. I’m guilty of this myself since when I first encountered this problem I quickly found the solution online and was happy to move on with my life, without trying to fully understand the intent of the Cache Control headers.</p>

<p>After reading through and understanding what each header suppose to do it was clear that the correct header to instruct browsers not to cache pages is the <strong>Cache Control: No-store</strong>. In addition it’s a good practice to include Cache Control: No-cache just to be on the safe side. And for sensitive content I think it’s also good to tell proxies not to cache the http result for example account areas. And to do that we need to set <strong>Cache-Control: private</strong>.</p>

<p>In ASP.NET we have the following method</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">SetNoStore</span><span class="p">();</span>
</code></pre></div></div>

<p>Which sets headers to <strong>Cache-Control:private, no-store</strong>. That takes care almost everything and the only thing left to do is to append the recommended no-cache to be on the safe side</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">AppendCacheExtension</span><span class="p">(</span><span class="s">"no-cache"</span><span class="p">);</span>
</code></pre></div></div>

<p>And now we have the desired headers: <strong>Cache-Control:private, no-store, no-cache</strong></p>

<p>Please let me know if you find any situations where above code doesn’t work. I’d like nail this problem once and for all.</p>

<p>Cheers</p>

<p><strong>Update 04-12-2012</strong></p>

<p>I’ve read another <a href="http://www.mnot.net/cache_docs/">good resource</a> on caching and think that adding expires header would also be beneficial for some other edge cases. So it wouldn’t hurt to add to this to your code as well:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Response</span><span class="p">.</span><span class="n">Expires</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span>
</code></pre></div></div>

<p>That brings us up to the three call that we need to make to make sure the page is not being cached:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">SetNoStore</span><span class="p">();</span>
<span class="n">Response</span><span class="p">.</span><span class="n">Cache</span><span class="p">.</span><span class="nf">AppendCacheExtension</span><span class="p">(</span><span class="s">"no-cache"</span><span class="p">);</span>
<span class="n">Response</span><span class="p">.</span><span class="n">Expires</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span>
</code></pre></div></div>


										
					<p>Posted in: asp.net</p>
						
				
					<p>Tagged with: asp.net and browser-cache</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/asp-net/resolving-browser-back-button-with-caching-pages/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/asp-net/resolving-browser-back-button-with-caching-pages/]]></guid>
		<pubDate>2012-04-02T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Implementing 2 Legged OAuth with ASP.NET and Google Gdata Library]]></title>
		<description>
			<![CDATA[
				<p>Unfortunately Factual api’s doesn’t have a .net client library. But it’s not a big deal, to get started all we need is to create a signed 2 legged oauth web request and hack query string together.</p>

<p>On the quest for simplest way to create a 2 legged oauth requests I stumbled upon
Google.Data.Client library which already takes care of hashing and creating signatures for your request. All we have to do is to extend the OAuthAuthenticator class and make one override.</p>

<p>First you need to install Google’s library by going to your NuGet console and</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">Install-Package</span><span class="w"> </span><span class="nx">Google.GData.Client</span><span class="w">
</span></code></pre></div></div>

<p>Then create a new class that inherits from Google.GData.Client.OAuthAuthenticator:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">using</span> <span class="nn">System.Net</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">Google.GData.Client</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">class</span> <span class="nc">OAuth2LeggedAuthenticator</span> <span class="p">:</span> <span class="n">OAuthAuthenticator</span>
    <span class="p">{</span>
        <span class="k">public</span> <span class="nf">OAuth2LeggedAuthenticator</span><span class="p">(</span><span class="kt">string</span> <span class="n">applicationName</span><span class="p">,</span> <span class="kt">string</span> <span class="n">consumerKey</span><span class="p">,</span> <span class="kt">string</span> <span class="n">consumerSecret</span><span class="p">)</span> <span class="p">:</span> <span class="k">base</span><span class="p">(</span><span class="n">applicationName</span><span class="p">,</span> <span class="n">consumerKey</span><span class="p">,</span> <span class="n">consumerSecret</span><span class="p">)</span>
        <span class="p">{</span>
        <span class="p">}</span>

        <span class="k">public</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">ApplyAuthenticationToRequest</span><span class="p">(</span><span class="n">HttpWebRequest</span> <span class="n">request</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">base</span><span class="p">.</span><span class="nf">ApplyAuthenticationToRequest</span><span class="p">(</span><span class="n">request</span><span class="p">);</span>
            <span class="kt">string</span> <span class="n">header</span> <span class="p">=</span> <span class="n">OAuthUtil</span><span class="p">.</span><span class="nf">GenerateHeader</span><span class="p">(</span><span class="n">request</span><span class="p">.</span><span class="n">RequestUri</span><span class="p">,</span> <span class="n">ConsumerKey</span><span class="p">,</span> <span class="n">ConsumerSecret</span><span class="p">,</span> <span class="k">null</span><span class="p">,</span> <span class="k">null</span><span class="p">,</span> <span class="n">request</span><span class="p">.</span><span class="n">Method</span><span class="p">);</span>
            <span class="n">request</span><span class="p">.</span><span class="n">Headers</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">header</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>
</code></pre></div></div>

<p>And here is sample of the Factual service that uses that new class to make requests</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">using</span> <span class="nn">System</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.Collections.Generic</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.IO</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.Net</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.Linq</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">Newtonsoft.Json.Linq</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">RestaurantRep.Data.Model</span><span class="p">;</span>

    <span class="k">namespace</span> <span class="nn">RestaurantRep.Data.Services</span>
    <span class="p">{</span>
        <span class="k">public</span> <span class="k">class</span> <span class="nc">FactualService</span>
        <span class="p">{</span>
            <span class="k">private</span> <span class="k">const</span> <span class="kt">string</span> <span class="n">OAuthKey</span> <span class="p">=</span> <span class="s">"youroauthkey"</span><span class="p">;</span>
            <span class="k">private</span> <span class="k">const</span> <span class="kt">string</span> <span class="n">OAuthSecret</span> <span class="p">=</span> <span class="s">"yoursecretkey"</span><span class="p">;</span>
            <span class="k">private</span> <span class="k">const</span> <span class="kt">string</span> <span class="n">factualApiUrl</span> <span class="p">=</span> <span class="s">"http://api.v3.factual.com"</span><span class="p">;</span>

            <span class="k">private</span> <span class="k">readonly</span> <span class="n">OAuth2LeggedAuthenticator</span> <span class="n">_factualAuthenticator</span><span class="p">;</span>

            <span class="k">public</span> <span class="nf">FactualService</span><span class="p">()</span>
            <span class="p">{</span>
                <span class="n">_factualAuthenticator</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">OAuth2LeggedAuthenticator</span><span class="p">(</span><span class="s">"RestaurantRep"</span><span class="p">,</span> <span class="n">OAuthKey</span><span class="p">,</span> <span class="n">OAuthSecret</span><span class="p">);</span>
            <span class="p">}</span>

            <span class="c1">//sample query limit=50&amp;filters={\"name\":\"Bar Hayama\"}"</span>
            <span class="k">public</span> <span class="n">HttpWebRequest</span> <span class="nf">CreateFactualRestaurantRequest</span><span class="p">(</span><span class="kt">string</span> <span class="n">query</span><span class="p">)</span>
            <span class="p">{</span>
                <span class="kt">var</span> <span class="n">requestUrl</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">Uri</span><span class="p">(</span><span class="kt">string</span><span class="p">.</span><span class="nf">Format</span><span class="p">(</span><span class="s">"{0}/t/restaurants-us/read{1}"</span><span class="p">,</span> <span class="n">factualApiUrl</span><span class="p">,</span> <span class="n">query</span><span class="p">));</span>
                <span class="k">return</span> <span class="n">_factualAuthenticator</span><span class="p">.</span><span class="nf">CreateHttpWebRequest</span><span class="p">(</span><span class="s">"GET"</span><span class="p">,</span> <span class="n">requestUrl</span><span class="p">);</span>
            <span class="p">}</span>
    <span class="p">...</span>
</code></pre></div></div>

<p>And here is the ASP.NET Async Controller which queries Factual Api</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">using</span> <span class="nn">System.IO</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.Net</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.Web</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.Web.Mvc</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">RestaurantRep.Data.Services</span><span class="p">;</span>


    <span class="k">namespace</span> <span class="nn">RestaurantRep.Web.Controllers</span>
    <span class="p">{</span>
        <span class="k">public</span> <span class="k">class</span> <span class="nc">FactualController</span> <span class="p">:</span> <span class="n">AsyncController</span>
        <span class="p">{</span>
            <span class="k">private</span> <span class="k">readonly</span> <span class="n">FactualService</span> <span class="n">_service</span><span class="p">;</span>
            <span class="k">public</span> <span class="nf">FactualController</span><span class="p">()</span>
            <span class="p">{</span>
                <span class="n">_service</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">FactualService</span><span class="p">();</span>
            <span class="p">}</span>

            <span class="k">public</span> <span class="k">void</span> <span class="nf">RestaurantsAsync</span><span class="p">()</span>
            <span class="p">{</span>
                <span class="n">AsyncManager</span><span class="p">.</span><span class="n">OutstandingOperations</span><span class="p">.</span><span class="nf">Increment</span><span class="p">();</span>

                <span class="kt">var</span> <span class="n">request</span> <span class="p">=</span> <span class="n">_service</span><span class="p">.</span><span class="nf">CreateFactualRestaurantRequest</span><span class="p">(</span><span class="n">HttpUtility</span><span class="p">.</span><span class="nf">UrlDecode</span><span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">Url</span><span class="p">.</span><span class="n">Query</span><span class="p">));</span>
                <span class="n">request</span><span class="p">.</span><span class="nf">BeginGetResponse</span><span class="p">(</span><span class="n">asyncResult</span> <span class="p">=&gt;</span>
                <span class="p">{</span>
                    <span class="k">using</span> <span class="p">(</span><span class="n">WebResponse</span> <span class="n">response</span> <span class="p">=</span> <span class="n">request</span><span class="p">.</span><span class="nf">EndGetResponse</span><span class="p">(</span><span class="n">asyncResult</span><span class="p">))</span>
                    <span class="p">{</span>
                        <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">reader</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">StreamReader</span><span class="p">(</span><span class="n">response</span><span class="p">.</span><span class="nf">GetResponseStream</span><span class="p">()))</span>
                        <span class="p">{</span>
                            <span class="kt">var</span> <span class="n">jsonResult</span> <span class="p">=</span> <span class="n">reader</span><span class="p">.</span><span class="nf">ReadToEnd</span><span class="p">();</span>
                            <span class="n">AsyncManager</span><span class="p">.</span><span class="n">Parameters</span><span class="p">[</span><span class="s">"restaurants"</span><span class="p">]</span> <span class="p">=</span> <span class="n">jsonResult</span><span class="p">;</span>
                            <span class="n">AsyncManager</span><span class="p">.</span><span class="n">OutstandingOperations</span><span class="p">.</span><span class="nf">Decrement</span><span class="p">();</span>
                        <span class="p">}</span>
                    <span class="p">}</span>
                <span class="p">},</span> <span class="k">null</span><span class="p">);</span>

            <span class="p">}</span>

            <span class="k">public</span> <span class="n">ContentResult</span> <span class="nf">RestaurantsCompleted</span><span class="p">(</span><span class="kt">string</span> <span class="n">restaurants</span><span class="p">)</span>
            <span class="p">{</span>
                <span class="k">return</span> <span class="k">new</span> <span class="n">ContentResult</span> <span class="p">{</span> <span class="n">Content</span> <span class="p">=</span> <span class="n">restaurants</span><span class="p">,</span> <span class="n">ContentType</span> <span class="p">=</span> <span class="s">"application/json"</span> <span class="p">};</span>
            <span class="p">}</span>
        <span class="p">}</span>
</code></pre></div></div>

<p>As always, please let me know if you have questions.</p>

				<p>Unfortunately Factual api’s doesn’t have a .net client library. But it’s not a big deal, to get started all we need is to create a signed 2 legged oauth web request and hack query string together.</p>

<p>On the quest for simplest way to create a 2 legged oauth requests I stumbled upon
Google.Data.Client library which already takes care of hashing and creating signatures for your request. All we have to do is to extend the OAuthAuthenticator class and make one override.</p>

<p>First you need to install Google’s library by going to your NuGet console and</p>

<div class="language-powershell highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">Install-Package</span><span class="w"> </span><span class="nx">Google.GData.Client</span><span class="w">
</span></code></pre></div></div>

<p>Then create a new class that inherits from Google.GData.Client.OAuthAuthenticator:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">using</span> <span class="nn">System.Net</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">Google.GData.Client</span><span class="p">;</span>

    <span class="k">public</span> <span class="k">class</span> <span class="nc">OAuth2LeggedAuthenticator</span> <span class="p">:</span> <span class="n">OAuthAuthenticator</span>
    <span class="p">{</span>
        <span class="k">public</span> <span class="nf">OAuth2LeggedAuthenticator</span><span class="p">(</span><span class="kt">string</span> <span class="n">applicationName</span><span class="p">,</span> <span class="kt">string</span> <span class="n">consumerKey</span><span class="p">,</span> <span class="kt">string</span> <span class="n">consumerSecret</span><span class="p">)</span> <span class="p">:</span> <span class="k">base</span><span class="p">(</span><span class="n">applicationName</span><span class="p">,</span> <span class="n">consumerKey</span><span class="p">,</span> <span class="n">consumerSecret</span><span class="p">)</span>
        <span class="p">{</span>
        <span class="p">}</span>

        <span class="k">public</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">ApplyAuthenticationToRequest</span><span class="p">(</span><span class="n">HttpWebRequest</span> <span class="n">request</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">base</span><span class="p">.</span><span class="nf">ApplyAuthenticationToRequest</span><span class="p">(</span><span class="n">request</span><span class="p">);</span>
            <span class="kt">string</span> <span class="n">header</span> <span class="p">=</span> <span class="n">OAuthUtil</span><span class="p">.</span><span class="nf">GenerateHeader</span><span class="p">(</span><span class="n">request</span><span class="p">.</span><span class="n">RequestUri</span><span class="p">,</span> <span class="n">ConsumerKey</span><span class="p">,</span> <span class="n">ConsumerSecret</span><span class="p">,</span> <span class="k">null</span><span class="p">,</span> <span class="k">null</span><span class="p">,</span> <span class="n">request</span><span class="p">.</span><span class="n">Method</span><span class="p">);</span>
            <span class="n">request</span><span class="p">.</span><span class="n">Headers</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">header</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>
</code></pre></div></div>

<p>And here is sample of the Factual service that uses that new class to make requests</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">using</span> <span class="nn">System</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.Collections.Generic</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.IO</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.Net</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.Linq</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">Newtonsoft.Json.Linq</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">RestaurantRep.Data.Model</span><span class="p">;</span>

    <span class="k">namespace</span> <span class="nn">RestaurantRep.Data.Services</span>
    <span class="p">{</span>
        <span class="k">public</span> <span class="k">class</span> <span class="nc">FactualService</span>
        <span class="p">{</span>
            <span class="k">private</span> <span class="k">const</span> <span class="kt">string</span> <span class="n">OAuthKey</span> <span class="p">=</span> <span class="s">"youroauthkey"</span><span class="p">;</span>
            <span class="k">private</span> <span class="k">const</span> <span class="kt">string</span> <span class="n">OAuthSecret</span> <span class="p">=</span> <span class="s">"yoursecretkey"</span><span class="p">;</span>
            <span class="k">private</span> <span class="k">const</span> <span class="kt">string</span> <span class="n">factualApiUrl</span> <span class="p">=</span> <span class="s">"http://api.v3.factual.com"</span><span class="p">;</span>

            <span class="k">private</span> <span class="k">readonly</span> <span class="n">OAuth2LeggedAuthenticator</span> <span class="n">_factualAuthenticator</span><span class="p">;</span>

            <span class="k">public</span> <span class="nf">FactualService</span><span class="p">()</span>
            <span class="p">{</span>
                <span class="n">_factualAuthenticator</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">OAuth2LeggedAuthenticator</span><span class="p">(</span><span class="s">"RestaurantRep"</span><span class="p">,</span> <span class="n">OAuthKey</span><span class="p">,</span> <span class="n">OAuthSecret</span><span class="p">);</span>
            <span class="p">}</span>

            <span class="c1">//sample query limit=50&amp;filters={\"name\":\"Bar Hayama\"}"</span>
            <span class="k">public</span> <span class="n">HttpWebRequest</span> <span class="nf">CreateFactualRestaurantRequest</span><span class="p">(</span><span class="kt">string</span> <span class="n">query</span><span class="p">)</span>
            <span class="p">{</span>
                <span class="kt">var</span> <span class="n">requestUrl</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">Uri</span><span class="p">(</span><span class="kt">string</span><span class="p">.</span><span class="nf">Format</span><span class="p">(</span><span class="s">"{0}/t/restaurants-us/read{1}"</span><span class="p">,</span> <span class="n">factualApiUrl</span><span class="p">,</span> <span class="n">query</span><span class="p">));</span>
                <span class="k">return</span> <span class="n">_factualAuthenticator</span><span class="p">.</span><span class="nf">CreateHttpWebRequest</span><span class="p">(</span><span class="s">"GET"</span><span class="p">,</span> <span class="n">requestUrl</span><span class="p">);</span>
            <span class="p">}</span>
    <span class="p">...</span>
</code></pre></div></div>

<p>And here is the ASP.NET Async Controller which queries Factual Api</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">using</span> <span class="nn">System.IO</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.Net</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.Web</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">System.Web.Mvc</span><span class="p">;</span>
    <span class="k">using</span> <span class="nn">RestaurantRep.Data.Services</span><span class="p">;</span>


    <span class="k">namespace</span> <span class="nn">RestaurantRep.Web.Controllers</span>
    <span class="p">{</span>
        <span class="k">public</span> <span class="k">class</span> <span class="nc">FactualController</span> <span class="p">:</span> <span class="n">AsyncController</span>
        <span class="p">{</span>
            <span class="k">private</span> <span class="k">readonly</span> <span class="n">FactualService</span> <span class="n">_service</span><span class="p">;</span>
            <span class="k">public</span> <span class="nf">FactualController</span><span class="p">()</span>
            <span class="p">{</span>
                <span class="n">_service</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">FactualService</span><span class="p">();</span>
            <span class="p">}</span>

            <span class="k">public</span> <span class="k">void</span> <span class="nf">RestaurantsAsync</span><span class="p">()</span>
            <span class="p">{</span>
                <span class="n">AsyncManager</span><span class="p">.</span><span class="n">OutstandingOperations</span><span class="p">.</span><span class="nf">Increment</span><span class="p">();</span>

                <span class="kt">var</span> <span class="n">request</span> <span class="p">=</span> <span class="n">_service</span><span class="p">.</span><span class="nf">CreateFactualRestaurantRequest</span><span class="p">(</span><span class="n">HttpUtility</span><span class="p">.</span><span class="nf">UrlDecode</span><span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">Url</span><span class="p">.</span><span class="n">Query</span><span class="p">));</span>
                <span class="n">request</span><span class="p">.</span><span class="nf">BeginGetResponse</span><span class="p">(</span><span class="n">asyncResult</span> <span class="p">=&gt;</span>
                <span class="p">{</span>
                    <span class="k">using</span> <span class="p">(</span><span class="n">WebResponse</span> <span class="n">response</span> <span class="p">=</span> <span class="n">request</span><span class="p">.</span><span class="nf">EndGetResponse</span><span class="p">(</span><span class="n">asyncResult</span><span class="p">))</span>
                    <span class="p">{</span>
                        <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">reader</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">StreamReader</span><span class="p">(</span><span class="n">response</span><span class="p">.</span><span class="nf">GetResponseStream</span><span class="p">()))</span>
                        <span class="p">{</span>
                            <span class="kt">var</span> <span class="n">jsonResult</span> <span class="p">=</span> <span class="n">reader</span><span class="p">.</span><span class="nf">ReadToEnd</span><span class="p">();</span>
                            <span class="n">AsyncManager</span><span class="p">.</span><span class="n">Parameters</span><span class="p">[</span><span class="s">"restaurants"</span><span class="p">]</span> <span class="p">=</span> <span class="n">jsonResult</span><span class="p">;</span>
                            <span class="n">AsyncManager</span><span class="p">.</span><span class="n">OutstandingOperations</span><span class="p">.</span><span class="nf">Decrement</span><span class="p">();</span>
                        <span class="p">}</span>
                    <span class="p">}</span>
                <span class="p">},</span> <span class="k">null</span><span class="p">);</span>

            <span class="p">}</span>

            <span class="k">public</span> <span class="n">ContentResult</span> <span class="nf">RestaurantsCompleted</span><span class="p">(</span><span class="kt">string</span> <span class="n">restaurants</span><span class="p">)</span>
            <span class="p">{</span>
                <span class="k">return</span> <span class="k">new</span> <span class="n">ContentResult</span> <span class="p">{</span> <span class="n">Content</span> <span class="p">=</span> <span class="n">restaurants</span><span class="p">,</span> <span class="n">ContentType</span> <span class="p">=</span> <span class="s">"application/json"</span> <span class="p">};</span>
            <span class="p">}</span>
        <span class="p">}</span>
</code></pre></div></div>

<p>As always, please let me know if you have questions.</p>

										
					<p>Posted in: asp.net</p>
						
				
					<p>Tagged with: asp.net, oauth, and factual</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/asp-net/2-legged-oath/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/asp-net/2-legged-oath/]]></guid>
		<pubDate>2012-03-19T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Cross Domain Communication And Data Storage With localStorage And postMessage]]></title>
		<description>
			<![CDATA[
				<h3 id="summary">Summary</h3>

<p>You have probably seen stackoverflow’s 3rd party authentication in action: when you visit one of their sister sites that you have never visited before it automatically knows who you are. That’s possible with using 3rd party domain to store global encrypted session information and cross domain communication mechanism. For storage we can use either cookies and html5 localStorage and for communication we will look at using postMessage.</p>

<p>Without getting into the security aspect of the global authentication, I want to show the cross domain communication mechanism that makes this possible. We will use <strong>unsecure</strong> personalization data, like user’s first name for demonstration purposes.</p>

<h4 id="browser-support-for-localstorage">Browser support for localStorage</h4>

<p><img src="/uploads/12-03/localStorage-browser-support.png" alt="localStorage browser support" /></p>

<p>Most modern browsers support localStorage except IE6 and IE7, pretty much exact same storage with postMessage</p>

<h4 id="browser-support-for-postmessage">Browser support for postMessage:</h4>

<p><img src="/uploads/12-03/postMessage-browser-support.png" alt="postMessagebrowsersuport" /></p>

<h4 id="browser-usage">Browser Usage</h4>

<p>That brings us to the question, how many users are still using IE6 and IE7 and after we look at the figures decide if we can leave with those numbers or go a painful route.</p>

<p>As of February 2012 IE6 and IE7 are used by <a href="http://www.w3schools.com/browsers/browsers_explorer.asp">3.6%</a> of all users, and that number decreasing pretty fast, it dropped 15% from previous months which was at 4.2%.<br />
So if you have a mission critical operation where you must support 100% of browsers then you have to go longer route and figure out your way through a tretcherous road of 3rd party cookies and additional cross domain communication scripts that support older browsers. <a href="http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage/">This</a> blog post has a nice write up about that.</p>

<p>It will probably take you 3 time as long to make it work for those 3.6% of users. So if you can I would save yourself a major headache and write clean code for modern browsers.</p>

<p>When I first started I was actually going to use cookies for storage, but later on I’ve discovered that IE blocks 3rd party content and you have go your way out to a <a href="http://stackoverflow.com/questions/389456/cookie-blocked-not-saved-in-iframe-in-internet-explorer#answer-389458">pretty complex workaround</a>. And there is also a reliability issue I sometimes experienced.</p>

<h3 id="storing-data-with-3rd-party-domain">Storing data with 3rd party domain</h3>

<p>We’ll take a look at authentication example. Once you login to bob.com, it stores a some piece of information on frank.com storage. So when you visit another site bobsister.com, it can also read information from frank.com as long as frank has bobsister.com in the list of valid sites. This is of course is not designed to be secure, but it is also possible by encrypting messages stored in localStorage. Making it secure is a topic for another blog post.</p>

<p><img src="/uploads/12-03/write.png" alt="storage write example" /></p>

<p>Upon authentication we add an iframe that will write Name to 3rd party page, this can be done server side as well as with javascript</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">src</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">https://www.frank.com/auth/global/write.aspx?name=Alice</span><span class="dl">"</span><span class="p">;</span>
<span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">body</span><span class="dl">"</span><span class="p">).</span><span class="nx">append</span><span class="p">(</span>
  <span class="dl">"</span><span class="s2">&lt;iframe id='global-auth-frame' style='display:none' src='</span><span class="dl">"</span> <span class="o">+</span>
    <span class="nx">src</span> <span class="o">+</span>
    <span class="dl">"</span><span class="s2">'&gt;&lt;/iframe&gt;</span><span class="dl">"</span>
<span class="p">);</span>
</code></pre></div></div>

<p>or</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="n">HtmlGenericControl</span> <span class="nf">CreateGlobalIdentityTag</span><span class="p">(</span><span class="kt">string</span> <span class="n">name</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">var</span> <span class="n">frame</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">HtmlGenericControl</span><span class="p">(</span><span class="s">"iframe"</span><span class="p">);</span>
    <span class="n">frame</span><span class="p">.</span><span class="n">Attributes</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"src"</span><span class="p">,</span> <span class="s">"https://www.frank.com/auth/global/write.aspx?name="</span> <span class="p">+</span> <span class="n">name</span><span class="p">);</span>
    <span class="n">frame</span><span class="p">.</span><span class="n">Attributes</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"height"</span><span class="p">,</span><span class="s">"1"</span><span class="p">);</span>
    <span class="n">frame</span><span class="p">.</span><span class="n">Attributes</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"width"</span><span class="p">,</span> <span class="s">"1"</span><span class="p">);</span>
    <span class="n">frame</span><span class="p">.</span><span class="n">Attributes</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"frameborder"</span><span class="p">,</span><span class="s">"0"</span><span class="p">);</span>
    <span class="n">frame</span><span class="p">.</span><span class="n">Attributes</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"scrolling"</span><span class="p">,</span><span class="s">"no"</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">frame</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Write page</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">&lt;%</span><span class="err">@</span> <span class="n">Page</span> <span class="n">Language</span><span class="p">=</span><span class="s">"C#"</span> <span class="n">AutoEventWireup</span><span class="p">=</span><span class="s">"false"</span> <span class="n">CodeBehind</span><span class="p">=</span><span class="s">"Write.aspx.cs"</span> <span class="n">Inherits</span><span class="p">=</span><span class="s">"Sample.Write"</span> <span class="n">EnableViewState</span><span class="p">=</span><span class="s">"false"</span> <span class="p">%&gt;</span>

<span class="p">&lt;</span><span class="n">html</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="n">head</span><span class="p">&gt;&lt;</span><span class="n">title</span><span class="p">&gt;&lt;/</span><span class="n">title</span><span class="p">&gt;&lt;/</span><span class="n">head</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="n">body</span><span class="p">&gt;</span>
        <span class="p">&lt;</span><span class="n">asp</span><span class="p">:</span><span class="n">PlaceHolder</span> <span class="n">runat</span><span class="p">=</span><span class="s">"server"</span> <span class="n">ID</span><span class="p">=</span><span class="s">"plhWriteGlobalSession"</span> <span class="n">Visible</span><span class="p">=</span><span class="s">"False"</span><span class="p">&gt;</span>
            <span class="p">&lt;</span><span class="n">script</span> <span class="n">type</span><span class="p">=</span><span class="s">"text/javascript"</span><span class="p">&gt;</span>
                <span class="n">function</span> <span class="nf">hasLocalStorage</span><span class="p">()</span> <span class="p">{</span>
                    <span class="k">try</span> <span class="p">{</span>
                        <span class="k">return</span> <span class="err">'</span><span class="n">localStorage</span><span class="err">'</span> <span class="k">in</span> <span class="n">window</span> <span class="p">&amp;&amp;</span> <span class="n">window</span><span class="p">[</span><span class="err">'</span><span class="n">localStorage</span><span class="err">'</span><span class="p">]</span> <span class="p">!==</span> <span class="k">null</span><span class="p">;</span>
                    <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="n">e</span><span class="p">)</span> <span class="p">{</span>
                        <span class="k">return</span> <span class="k">false</span><span class="p">;</span>
                    <span class="p">}</span>
                <span class="p">}</span>

                <span class="n">function</span> <span class="nf">save</span><span class="p">(</span><span class="n">keyPrefix</span><span class="p">,</span> <span class="k">value</span><span class="p">)</span> <span class="p">{</span>
                    <span class="k">if</span> <span class="p">(!</span><span class="nf">hasLocalStorage</span><span class="p">())</span> <span class="p">{</span> <span class="k">return</span><span class="p">;</span> <span class="p">}</span>

                    <span class="c1">// clear old keys with this prefix, if any</span>
                    <span class="k">for</span> <span class="p">(</span><span class="kt">var</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">localStorage</span><span class="p">.</span><span class="n">length</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span> <span class="p">{</span>
                        <span class="k">if</span> <span class="p">((</span><span class="n">localStorage</span><span class="p">.</span><span class="nf">key</span><span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="p">||</span> <span class="err">''</span><span class="p">).</span><span class="nf">indexOf</span><span class="p">(</span><span class="n">keyPrefix</span><span class="p">)</span> <span class="p">&gt;</span> <span class="p">-</span><span class="m">1</span><span class="p">)</span> <span class="p">{</span>
                            <span class="n">localStorage</span><span class="p">.</span><span class="nf">removeItem</span><span class="p">(</span><span class="n">localStorage</span><span class="p">.</span><span class="nf">key</span><span class="p">(</span><span class="n">i</span><span class="p">));</span>
                        <span class="p">}</span>
                    <span class="p">}</span>

                    <span class="c1">// save under this version</span>
                    <span class="n">localStorage</span><span class="p">[</span><span class="n">keyPrefix</span><span class="p">]</span> <span class="p">=</span> <span class="k">value</span><span class="p">;</span>
                <span class="p">};</span>

                <span class="nf">save</span><span class="p">(</span><span class="err">'</span><span class="p">&lt;%=</span> <span class="n">StorageName</span> <span class="p">%&gt;</span><span class="err">'</span> <span class="p">+</span> <span class="err">'</span><span class="p">-</span><span class="n">name</span><span class="err">'</span><span class="p">,</span> <span class="err">'</span><span class="p">&lt;%=</span><span class="n">Name</span> <span class="p">%&gt;</span><span class="err">'</span><span class="p">);</span>
        <span class="p">&lt;/</span><span class="n">script</span><span class="p">&gt;</span>
    <span class="p">&lt;/</span><span class="n">asp</span><span class="p">:</span><span class="n">PlaceHolder</span><span class="p">&gt;</span>
<span class="p">&lt;/</span><span class="n">body</span><span class="p">&gt;</span>
<span class="p">&lt;/</span><span class="n">html</span><span class="p">&gt;</span>
</code></pre></div></div>

<p>And a code behind that check’s if request came from trusted domain</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">Write</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Web</span><span class="p">.</span><span class="n">UI</span><span class="p">.</span><span class="n">Page</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">StorageName</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">Name</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>

    <span class="k">protected</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">OnLoad</span><span class="p">(</span><span class="n">System</span><span class="p">.</span><span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">//Check if iframe UrlReferrer is valid</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">UrlReferrer</span> <span class="p">!=</span> <span class="k">null</span> <span class="p">&amp;&amp;</span> <span class="nf">AuthorizedDomain</span><span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">UrlReferrer</span><span class="p">.</span><span class="n">Authority</span><span class="p">))</span>
        <span class="p">{</span>
            <span class="n">plhWriteGlobalSession</span><span class="p">.</span><span class="n">Visible</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="k">else</span>
        <span class="p">{</span>
            <span class="k">return</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="n">Name</span> <span class="p">=</span> <span class="n">Request</span><span class="p">.</span><span class="n">QueryString</span><span class="p">[</span><span class="s">"name"</span><span class="p">];</span>
        <span class="k">if</span> <span class="p">(</span><span class="kt">string</span><span class="p">.</span><span class="nf">IsNullOrEmpty</span><span class="p">(</span><span class="n">Name</span><span class="p">))</span>
            <span class="k">return</span><span class="p">;</span>

        <span class="n">StorageName</span> <span class="p">=</span> <span class="s">"GlobalName"</span><span class="p">;</span>
        <span class="n">plhWriteGlobalSession</span><span class="p">.</span><span class="n">Visible</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>

        <span class="k">base</span><span class="p">.</span><span class="nf">OnLoad</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">private</span> <span class="k">static</span> <span class="kt">bool</span> <span class="nf">AuthorizedDomain</span><span class="p">(</span><span class="kt">string</span> <span class="n">uri</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="kt">string</span><span class="p">[]</span> <span class="n">authorizedDomains</span> <span class="p">=</span> <span class="k">new</span> <span class="p">[]</span>
                                            <span class="p">{</span>
                                                <span class="s">"bob.com"</span><span class="p">,</span>
                                                <span class="s">"bobsister.com"</span>
                                            <span class="p">};</span>
        <span class="k">return</span> <span class="n">authorizedDomains</span><span class="p">.</span><span class="nf">Contains</span><span class="p">(</span><span class="n">uri</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="reading-data-from-3rd-party-domain">Reading data from 3rd party domain</h3>

<p>To read data from 3rd party we create an iframe similar to the write example.</p>

<p>And our read page will look like this.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">&lt;%</span><span class="err">@</span> <span class="n">Page</span> <span class="n">Language</span><span class="p">=</span><span class="s">"C#"</span> <span class="n">AutoEventWireup</span><span class="p">=</span><span class="s">"false"</span> <span class="n">CodeBehind</span><span class="p">=</span><span class="s">"Read.aspx.cs"</span> <span class="n">Inherits</span><span class="p">=</span><span class="s">"Sample.Read"</span> <span class="n">EnableViewState</span><span class="p">=</span><span class="s">"false"</span> <span class="p">%&gt;</span>

<span class="p">&lt;</span><span class="n">html</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="n">head</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="n">title</span><span class="p">&gt;&lt;/</span><span class="n">title</span><span class="p">&gt;</span>
<span class="p">&lt;/</span><span class="n">head</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="n">body</span><span class="p">&gt;</span>
    <span class="p">&lt;</span><span class="n">script</span> <span class="n">type</span><span class="p">=</span><span class="s">"text/javascript"</span><span class="p">&gt;</span>
        <span class="n">function</span> <span class="nf">hasLocalStorage</span><span class="p">()</span> <span class="p">{</span>
            <span class="k">try</span> <span class="p">{</span>
                <span class="k">return</span> <span class="err">'</span><span class="n">localStorage</span><span class="err">'</span> <span class="k">in</span> <span class="n">window</span> <span class="p">&amp;&amp;</span> <span class="n">window</span><span class="p">[</span><span class="err">'</span><span class="n">localStorage</span><span class="err">'</span><span class="p">]</span> <span class="p">!==</span> <span class="k">null</span><span class="p">;</span>
            <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="n">e</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="k">false</span><span class="p">;</span>
            <span class="p">}</span>
        <span class="p">}</span>

        <span class="n">function</span> <span class="nf">load</span><span class="p">(</span><span class="n">keyPrefix</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(!</span><span class="nf">hasLocalStorage</span><span class="p">())</span> <span class="p">{</span> <span class="k">return</span> <span class="k">null</span><span class="p">;</span> <span class="p">}</span>
            <span class="k">return</span> <span class="n">localStorage</span><span class="p">[</span><span class="n">keyPrefix</span><span class="p">];</span>
        <span class="p">}</span>

        <span class="n">function</span> <span class="nf">serialize</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="p">{</span>
            <span class="kt">var</span> <span class="n">str</span> <span class="p">=</span> <span class="p">[];</span>
            <span class="k">for</span> <span class="p">(</span><span class="kt">var</span> <span class="n">p</span> <span class="k">in</span> <span class="n">obj</span><span class="p">)</span>
                <span class="n">str</span><span class="p">.</span><span class="nf">push</span><span class="p">(</span><span class="n">p</span> <span class="p">+</span> <span class="s">"="</span> <span class="p">+</span> <span class="n">obj</span><span class="p">[</span><span class="n">p</span><span class="p">]);</span>
            <span class="k">return</span> <span class="n">str</span><span class="p">.</span><span class="k">join</span><span class="p">(</span><span class="s">"&amp;"</span><span class="p">);</span>
        <span class="p">}</span>

    <span class="p">&lt;/</span><span class="n">script</span><span class="p">&gt;</span>

    <span class="p">&lt;%--</span> <span class="n">Not</span> <span class="n">authorized</span> <span class="n">domain</span> <span class="k">is</span> <span class="n">making</span> <span class="n">request</span><span class="p">--%&gt;</span>
    <span class="p">&lt;</span><span class="n">asp</span><span class="p">:</span><span class="n">Panel</span> <span class="n">runat</span><span class="p">=</span><span class="s">"server"</span> <span class="n">ID</span><span class="p">=</span><span class="s">"pnlNotAuthorized"</span> <span class="n">Visible</span><span class="p">=</span><span class="s">"false"</span><span class="p">&gt;</span>
        <span class="p">&lt;</span><span class="n">script</span> <span class="n">type</span><span class="p">=</span><span class="err">'</span><span class="n">text</span><span class="p">/</span><span class="n">javascript</span><span class="err">'</span><span class="p">&gt;</span>
            <span class="k">if</span><span class="p">(</span><span class="n">top</span><span class="p">.</span><span class="n">postMessage</span> <span class="p">!=</span> <span class="err">'</span><span class="n">undefined</span><span class="err">'</span> <span class="p">&amp;&amp;</span> <span class="n">top</span><span class="p">.</span><span class="n">postMessage</span> <span class="p">!=</span> <span class="k">null</span><span class="p">){</span>
                <span class="n">top</span><span class="p">.</span><span class="nf">postMessage</span><span class="p">(</span><span class="err">'</span><span class="n">Not</span> <span class="n">one</span> <span class="n">of</span> <span class="n">the</span> <span class="n">authorized</span> <span class="n">domains</span><span class="err">'</span><span class="p">,</span> <span class="s">"&lt;%= Referrer %&gt;"</span><span class="p">);</span>
            <span class="p">}</span>
        <span class="p">&lt;/</span><span class="n">script</span><span class="p">&gt;</span>
    <span class="p">&lt;/</span><span class="n">asp</span><span class="p">:</span><span class="n">Panel</span><span class="p">&gt;</span>

    <span class="p">&lt;%--</span> <span class="n">Authorized</span> <span class="p">--%&gt;</span>
    <span class="p">&lt;</span><span class="n">asp</span><span class="p">:</span><span class="n">Panel</span> <span class="n">runat</span><span class="p">=</span><span class="s">"server"</span> <span class="n">ID</span><span class="p">=</span><span class="s">"pnlAuthorized"</span> <span class="n">Visible</span><span class="p">=</span><span class="s">"false"</span><span class="p">&gt;</span>
        <span class="p">&lt;</span><span class="n">script</span> <span class="n">type</span><span class="p">=</span><span class="err">'</span><span class="n">text</span><span class="p">/</span><span class="n">javascript</span><span class="err">'</span><span class="p">&gt;</span>
            <span class="k">if</span> <span class="p">(!</span><span class="nf">hasLocalStorage</span><span class="p">())</span> <span class="p">{</span>
                <span class="k">if</span> <span class="p">(</span><span class="n">top</span><span class="p">.</span><span class="n">postMessage</span> <span class="p">!=</span> <span class="err">'</span><span class="n">undefined</span><span class="err">'</span> <span class="p">&amp;&amp;</span> <span class="n">top</span><span class="p">.</span><span class="n">postMessage</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
                    <span class="n">top</span><span class="p">.</span><span class="nf">postMessage</span><span class="p">(</span><span class="err">'</span><span class="n">No</span> <span class="n">Local</span> <span class="n">Storage</span><span class="err">'</span><span class="p">,</span> <span class="s">"&lt;%= Referrer %&gt;"</span><span class="p">);</span>
                <span class="p">}</span>
            <span class="p">}</span>

            <span class="kt">var</span> <span class="n">storageKey</span> <span class="p">=</span> <span class="err">'</span><span class="p">&lt;%=</span> <span class="n">StorageKey</span><span class="p">%&gt;</span><span class="err">'</span><span class="p">;</span>
            <span class="kt">var</span> <span class="n">data</span> <span class="p">=</span> <span class="p">{</span> <span class="n">Referrer</span><span class="p">:</span>  <span class="err">'</span><span class="p">&lt;%=</span> <span class="n">String</span><span class="p">.</span><span class="nf">Format</span><span class="p">(</span><span class="s">"{0}://{1}"</span><span class="p">,</span><span class="n">Referrer</span><span class="p">.</span><span class="n">Scheme</span><span class="p">,</span> <span class="n">Referrer</span><span class="p">.</span><span class="n">Authority</span><span class="p">)</span> <span class="p">%&gt;</span><span class="err">'</span><span class="p">,</span> <span class="n">Name</span> <span class="p">:</span> <span class="nf">load</span><span class="p">(</span><span class="n">storageKey</span> <span class="p">+</span> <span class="err">'</span><span class="p">-</span><span class="n">name</span><span class="err">'</span><span class="p">)};</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">top</span><span class="p">.</span><span class="n">postMessage</span> <span class="p">!=</span> <span class="err">'</span><span class="n">undefined</span><span class="err">'</span> <span class="p">&amp;&amp;</span> <span class="n">top</span><span class="p">.</span><span class="n">postMessage</span> <span class="p">!=</span> <span class="k">null</span> <span class="p">&amp;&amp;</span> <span class="n">data</span><span class="p">.</span><span class="n">Name</span> <span class="p">!=</span> <span class="err">'</span><span class="n">undefined</span><span class="err">'</span> <span class="p">&amp;&amp;</span> <span class="n">data</span><span class="p">.</span><span class="n">Name</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
                <span class="n">top</span><span class="p">.</span><span class="nf">postMessage</span><span class="p">(</span><span class="nf">serialize</span><span class="p">(</span><span class="n">data</span><span class="p">),</span> <span class="n">data</span><span class="p">.</span><span class="n">Referrer</span><span class="p">);</span>
            <span class="p">}</span>
        <span class="p">&lt;/</span><span class="n">script</span><span class="p">&gt;</span>
    <span class="p">&lt;/</span><span class="n">asp</span><span class="p">:</span><span class="n">Panel</span><span class="p">&gt;</span>


<span class="p">&lt;/</span><span class="n">body</span><span class="p">&gt;</span>
<span class="p">&lt;/</span><span class="n">html</span><span class="p">&gt;</span>
</code></pre></div></div>

<p>If the domain making the 3rd party request is not authorized we display a not authorized panel which post “Not authorized message”. Since postMessage is designed to use a string message, I’ve added a simple serialization method which formats object as a query string. I decided not to use outside libraries to serialize data to keep the number of requests to one and make this as fast as possible.</p>

<p>And the code behind:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">Read</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Web</span><span class="p">.</span><span class="n">UI</span><span class="p">.</span><span class="n">Page</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">Name</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="n">Uri</span> <span class="n">Referrer</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>

    <span class="k">protected</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">OnLoad</span><span class="p">(</span><span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">if</span><span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">UrlReferrer</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span> <span class="k">return</span><span class="p">;</span>

        <span class="n">Referrer</span> <span class="p">=</span> <span class="n">Request</span><span class="p">.</span><span class="n">UrlReferrer</span><span class="p">;</span>

        <span class="k">if</span> <span class="p">(</span><span class="nf">AuthorizedDomain</span><span class="p">(</span><span class="n">Referrer</span><span class="p">.</span><span class="n">Authority</span><span class="p">))</span>
        <span class="p">{</span>
            <span class="n">pnlAuthorized</span><span class="p">.</span><span class="n">Visible</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="k">else</span>
        <span class="p">{</span>
            <span class="n">pnlNotAuthorized</span><span class="p">.</span><span class="n">Visible</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
        <span class="p">}</span>


        <span class="k">base</span><span class="p">.</span><span class="nf">OnLoad</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="p">...</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The final piece is to subscribe our client side page page to receive Alice’s name once the 3rd party global data is read cross domain. Once we receive that data we can display it to the user, and/or save it in the cookie so it server side will have it available on the next request.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">deSerialize</span><span class="p">(</span><span class="nx">text</span><span class="p">)</span> <span class="p">{</span>
  <span class="kd">var</span> <span class="nx">result</span> <span class="o">=</span> <span class="p">{};</span>
  <span class="kd">var</span> <span class="nx">pairs</span> <span class="o">=</span> <span class="nx">text</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="dl">"</span><span class="s2">&amp;</span><span class="dl">"</span><span class="p">);</span>
  <span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">pairs</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">keyValuePair</span> <span class="o">=</span> <span class="nx">pairs</span><span class="p">[</span><span class="nx">i</span><span class="p">].</span><span class="nx">split</span><span class="p">(</span><span class="dl">"</span><span class="s2">=</span><span class="dl">"</span><span class="p">);</span>
    <span class="nx">result</span><span class="p">[</span><span class="nx">keyValuePair</span><span class="p">[</span><span class="mi">0</span><span class="p">]]</span> <span class="o">=</span> <span class="nx">keyValuePair</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="nx">result</span><span class="p">;</span>
<span class="p">}</span>

<span class="nx">$</span><span class="p">(</span><span class="nb">window</span><span class="p">).</span><span class="nx">bind</span><span class="p">(</span><span class="dl">"</span><span class="s2">message</span><span class="dl">"</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
  <span class="kd">var</span> <span class="nx">e</span> <span class="o">=</span> <span class="nx">event</span><span class="p">.</span><span class="nx">originalEvent</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">origin</span> <span class="o">!==</span> <span class="dl">"</span><span class="s2">https://www.frank.com</span><span class="dl">"</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">not authorized domain</span><span class="dl">"</span><span class="p">);</span>
    <span class="k">return</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="kd">var</span> <span class="nx">data</span> <span class="o">=</span> <span class="nx">deSerialize</span><span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">data</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">Name</span> <span class="o">&amp;&amp;</span> <span class="nx">data</span><span class="p">.</span><span class="nx">Name</span> <span class="o">!=</span> <span class="dl">""</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">//Display name on the page, etc..</span>

    <span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Name is found </span><span class="dl">"</span> <span class="o">+</span> <span class="nx">data</span><span class="p">.</span><span class="nx">Name</span><span class="p">);</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">No Global Session Found</span><span class="dl">"</span><span class="p">);</span>
    <span class="nx">setGlobalSessionCookie</span><span class="p">(</span><span class="kc">false</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">});</span>

<span class="kd">function</span> <span class="nx">log</span><span class="p">(</span><span class="nx">text</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">console</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">INFO: </span><span class="dl">"</span> <span class="o">+</span> <span class="nx">text</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>I also learned the localStorage is based on the domain, so if you are going to be reading from secure pages make sure that you store and read from https domain because localStorage is different for secure and unsecure domains.</p>

<h3 id="and-there-you-have-it">And there you have it.</h3>

<p>Now you know how cross domain storage/communication is achieved with modern browsers. Let me know if you have any questions, and of course feedback is always greatly appreciated!</p>

<p>Cheers</p>


				<h3 id="summary">Summary</h3>

<p>You have probably seen stackoverflow’s 3rd party authentication in action: when you visit one of their sister sites that you have never visited before it automatically knows who you are. That’s possible with using 3rd party domain to store global encrypted session information and cross domain communication mechanism. For storage we can use either cookies and html5 localStorage and for communication we will look at using postMessage.</p>

<p>Without getting into the security aspect of the global authentication, I want to show the cross domain communication mechanism that makes this possible. We will use <strong>unsecure</strong> personalization data, like user’s first name for demonstration purposes.</p>

<h4 id="browser-support-for-localstorage">Browser support for localStorage</h4>

<p><img src="/uploads/12-03/localStorage-browser-support.png" alt="localStorage browser support" /></p>

<p>Most modern browsers support localStorage except IE6 and IE7, pretty much exact same storage with postMessage</p>

<h4 id="browser-support-for-postmessage">Browser support for postMessage:</h4>

<p><img src="/uploads/12-03/postMessage-browser-support.png" alt="postMessagebrowsersuport" /></p>

<h4 id="browser-usage">Browser Usage</h4>

<p>That brings us to the question, how many users are still using IE6 and IE7 and after we look at the figures decide if we can leave with those numbers or go a painful route.</p>

<p>As of February 2012 IE6 and IE7 are used by <a href="http://www.w3schools.com/browsers/browsers_explorer.asp">3.6%</a> of all users, and that number decreasing pretty fast, it dropped 15% from previous months which was at 4.2%.<br />
So if you have a mission critical operation where you must support 100% of browsers then you have to go longer route and figure out your way through a tretcherous road of 3rd party cookies and additional cross domain communication scripts that support older browsers. <a href="http://www.onlineaspect.com/2010/01/15/backwards-compatible-postmessage/">This</a> blog post has a nice write up about that.</p>

<p>It will probably take you 3 time as long to make it work for those 3.6% of users. So if you can I would save yourself a major headache and write clean code for modern browsers.</p>

<p>When I first started I was actually going to use cookies for storage, but later on I’ve discovered that IE blocks 3rd party content and you have go your way out to a <a href="http://stackoverflow.com/questions/389456/cookie-blocked-not-saved-in-iframe-in-internet-explorer#answer-389458">pretty complex workaround</a>. And there is also a reliability issue I sometimes experienced.</p>

<h3 id="storing-data-with-3rd-party-domain">Storing data with 3rd party domain</h3>

<p>We’ll take a look at authentication example. Once you login to bob.com, it stores a some piece of information on frank.com storage. So when you visit another site bobsister.com, it can also read information from frank.com as long as frank has bobsister.com in the list of valid sites. This is of course is not designed to be secure, but it is also possible by encrypting messages stored in localStorage. Making it secure is a topic for another blog post.</p>

<p><img src="/uploads/12-03/write.png" alt="storage write example" /></p>

<p>Upon authentication we add an iframe that will write Name to 3rd party page, this can be done server side as well as with javascript</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">var</span> <span class="nx">src</span> <span class="o">=</span> <span class="dl">"</span><span class="s2">https://www.frank.com/auth/global/write.aspx?name=Alice</span><span class="dl">"</span><span class="p">;</span>
<span class="nx">$</span><span class="p">(</span><span class="dl">"</span><span class="s2">body</span><span class="dl">"</span><span class="p">).</span><span class="nx">append</span><span class="p">(</span>
  <span class="dl">"</span><span class="s2">&lt;iframe id='global-auth-frame' style='display:none' src='</span><span class="dl">"</span> <span class="o">+</span>
    <span class="nx">src</span> <span class="o">+</span>
    <span class="dl">"</span><span class="s2">'&gt;&lt;/iframe&gt;</span><span class="dl">"</span>
<span class="p">);</span>
</code></pre></div></div>

<p>or</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="n">HtmlGenericControl</span> <span class="nf">CreateGlobalIdentityTag</span><span class="p">(</span><span class="kt">string</span> <span class="n">name</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">var</span> <span class="n">frame</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">HtmlGenericControl</span><span class="p">(</span><span class="s">"iframe"</span><span class="p">);</span>
    <span class="n">frame</span><span class="p">.</span><span class="n">Attributes</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"src"</span><span class="p">,</span> <span class="s">"https://www.frank.com/auth/global/write.aspx?name="</span> <span class="p">+</span> <span class="n">name</span><span class="p">);</span>
    <span class="n">frame</span><span class="p">.</span><span class="n">Attributes</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"height"</span><span class="p">,</span><span class="s">"1"</span><span class="p">);</span>
    <span class="n">frame</span><span class="p">.</span><span class="n">Attributes</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"width"</span><span class="p">,</span> <span class="s">"1"</span><span class="p">);</span>
    <span class="n">frame</span><span class="p">.</span><span class="n">Attributes</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"frameborder"</span><span class="p">,</span><span class="s">"0"</span><span class="p">);</span>
    <span class="n">frame</span><span class="p">.</span><span class="n">Attributes</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="s">"scrolling"</span><span class="p">,</span><span class="s">"no"</span><span class="p">);</span>
    <span class="k">return</span> <span class="n">frame</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Write page</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">&lt;%</span><span class="err">@</span> <span class="n">Page</span> <span class="n">Language</span><span class="p">=</span><span class="s">"C#"</span> <span class="n">AutoEventWireup</span><span class="p">=</span><span class="s">"false"</span> <span class="n">CodeBehind</span><span class="p">=</span><span class="s">"Write.aspx.cs"</span> <span class="n">Inherits</span><span class="p">=</span><span class="s">"Sample.Write"</span> <span class="n">EnableViewState</span><span class="p">=</span><span class="s">"false"</span> <span class="p">%&gt;</span>

<span class="p">&lt;</span><span class="n">html</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="n">head</span><span class="p">&gt;&lt;</span><span class="n">title</span><span class="p">&gt;&lt;/</span><span class="n">title</span><span class="p">&gt;&lt;/</span><span class="n">head</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="n">body</span><span class="p">&gt;</span>
        <span class="p">&lt;</span><span class="n">asp</span><span class="p">:</span><span class="n">PlaceHolder</span> <span class="n">runat</span><span class="p">=</span><span class="s">"server"</span> <span class="n">ID</span><span class="p">=</span><span class="s">"plhWriteGlobalSession"</span> <span class="n">Visible</span><span class="p">=</span><span class="s">"False"</span><span class="p">&gt;</span>
            <span class="p">&lt;</span><span class="n">script</span> <span class="n">type</span><span class="p">=</span><span class="s">"text/javascript"</span><span class="p">&gt;</span>
                <span class="n">function</span> <span class="nf">hasLocalStorage</span><span class="p">()</span> <span class="p">{</span>
                    <span class="k">try</span> <span class="p">{</span>
                        <span class="k">return</span> <span class="err">'</span><span class="n">localStorage</span><span class="err">'</span> <span class="k">in</span> <span class="n">window</span> <span class="p">&amp;&amp;</span> <span class="n">window</span><span class="p">[</span><span class="err">'</span><span class="n">localStorage</span><span class="err">'</span><span class="p">]</span> <span class="p">!==</span> <span class="k">null</span><span class="p">;</span>
                    <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="n">e</span><span class="p">)</span> <span class="p">{</span>
                        <span class="k">return</span> <span class="k">false</span><span class="p">;</span>
                    <span class="p">}</span>
                <span class="p">}</span>

                <span class="n">function</span> <span class="nf">save</span><span class="p">(</span><span class="n">keyPrefix</span><span class="p">,</span> <span class="k">value</span><span class="p">)</span> <span class="p">{</span>
                    <span class="k">if</span> <span class="p">(!</span><span class="nf">hasLocalStorage</span><span class="p">())</span> <span class="p">{</span> <span class="k">return</span><span class="p">;</span> <span class="p">}</span>

                    <span class="c1">// clear old keys with this prefix, if any</span>
                    <span class="k">for</span> <span class="p">(</span><span class="kt">var</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">localStorage</span><span class="p">.</span><span class="n">length</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span> <span class="p">{</span>
                        <span class="k">if</span> <span class="p">((</span><span class="n">localStorage</span><span class="p">.</span><span class="nf">key</span><span class="p">(</span><span class="n">i</span><span class="p">)</span> <span class="p">||</span> <span class="err">''</span><span class="p">).</span><span class="nf">indexOf</span><span class="p">(</span><span class="n">keyPrefix</span><span class="p">)</span> <span class="p">&gt;</span> <span class="p">-</span><span class="m">1</span><span class="p">)</span> <span class="p">{</span>
                            <span class="n">localStorage</span><span class="p">.</span><span class="nf">removeItem</span><span class="p">(</span><span class="n">localStorage</span><span class="p">.</span><span class="nf">key</span><span class="p">(</span><span class="n">i</span><span class="p">));</span>
                        <span class="p">}</span>
                    <span class="p">}</span>

                    <span class="c1">// save under this version</span>
                    <span class="n">localStorage</span><span class="p">[</span><span class="n">keyPrefix</span><span class="p">]</span> <span class="p">=</span> <span class="k">value</span><span class="p">;</span>
                <span class="p">};</span>

                <span class="nf">save</span><span class="p">(</span><span class="err">'</span><span class="p">&lt;%=</span> <span class="n">StorageName</span> <span class="p">%&gt;</span><span class="err">'</span> <span class="p">+</span> <span class="err">'</span><span class="p">-</span><span class="n">name</span><span class="err">'</span><span class="p">,</span> <span class="err">'</span><span class="p">&lt;%=</span><span class="n">Name</span> <span class="p">%&gt;</span><span class="err">'</span><span class="p">);</span>
        <span class="p">&lt;/</span><span class="n">script</span><span class="p">&gt;</span>
    <span class="p">&lt;/</span><span class="n">asp</span><span class="p">:</span><span class="n">PlaceHolder</span><span class="p">&gt;</span>
<span class="p">&lt;/</span><span class="n">body</span><span class="p">&gt;</span>
<span class="p">&lt;/</span><span class="n">html</span><span class="p">&gt;</span>
</code></pre></div></div>

<p>And a code behind that check’s if request came from trusted domain</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">Write</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Web</span><span class="p">.</span><span class="n">UI</span><span class="p">.</span><span class="n">Page</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">StorageName</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">Name</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>

    <span class="k">protected</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">OnLoad</span><span class="p">(</span><span class="n">System</span><span class="p">.</span><span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="c1">//Check if iframe UrlReferrer is valid</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">UrlReferrer</span> <span class="p">!=</span> <span class="k">null</span> <span class="p">&amp;&amp;</span> <span class="nf">AuthorizedDomain</span><span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">UrlReferrer</span><span class="p">.</span><span class="n">Authority</span><span class="p">))</span>
        <span class="p">{</span>
            <span class="n">plhWriteGlobalSession</span><span class="p">.</span><span class="n">Visible</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="k">else</span>
        <span class="p">{</span>
            <span class="k">return</span><span class="p">;</span>
        <span class="p">}</span>

        <span class="n">Name</span> <span class="p">=</span> <span class="n">Request</span><span class="p">.</span><span class="n">QueryString</span><span class="p">[</span><span class="s">"name"</span><span class="p">];</span>
        <span class="k">if</span> <span class="p">(</span><span class="kt">string</span><span class="p">.</span><span class="nf">IsNullOrEmpty</span><span class="p">(</span><span class="n">Name</span><span class="p">))</span>
            <span class="k">return</span><span class="p">;</span>

        <span class="n">StorageName</span> <span class="p">=</span> <span class="s">"GlobalName"</span><span class="p">;</span>
        <span class="n">plhWriteGlobalSession</span><span class="p">.</span><span class="n">Visible</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>

        <span class="k">base</span><span class="p">.</span><span class="nf">OnLoad</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="k">private</span> <span class="k">static</span> <span class="kt">bool</span> <span class="nf">AuthorizedDomain</span><span class="p">(</span><span class="kt">string</span> <span class="n">uri</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="kt">string</span><span class="p">[]</span> <span class="n">authorizedDomains</span> <span class="p">=</span> <span class="k">new</span> <span class="p">[]</span>
                                            <span class="p">{</span>
                                                <span class="s">"bob.com"</span><span class="p">,</span>
                                                <span class="s">"bobsister.com"</span>
                                            <span class="p">};</span>
        <span class="k">return</span> <span class="n">authorizedDomains</span><span class="p">.</span><span class="nf">Contains</span><span class="p">(</span><span class="n">uri</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h3 id="reading-data-from-3rd-party-domain">Reading data from 3rd party domain</h3>

<p>To read data from 3rd party we create an iframe similar to the write example.</p>

<p>And our read page will look like this.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">&lt;%</span><span class="err">@</span> <span class="n">Page</span> <span class="n">Language</span><span class="p">=</span><span class="s">"C#"</span> <span class="n">AutoEventWireup</span><span class="p">=</span><span class="s">"false"</span> <span class="n">CodeBehind</span><span class="p">=</span><span class="s">"Read.aspx.cs"</span> <span class="n">Inherits</span><span class="p">=</span><span class="s">"Sample.Read"</span> <span class="n">EnableViewState</span><span class="p">=</span><span class="s">"false"</span> <span class="p">%&gt;</span>

<span class="p">&lt;</span><span class="n">html</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="n">head</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="n">title</span><span class="p">&gt;&lt;/</span><span class="n">title</span><span class="p">&gt;</span>
<span class="p">&lt;/</span><span class="n">head</span><span class="p">&gt;</span>
<span class="p">&lt;</span><span class="n">body</span><span class="p">&gt;</span>
    <span class="p">&lt;</span><span class="n">script</span> <span class="n">type</span><span class="p">=</span><span class="s">"text/javascript"</span><span class="p">&gt;</span>
        <span class="n">function</span> <span class="nf">hasLocalStorage</span><span class="p">()</span> <span class="p">{</span>
            <span class="k">try</span> <span class="p">{</span>
                <span class="k">return</span> <span class="err">'</span><span class="n">localStorage</span><span class="err">'</span> <span class="k">in</span> <span class="n">window</span> <span class="p">&amp;&amp;</span> <span class="n">window</span><span class="p">[</span><span class="err">'</span><span class="n">localStorage</span><span class="err">'</span><span class="p">]</span> <span class="p">!==</span> <span class="k">null</span><span class="p">;</span>
            <span class="p">}</span> <span class="k">catch</span> <span class="p">(</span><span class="n">e</span><span class="p">)</span> <span class="p">{</span>
                <span class="k">return</span> <span class="k">false</span><span class="p">;</span>
            <span class="p">}</span>
        <span class="p">}</span>

        <span class="n">function</span> <span class="nf">load</span><span class="p">(</span><span class="n">keyPrefix</span><span class="p">)</span> <span class="p">{</span>
            <span class="k">if</span> <span class="p">(!</span><span class="nf">hasLocalStorage</span><span class="p">())</span> <span class="p">{</span> <span class="k">return</span> <span class="k">null</span><span class="p">;</span> <span class="p">}</span>
            <span class="k">return</span> <span class="n">localStorage</span><span class="p">[</span><span class="n">keyPrefix</span><span class="p">];</span>
        <span class="p">}</span>

        <span class="n">function</span> <span class="nf">serialize</span><span class="p">(</span><span class="n">obj</span><span class="p">)</span> <span class="p">{</span>
            <span class="kt">var</span> <span class="n">str</span> <span class="p">=</span> <span class="p">[];</span>
            <span class="k">for</span> <span class="p">(</span><span class="kt">var</span> <span class="n">p</span> <span class="k">in</span> <span class="n">obj</span><span class="p">)</span>
                <span class="n">str</span><span class="p">.</span><span class="nf">push</span><span class="p">(</span><span class="n">p</span> <span class="p">+</span> <span class="s">"="</span> <span class="p">+</span> <span class="n">obj</span><span class="p">[</span><span class="n">p</span><span class="p">]);</span>
            <span class="k">return</span> <span class="n">str</span><span class="p">.</span><span class="k">join</span><span class="p">(</span><span class="s">"&amp;"</span><span class="p">);</span>
        <span class="p">}</span>

    <span class="p">&lt;/</span><span class="n">script</span><span class="p">&gt;</span>

    <span class="p">&lt;%--</span> <span class="n">Not</span> <span class="n">authorized</span> <span class="n">domain</span> <span class="k">is</span> <span class="n">making</span> <span class="n">request</span><span class="p">--%&gt;</span>
    <span class="p">&lt;</span><span class="n">asp</span><span class="p">:</span><span class="n">Panel</span> <span class="n">runat</span><span class="p">=</span><span class="s">"server"</span> <span class="n">ID</span><span class="p">=</span><span class="s">"pnlNotAuthorized"</span> <span class="n">Visible</span><span class="p">=</span><span class="s">"false"</span><span class="p">&gt;</span>
        <span class="p">&lt;</span><span class="n">script</span> <span class="n">type</span><span class="p">=</span><span class="err">'</span><span class="n">text</span><span class="p">/</span><span class="n">javascript</span><span class="err">'</span><span class="p">&gt;</span>
            <span class="k">if</span><span class="p">(</span><span class="n">top</span><span class="p">.</span><span class="n">postMessage</span> <span class="p">!=</span> <span class="err">'</span><span class="n">undefined</span><span class="err">'</span> <span class="p">&amp;&amp;</span> <span class="n">top</span><span class="p">.</span><span class="n">postMessage</span> <span class="p">!=</span> <span class="k">null</span><span class="p">){</span>
                <span class="n">top</span><span class="p">.</span><span class="nf">postMessage</span><span class="p">(</span><span class="err">'</span><span class="n">Not</span> <span class="n">one</span> <span class="n">of</span> <span class="n">the</span> <span class="n">authorized</span> <span class="n">domains</span><span class="err">'</span><span class="p">,</span> <span class="s">"&lt;%= Referrer %&gt;"</span><span class="p">);</span>
            <span class="p">}</span>
        <span class="p">&lt;/</span><span class="n">script</span><span class="p">&gt;</span>
    <span class="p">&lt;/</span><span class="n">asp</span><span class="p">:</span><span class="n">Panel</span><span class="p">&gt;</span>

    <span class="p">&lt;%--</span> <span class="n">Authorized</span> <span class="p">--%&gt;</span>
    <span class="p">&lt;</span><span class="n">asp</span><span class="p">:</span><span class="n">Panel</span> <span class="n">runat</span><span class="p">=</span><span class="s">"server"</span> <span class="n">ID</span><span class="p">=</span><span class="s">"pnlAuthorized"</span> <span class="n">Visible</span><span class="p">=</span><span class="s">"false"</span><span class="p">&gt;</span>
        <span class="p">&lt;</span><span class="n">script</span> <span class="n">type</span><span class="p">=</span><span class="err">'</span><span class="n">text</span><span class="p">/</span><span class="n">javascript</span><span class="err">'</span><span class="p">&gt;</span>
            <span class="k">if</span> <span class="p">(!</span><span class="nf">hasLocalStorage</span><span class="p">())</span> <span class="p">{</span>
                <span class="k">if</span> <span class="p">(</span><span class="n">top</span><span class="p">.</span><span class="n">postMessage</span> <span class="p">!=</span> <span class="err">'</span><span class="n">undefined</span><span class="err">'</span> <span class="p">&amp;&amp;</span> <span class="n">top</span><span class="p">.</span><span class="n">postMessage</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
                    <span class="n">top</span><span class="p">.</span><span class="nf">postMessage</span><span class="p">(</span><span class="err">'</span><span class="n">No</span> <span class="n">Local</span> <span class="n">Storage</span><span class="err">'</span><span class="p">,</span> <span class="s">"&lt;%= Referrer %&gt;"</span><span class="p">);</span>
                <span class="p">}</span>
            <span class="p">}</span>

            <span class="kt">var</span> <span class="n">storageKey</span> <span class="p">=</span> <span class="err">'</span><span class="p">&lt;%=</span> <span class="n">StorageKey</span><span class="p">%&gt;</span><span class="err">'</span><span class="p">;</span>
            <span class="kt">var</span> <span class="n">data</span> <span class="p">=</span> <span class="p">{</span> <span class="n">Referrer</span><span class="p">:</span>  <span class="err">'</span><span class="p">&lt;%=</span> <span class="n">String</span><span class="p">.</span><span class="nf">Format</span><span class="p">(</span><span class="s">"{0}://{1}"</span><span class="p">,</span><span class="n">Referrer</span><span class="p">.</span><span class="n">Scheme</span><span class="p">,</span> <span class="n">Referrer</span><span class="p">.</span><span class="n">Authority</span><span class="p">)</span> <span class="p">%&gt;</span><span class="err">'</span><span class="p">,</span> <span class="n">Name</span> <span class="p">:</span> <span class="nf">load</span><span class="p">(</span><span class="n">storageKey</span> <span class="p">+</span> <span class="err">'</span><span class="p">-</span><span class="n">name</span><span class="err">'</span><span class="p">)};</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">top</span><span class="p">.</span><span class="n">postMessage</span> <span class="p">!=</span> <span class="err">'</span><span class="n">undefined</span><span class="err">'</span> <span class="p">&amp;&amp;</span> <span class="n">top</span><span class="p">.</span><span class="n">postMessage</span> <span class="p">!=</span> <span class="k">null</span> <span class="p">&amp;&amp;</span> <span class="n">data</span><span class="p">.</span><span class="n">Name</span> <span class="p">!=</span> <span class="err">'</span><span class="n">undefined</span><span class="err">'</span> <span class="p">&amp;&amp;</span> <span class="n">data</span><span class="p">.</span><span class="n">Name</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span> <span class="p">{</span>
                <span class="n">top</span><span class="p">.</span><span class="nf">postMessage</span><span class="p">(</span><span class="nf">serialize</span><span class="p">(</span><span class="n">data</span><span class="p">),</span> <span class="n">data</span><span class="p">.</span><span class="n">Referrer</span><span class="p">);</span>
            <span class="p">}</span>
        <span class="p">&lt;/</span><span class="n">script</span><span class="p">&gt;</span>
    <span class="p">&lt;/</span><span class="n">asp</span><span class="p">:</span><span class="n">Panel</span><span class="p">&gt;</span>


<span class="p">&lt;/</span><span class="n">body</span><span class="p">&gt;</span>
<span class="p">&lt;/</span><span class="n">html</span><span class="p">&gt;</span>
</code></pre></div></div>

<p>If the domain making the 3rd party request is not authorized we display a not authorized panel which post “Not authorized message”. Since postMessage is designed to use a string message, I’ve added a simple serialization method which formats object as a query string. I decided not to use outside libraries to serialize data to keep the number of requests to one and make this as fast as possible.</p>

<p>And the code behind:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">Read</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Web</span><span class="p">.</span><span class="n">UI</span><span class="p">.</span><span class="n">Page</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="kt">string</span> <span class="n">Name</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="n">Uri</span> <span class="n">Referrer</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>

    <span class="k">protected</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">OnLoad</span><span class="p">(</span><span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">if</span><span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">UrlReferrer</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span> <span class="k">return</span><span class="p">;</span>

        <span class="n">Referrer</span> <span class="p">=</span> <span class="n">Request</span><span class="p">.</span><span class="n">UrlReferrer</span><span class="p">;</span>

        <span class="k">if</span> <span class="p">(</span><span class="nf">AuthorizedDomain</span><span class="p">(</span><span class="n">Referrer</span><span class="p">.</span><span class="n">Authority</span><span class="p">))</span>
        <span class="p">{</span>
            <span class="n">pnlAuthorized</span><span class="p">.</span><span class="n">Visible</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="k">else</span>
        <span class="p">{</span>
            <span class="n">pnlNotAuthorized</span><span class="p">.</span><span class="n">Visible</span> <span class="p">=</span> <span class="k">true</span><span class="p">;</span>
        <span class="p">}</span>


        <span class="k">base</span><span class="p">.</span><span class="nf">OnLoad</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
    <span class="p">}</span>

    <span class="p">...</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The final piece is to subscribe our client side page page to receive Alice’s name once the 3rd party global data is read cross domain. Once we receive that data we can display it to the user, and/or save it in the cookie so it server side will have it available on the next request.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">deSerialize</span><span class="p">(</span><span class="nx">text</span><span class="p">)</span> <span class="p">{</span>
  <span class="kd">var</span> <span class="nx">result</span> <span class="o">=</span> <span class="p">{};</span>
  <span class="kd">var</span> <span class="nx">pairs</span> <span class="o">=</span> <span class="nx">text</span><span class="p">.</span><span class="nx">split</span><span class="p">(</span><span class="dl">"</span><span class="s2">&amp;</span><span class="dl">"</span><span class="p">);</span>
  <span class="k">for</span> <span class="p">(</span><span class="kd">var</span> <span class="nx">i</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span> <span class="nx">i</span> <span class="o">&lt;</span> <span class="nx">pairs</span><span class="p">.</span><span class="nx">length</span><span class="p">;</span> <span class="nx">i</span><span class="o">++</span><span class="p">)</span> <span class="p">{</span>
    <span class="kd">var</span> <span class="nx">keyValuePair</span> <span class="o">=</span> <span class="nx">pairs</span><span class="p">[</span><span class="nx">i</span><span class="p">].</span><span class="nx">split</span><span class="p">(</span><span class="dl">"</span><span class="s2">=</span><span class="dl">"</span><span class="p">);</span>
    <span class="nx">result</span><span class="p">[</span><span class="nx">keyValuePair</span><span class="p">[</span><span class="mi">0</span><span class="p">]]</span> <span class="o">=</span> <span class="nx">keyValuePair</span><span class="p">[</span><span class="mi">1</span><span class="p">];</span>
  <span class="p">}</span>
  <span class="k">return</span> <span class="nx">result</span><span class="p">;</span>
<span class="p">}</span>

<span class="nx">$</span><span class="p">(</span><span class="nb">window</span><span class="p">).</span><span class="nx">bind</span><span class="p">(</span><span class="dl">"</span><span class="s2">message</span><span class="dl">"</span><span class="p">,</span> <span class="kd">function</span> <span class="p">(</span><span class="nx">event</span><span class="p">)</span> <span class="p">{</span>
  <span class="kd">var</span> <span class="nx">e</span> <span class="o">=</span> <span class="nx">event</span><span class="p">.</span><span class="nx">originalEvent</span><span class="p">;</span>
  <span class="k">if</span> <span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">origin</span> <span class="o">!==</span> <span class="dl">"</span><span class="s2">https://www.frank.com</span><span class="dl">"</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">not authorized domain</span><span class="dl">"</span><span class="p">);</span>
    <span class="k">return</span><span class="p">;</span>
  <span class="p">}</span>

  <span class="kd">var</span> <span class="nx">data</span> <span class="o">=</span> <span class="nx">deSerialize</span><span class="p">(</span><span class="nx">e</span><span class="p">.</span><span class="nx">data</span><span class="p">);</span>
  <span class="k">if</span> <span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">Name</span> <span class="o">&amp;&amp;</span> <span class="nx">data</span><span class="p">.</span><span class="nx">Name</span> <span class="o">!=</span> <span class="dl">""</span><span class="p">)</span> <span class="p">{</span>
    <span class="c1">//Display name on the page, etc..</span>

    <span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Name is found </span><span class="dl">"</span> <span class="o">+</span> <span class="nx">data</span><span class="p">.</span><span class="nx">Name</span><span class="p">);</span>
  <span class="p">}</span> <span class="k">else</span> <span class="p">{</span>
    <span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">No Global Session Found</span><span class="dl">"</span><span class="p">);</span>
    <span class="nx">setGlobalSessionCookie</span><span class="p">(</span><span class="kc">false</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">});</span>

<span class="kd">function</span> <span class="nx">log</span><span class="p">(</span><span class="nx">text</span><span class="p">)</span> <span class="p">{</span>
  <span class="k">if</span> <span class="p">(</span><span class="nb">window</span><span class="p">.</span><span class="nx">console</span><span class="p">)</span> <span class="p">{</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">INFO: </span><span class="dl">"</span> <span class="o">+</span> <span class="nx">text</span><span class="p">);</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>I also learned the localStorage is based on the domain, so if you are going to be reading from secure pages make sure that you store and read from https domain because localStorage is different for secure and unsecure domains.</p>

<h3 id="and-there-you-have-it">And there you have it.</h3>

<p>Now you know how cross domain storage/communication is achieved with modern browsers. Let me know if you have any questions, and of course feedback is always greatly appreciated!</p>

<p>Cheers</p>


										
					<p>Posted in: dom</p>
						
				
					<p>Tagged with: cross-domain, html5, and authentication</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/dom/html5-localstorage-3rd-party-storage-iframe/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/dom/html5-localstorage-3rd-party-storage-iframe/]]></guid>
		<pubDate>2012-03-07T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Favorite posts and videos]]></title>
		<description>
			<![CDATA[
				<p><a href="http://www.infoq.com/presentations/Simple-Made-Easy">Simple Made Easy</a> by Rich Hickey.<br />
Rich Hickey is one of the most thoughful people I know and his talks are full of wisdom any programmer can appreciate.</p>

<p><a href="http://blog.stevensanderson.com/2007/11/29/linq-to-sql-the-multi-tier-story/">LINQ-to-SQL: the multi-tier story story</a> by Steven Sanderson.<br />
This is a great post on how to manage lifecycle of your Linq-to-SQL DataContext in the layered architecture using Unit of Work pattern and HttpContext.Current.Items -</p>

<p><a href="http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx">Truly Understanding Viewstate</a> by Dave Reed - a must read for any Web Forms developer</p>

<p><a href="http://channel9.msdn.com/Events/TechDays/Techdays-2012-the-Netherlands/2159">A must watch: Single Page Application Presentations</a> by Steven Sanderson</p>

<p><a href="http://blog.stevensanderson.com/2009/11/04/selective-unit-testing-costs-and-benefits/">Selective Unit Testing – Costs and Benefits</a> by Steven Sanderson</p>


				<p><a href="http://www.infoq.com/presentations/Simple-Made-Easy">Simple Made Easy</a> by Rich Hickey.<br />
Rich Hickey is one of the most thoughful people I know and his talks are full of wisdom any programmer can appreciate.</p>

<p><a href="http://blog.stevensanderson.com/2007/11/29/linq-to-sql-the-multi-tier-story/">LINQ-to-SQL: the multi-tier story story</a> by Steven Sanderson.<br />
This is a great post on how to manage lifecycle of your Linq-to-SQL DataContext in the layered architecture using Unit of Work pattern and HttpContext.Current.Items -</p>

<p><a href="http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx">Truly Understanding Viewstate</a> by Dave Reed - a must read for any Web Forms developer</p>

<p><a href="http://channel9.msdn.com/Events/TechDays/Techdays-2012-the-Netherlands/2159">A must watch: Single Page Application Presentations</a> by Steven Sanderson</p>

<p><a href="http://blog.stevensanderson.com/2009/11/04/selective-unit-testing-costs-and-benefits/">Selective Unit Testing – Costs and Benefits</a> by Steven Sanderson</p>


										
					<p>Posted in: favorites</p>
						
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/favorites/blog-posts/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/favorites/blog-posts/]]></guid>
		<pubDate>2012-03-06T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Startup Weekend Los Angeles February 2012 Review]]></title>
		<description>
			<![CDATA[
				<p>If you are like me who’d rather work on your own company than come to work. Who has a lot of side projects that keep you up late at night. And you’ve read books on startups and have many more that you want to read, I think you need to know about startup weekends! Why? because I think you have been missing out on a lot of fun and opportunities to connect with people like you are.</p>

<p>For about a month right before the startup weekend I had to work 60-hour work weeks  to make this ridiculous deadline at my current day job. I was actually thinking of not going since I was pretty tired. But I sucked it up and drove to Santa Monica on Friday night to join my coworker and about another 100 hungry for success people. It took place at the <a href="http://coloft.com/">Coloft</a>, when I got there it was packed with people. Most were drinking beers from a couple of kegs and socializing. Few people came by and introduced themselves and pitched their idea, that was actually kinda interesting to hear their ideas and pick their brain.</p>

<p>After dinner and beer there were few short presentations from facilitators about the whole process, and then they asked people to raise hands who wanted to pitch their idea. I think at first I only saw close to 1/4 of hands raised, I think most people got scared because when the second time they asked I saw more hands. It ended up being about 35 pitches. Each pitch was 60 seconds with no questions and at the end you were given a cup with your name, (oh yea and when you got there they gave you two tickets to vote for the idea that you liked). When I was pitching my idea I had a lot of adrenaline going. When it was over it was an awesome feeling! I actually wanted to do it again. After pitches it turned into chaos, everyone was walking around asking questions and voting for people. I think I had to repeat my idea like 10 times to different people. One nice lady voted for my idea, it was a great feeling lol! I voted for my friend’s idea and he got few other people interested so it was picked as one of 14 ideas.</p>

<p>After people’s ideas got picked, second round of chaos started. Picking team members was not easy. I think we were desperately looking for designer at first. I’ve solicited a couple but they ended up on other more persuasive teams. We were fortunate to end up with a great team of 5 total: two developers, two business people and one finance/database guy.</p>

<p>I think after we got our table we got straight to work. It kinda reminded me of Apprentice TV reality show at the beginning. I remember going back home at 12AM being exhausted not sure what to expect from this weekend, with some nervousness if I could last another two days with no rest.</p>

<p>On Saturday morning we got together around 9 am and started breaking down the work and figuring out minimal viable product. I’ve started setting up webserver, source control, database and I remember I was having issues with my two firewalls and ftp, and wasted a good hour on it. It was kinda stressful since we only had like one day to get things done. I think we had a lot of ups and downs on the first day, it got pretty close to almost quitting until we figured out that we can use one of the sponsors APIs (<a href="http://www.factual.com/">Factual</a>) for data instead of the data that was not publicly available. I think when we started coding it was already 2PM which was extremely stressful on it’s own. It was cool to see everyone around really working hard on their projects. The energy in the Coloft was amazing, we constantly had sponsors come up and asking if we needed any help, which was very nice of them.</p>

<p>This is what morning looked like…
<img src="/uploads/12-02/morning.JPG" alt="Morning Startup Weekend" /></p>

<p>Everything was provided , we had breakfast, lunch, dinner, drinks, energy drinks and all kinds of other goodies. Factual gave away hacky sacks. And during the day to relieve some stress we’ve stepped out outside to enjoy the beautiful beach weather and hit up the sack. I think I was very stressed and after the 20 minute game it was all gone, I had a new flow of energy and ready to finish the Saturday strong. We called it a day after 11PM, at that time we had 2 APIs, one from Yelp and other from Factual integrated, a lot of good ideas and content for presentation.</p>

<p>Sunday was mostly about bug fixes and styling. I realized how much I suck at css, it was very frustrating to positing things, luckily, Aurelio, other developer was great at it and took care of most styling. A night before Coloft crew showed us a quick youtube video from Glengarry Glen Ross where Alec Baldwin gives this ball breaking speech with legendary quote “Coffee is for closers”</p>

<iframe width="500" height="315" src="http://www.youtube.com/embed/y-AXTx4PcKI" frameborder="0" allowfullscreen=""></iframe>

<p>One of our team members stepped out during lunch to close! He got back with some encouraging results, he closed 6 restaurants out of 10 he visited. We were all pumped up, we had a minimal viable product we had closed accounts we were all set!</p>

<p>I think when the time came to presentations I was more relaxed than before, it was time for our business dev team members to shine giving presentations. Overall I was very happy with what we have achieved. We didn’t win the first place but we did get some interest from incubator sponsors and overall a lot of people were telling us that they’ve liked our project. The weekend in itself was a lot of fun, it did not feel like work or a chore at all. Oh yea and we won Factual’s developers challenge!! That was awesome in itself. It was an extremely satisfying weekend. I left with this renewed confidence that it is possible to succeed as long as you work hard and have same minded people along with you on. Plus I met a lot of good people and discovered a sweet place like Coloft where you can gather with your team and kick ass.</p>

<p>Coming to work on Monday was not hard at all, surprisingly I was not tired at all and full of startup weekend energy!!! I have one advice, don’t let the day job drag you down, keep working on your projects, get together with people like you and no doubt you will succeed. Good luck!</p>

<p>P.S. We are continuing our project after the weekend, which is exciting on it’s own. I will update on progress in the future posts.</p>


				<p>If you are like me who’d rather work on your own company than come to work. Who has a lot of side projects that keep you up late at night. And you’ve read books on startups and have many more that you want to read, I think you need to know about startup weekends! Why? because I think you have been missing out on a lot of fun and opportunities to connect with people like you are.</p>

<p>For about a month right before the startup weekend I had to work 60-hour work weeks  to make this ridiculous deadline at my current day job. I was actually thinking of not going since I was pretty tired. But I sucked it up and drove to Santa Monica on Friday night to join my coworker and about another 100 hungry for success people. It took place at the <a href="http://coloft.com/">Coloft</a>, when I got there it was packed with people. Most were drinking beers from a couple of kegs and socializing. Few people came by and introduced themselves and pitched their idea, that was actually kinda interesting to hear their ideas and pick their brain.</p>

<p>After dinner and beer there were few short presentations from facilitators about the whole process, and then they asked people to raise hands who wanted to pitch their idea. I think at first I only saw close to 1/4 of hands raised, I think most people got scared because when the second time they asked I saw more hands. It ended up being about 35 pitches. Each pitch was 60 seconds with no questions and at the end you were given a cup with your name, (oh yea and when you got there they gave you two tickets to vote for the idea that you liked). When I was pitching my idea I had a lot of adrenaline going. When it was over it was an awesome feeling! I actually wanted to do it again. After pitches it turned into chaos, everyone was walking around asking questions and voting for people. I think I had to repeat my idea like 10 times to different people. One nice lady voted for my idea, it was a great feeling lol! I voted for my friend’s idea and he got few other people interested so it was picked as one of 14 ideas.</p>

<p>After people’s ideas got picked, second round of chaos started. Picking team members was not easy. I think we were desperately looking for designer at first. I’ve solicited a couple but they ended up on other more persuasive teams. We were fortunate to end up with a great team of 5 total: two developers, two business people and one finance/database guy.</p>

<p>I think after we got our table we got straight to work. It kinda reminded me of Apprentice TV reality show at the beginning. I remember going back home at 12AM being exhausted not sure what to expect from this weekend, with some nervousness if I could last another two days with no rest.</p>

<p>On Saturday morning we got together around 9 am and started breaking down the work and figuring out minimal viable product. I’ve started setting up webserver, source control, database and I remember I was having issues with my two firewalls and ftp, and wasted a good hour on it. It was kinda stressful since we only had like one day to get things done. I think we had a lot of ups and downs on the first day, it got pretty close to almost quitting until we figured out that we can use one of the sponsors APIs (<a href="http://www.factual.com/">Factual</a>) for data instead of the data that was not publicly available. I think when we started coding it was already 2PM which was extremely stressful on it’s own. It was cool to see everyone around really working hard on their projects. The energy in the Coloft was amazing, we constantly had sponsors come up and asking if we needed any help, which was very nice of them.</p>

<p>This is what morning looked like…
<img src="/uploads/12-02/morning.JPG" alt="Morning Startup Weekend" /></p>

<p>Everything was provided , we had breakfast, lunch, dinner, drinks, energy drinks and all kinds of other goodies. Factual gave away hacky sacks. And during the day to relieve some stress we’ve stepped out outside to enjoy the beautiful beach weather and hit up the sack. I think I was very stressed and after the 20 minute game it was all gone, I had a new flow of energy and ready to finish the Saturday strong. We called it a day after 11PM, at that time we had 2 APIs, one from Yelp and other from Factual integrated, a lot of good ideas and content for presentation.</p>

<p>Sunday was mostly about bug fixes and styling. I realized how much I suck at css, it was very frustrating to positing things, luckily, Aurelio, other developer was great at it and took care of most styling. A night before Coloft crew showed us a quick youtube video from Glengarry Glen Ross where Alec Baldwin gives this ball breaking speech with legendary quote “Coffee is for closers”</p>

<iframe width="500" height="315" src="http://www.youtube.com/embed/y-AXTx4PcKI" frameborder="0" allowfullscreen=""></iframe>

<p>One of our team members stepped out during lunch to close! He got back with some encouraging results, he closed 6 restaurants out of 10 he visited. We were all pumped up, we had a minimal viable product we had closed accounts we were all set!</p>

<p>I think when the time came to presentations I was more relaxed than before, it was time for our business dev team members to shine giving presentations. Overall I was very happy with what we have achieved. We didn’t win the first place but we did get some interest from incubator sponsors and overall a lot of people were telling us that they’ve liked our project. The weekend in itself was a lot of fun, it did not feel like work or a chore at all. Oh yea and we won Factual’s developers challenge!! That was awesome in itself. It was an extremely satisfying weekend. I left with this renewed confidence that it is possible to succeed as long as you work hard and have same minded people along with you on. Plus I met a lot of good people and discovered a sweet place like Coloft where you can gather with your team and kick ass.</p>

<p>Coming to work on Monday was not hard at all, surprisingly I was not tired at all and full of startup weekend energy!!! I have one advice, don’t let the day job drag you down, keep working on your projects, get together with people like you and no doubt you will succeed. Good luck!</p>

<p>P.S. We are continuing our project after the weekend, which is exciting on it’s own. I will update on progress in the future posts.</p>


										
					<p>Posted in: startup</p>
						
				
					<p>Tagged with: startup-weekend</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/startup/startup-weekend-los-angeles-february-2012/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/startup/startup-weekend-los-angeles-february-2012/]]></guid>
		<pubDate>2012-02-28T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Sprinkle some design into ASP.NET User Controls]]></title>
		<description>
			<![CDATA[
				<p>We don’t always get to work on the cool stuff like ASP.NET MVC. So for those unfortunate ones we’ll explore some things that can make ASP.NET User Controls follow some patterns and in the end make Web Forms world a better place :)</p>

<p>In ASP.NET, User Controls if designed properly, can play a role of reusable UI components and decrease number of code and markup. It should also make your web project easier to maintain by centralizing code in one location.</p>

<h3 id="parent-page-contract">Parent Page Contract</h3>

<p>I think the most important and challenging task that developer faces when building a user control is to make it independent from the page. For simple controls that don’t require any input or don’t communicate with the page that job is extremely easy.</p>

<p><strong>Traditional way:</strong></p>

<p>On the other hand, most of the controls that we build will require some kind of input from the page. The easiest way is to make a public property on the control and have page set it like so:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">SimpleControl</span> <span class="p">:</span> <span class="n">UserControl</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="kt">int</span> <span class="n">MaximumResults</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">protected</span> <span class="k">void</span> <span class="nf">Page_Load</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">MaximumResults</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span>
        <span class="p">{</span>
            <span class="n">litResults</span><span class="p">.</span><span class="n">Text</span> <span class="p">+=</span> <span class="n">i</span><span class="p">.</span><span class="nf">ToString</span><span class="p">();</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And set it on the page:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">Default</span> <span class="p">:</span> <span class="n">Page</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">OnLoad</span><span class="p">(</span><span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">ctlSimpleControl</span><span class="p">.</span><span class="n">MaximumResults</span> <span class="p">=</span> <span class="m">5</span><span class="p">;</span>
        <span class="k">base</span><span class="p">.</span><span class="nf">OnLoad</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>There is one problem with this, the control requires you to supply that maximum results number and if some other developer than you tries to use this control he will have to read through the code, which won’t be as simple as above and figure out what properties it needs to set. We can improve the situation a little by throwing an exception during OnLoad</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">protected</span> <span class="k">void</span> <span class="nf">Page_Load</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span><span class="p">(</span><span class="n">MaximumResults</span> <span class="p">==</span> <span class="m">0</span><span class="p">)</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nf">ConfigurationErrorsException</span><span class="p">(</span><span class="s">"Missing maximum results"</span><span class="p">);</span>
</code></pre></div></div>

<p><strong>Programming to an interface:</strong></p>

<p>Another was it to create a “contract” between page and user control, so if anyone wants to use the user control they must implement an interface on the page.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">interface</span> <span class="nc">ISimpleControl</span>
<span class="p">{</span>
    <span class="kt">int</span> <span class="n">MaximumResults</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="kt">int</span> <span class="n">Heigh</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="kt">int</span> <span class="n">Width</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And our user control will communicate with the parent page through that interface, and throw exception if interface is not implemented.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">BetterControl</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Web</span><span class="p">.</span><span class="n">UI</span><span class="p">.</span><span class="n">UserControl</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="n">IBetterControl</span> <span class="n">PageContract</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">protected</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">OnLoad</span><span class="p">(</span><span class="n">EventArgs</span> <span class="n">eventArgs</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">PageContract</span> <span class="p">=</span> <span class="n">Page</span> <span class="k">as</span> <span class="n">IBetterControl</span><span class="p">;</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">PageContract</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nf">Exception</span><span class="p">(</span><span class="s">"Parent page does not implement IBetterControl interface"</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">PageContract</span><span class="p">.</span><span class="n">MaximumResults</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span>
        <span class="p">{</span>
            <span class="n">litResults</span><span class="p">.</span><span class="n">Text</span> <span class="p">+=</span> <span class="n">i</span><span class="p">.</span><span class="nf">ToString</span><span class="p">();</span>
        <span class="p">}</span>
        <span class="k">base</span><span class="p">.</span><span class="nf">OnLoad</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Now if another developer slaps your control on the page without implementing an interface he will get an exception which will let him know what he needs to implement in order for this control to properly work. Like so:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">BetterPage</span> <span class="p">:</span> <span class="n">Page</span><span class="p">,</span> <span class="n">IBetterControl</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="kt">int</span> <span class="n">MaximumResults</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">int</span> <span class="n">Heigh</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">int</span> <span class="n">Width</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>

    <span class="k">protected</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">OnLoad</span><span class="p">(</span><span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">MaximumResults</span> <span class="p">=</span> <span class="m">4</span><span class="p">;</span>
        <span class="k">base</span><span class="p">.</span><span class="nf">OnLoad</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This way if user intentionally leaves a 0 for MaximumResults property, User Control will work as intended.</p>

<h3 id="exposing-events-in-your-user-control">Exposing events in your user control.</h3>

<p>Let’s say your user control is doing account authentication, it’s always nice if it provides an event to which a parent page can subscribe and act. For example when user successfully authenticates page would execute a method which will redirect to some other page. That way your User Control stays independent from implementation and does only one thing that it meant to do.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">event</span> <span class="n">EventHandler</span> <span class="n">SuccessfulLogin</span><span class="p">;</span>
<span class="k">protected</span> <span class="k">void</span> <span class="nf">OnLoginButtonClick</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span><span class="p">(</span><span class="n">txtUsername</span><span class="p">.</span><span class="n">Text</span> <span class="p">==</span> <span class="s">"user"</span> <span class="p">&amp;&amp;</span> <span class="n">txtPassword</span><span class="p">.</span><span class="n">Text</span> <span class="p">==</span> <span class="s">"password"</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">FormsAuthentication</span><span class="p">.</span><span class="nf">SetAuthCookie</span><span class="p">(</span><span class="s">"user"</span><span class="p">,</span><span class="k">true</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">SuccessfulLogin</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
            <span class="nf">SuccessfulLogin</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="n">EventArgs</span><span class="p">.</span><span class="n">Empty</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Subscribing:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;uc:LoginControl runat="server" OnSuccessfulLogin="OnSuccessfulLogin"&gt;&lt;/uc:LoginControl&gt;
</code></pre></div></div>

<p>And implementing on page</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">Login</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Web</span><span class="p">.</span><span class="n">UI</span><span class="p">.</span><span class="n">Page</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="k">void</span> <span class="nf">OnSuccessfulLogin</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">Response</span><span class="p">.</span><span class="nf">Redirect</span><span class="p">(</span><span class="n">FormsAuthentication</span><span class="p">.</span><span class="n">DefaultUrl</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>You can also create a method in the interface similar to the first part with properties. And that’s fine if you must force a page to execute some method. If the event is optional then I think eventhandlers are the way to go.</p>

<h3 id="other-thoughts">Other thoughts:</h3>

<h4 id="keep-it-simple">Keep it simple</h4>

<p>On a general note, it’s better to keep user controls simple. If your complexity grows and you get lost in settings that your control requires, it’s probably a good time to rethink your design and split some of the code into a page or another user control.</p>

<h4 id="put-code-behind-into-separate-libraries">Put code behind into separate libraries</h4>

<p>If you are going to be sharing code between projects. It’s a good idea to put code behind into a separate code project, that way if any of the logic changes it will impact all projects.</p>

<h4 id="create-an-internal-nuget-package">Create an internal NuGet package</h4>

<p>This is definitely a nice way to publish your user control markup and make it updatable with one simple command.</p>

<p><a href="http://docs.nuget.org/docs/creating-packages/creating-and-publishing-a-package">NuGet Creating Packages</a></p>

<h4 id="embed-your-javascript-as-webresource">Embed your javascript as webresource</h4>

<p>If you have a javascript on your user control with some logic, it would not be a bad idea to move that javascript into a code library and make it a webresource. That way javascript code is also centralized and easier to maintain.</p>

<p><a href="http://msdn.microsoft.com/en-us/library/bb398930.aspx">Walkthrough: Embedding a JavaScript File as a Resource in an Assembly</a></p>

<h4 id="minimize-your-controls-viewstate">Minimize your control’s viewstate.</h4>

<p>There is an awesome article that can help you do that here:</p>

<p><a href="http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx">TRULY UNDERSTANDING VIEWSTATE</a></p>

<p>Let me know what you think, or if you have some other ideas please share!</p>

<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.maskalik.com%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.maskalik.com%2f" alt="kick it on DotNetKicks.com" /></a></p>


				<p>We don’t always get to work on the cool stuff like ASP.NET MVC. So for those unfortunate ones we’ll explore some things that can make ASP.NET User Controls follow some patterns and in the end make Web Forms world a better place :)</p>

<p>In ASP.NET, User Controls if designed properly, can play a role of reusable UI components and decrease number of code and markup. It should also make your web project easier to maintain by centralizing code in one location.</p>

<h3 id="parent-page-contract">Parent Page Contract</h3>

<p>I think the most important and challenging task that developer faces when building a user control is to make it independent from the page. For simple controls that don’t require any input or don’t communicate with the page that job is extremely easy.</p>

<p><strong>Traditional way:</strong></p>

<p>On the other hand, most of the controls that we build will require some kind of input from the page. The easiest way is to make a public property on the control and have page set it like so:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">SimpleControl</span> <span class="p">:</span> <span class="n">UserControl</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="kt">int</span> <span class="n">MaximumResults</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">protected</span> <span class="k">void</span> <span class="nf">Page_Load</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">MaximumResults</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span>
        <span class="p">{</span>
            <span class="n">litResults</span><span class="p">.</span><span class="n">Text</span> <span class="p">+=</span> <span class="n">i</span><span class="p">.</span><span class="nf">ToString</span><span class="p">();</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And set it on the page:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">Default</span> <span class="p">:</span> <span class="n">Page</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">OnLoad</span><span class="p">(</span><span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">ctlSimpleControl</span><span class="p">.</span><span class="n">MaximumResults</span> <span class="p">=</span> <span class="m">5</span><span class="p">;</span>
        <span class="k">base</span><span class="p">.</span><span class="nf">OnLoad</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>There is one problem with this, the control requires you to supply that maximum results number and if some other developer than you tries to use this control he will have to read through the code, which won’t be as simple as above and figure out what properties it needs to set. We can improve the situation a little by throwing an exception during OnLoad</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">protected</span> <span class="k">void</span> <span class="nf">Page_Load</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span><span class="p">(</span><span class="n">MaximumResults</span> <span class="p">==</span> <span class="m">0</span><span class="p">)</span>
        <span class="k">throw</span> <span class="k">new</span> <span class="nf">ConfigurationErrorsException</span><span class="p">(</span><span class="s">"Missing maximum results"</span><span class="p">);</span>
</code></pre></div></div>

<p><strong>Programming to an interface:</strong></p>

<p>Another was it to create a “contract” between page and user control, so if anyone wants to use the user control they must implement an interface on the page.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">interface</span> <span class="nc">ISimpleControl</span>
<span class="p">{</span>
    <span class="kt">int</span> <span class="n">MaximumResults</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="kt">int</span> <span class="n">Heigh</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="kt">int</span> <span class="n">Width</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>And our user control will communicate with the parent page through that interface, and throw exception if interface is not implemented.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">BetterControl</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Web</span><span class="p">.</span><span class="n">UI</span><span class="p">.</span><span class="n">UserControl</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="n">IBetterControl</span> <span class="n">PageContract</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">protected</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">OnLoad</span><span class="p">(</span><span class="n">EventArgs</span> <span class="n">eventArgs</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">PageContract</span> <span class="p">=</span> <span class="n">Page</span> <span class="k">as</span> <span class="n">IBetterControl</span><span class="p">;</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">PageContract</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span>
        <span class="p">{</span>
            <span class="k">throw</span> <span class="k">new</span> <span class="nf">Exception</span><span class="p">(</span><span class="s">"Parent page does not implement IBetterControl interface"</span><span class="p">);</span>
        <span class="p">}</span>

        <span class="k">for</span> <span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">PageContract</span><span class="p">.</span><span class="n">MaximumResults</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span>
        <span class="p">{</span>
            <span class="n">litResults</span><span class="p">.</span><span class="n">Text</span> <span class="p">+=</span> <span class="n">i</span><span class="p">.</span><span class="nf">ToString</span><span class="p">();</span>
        <span class="p">}</span>
        <span class="k">base</span><span class="p">.</span><span class="nf">OnLoad</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Now if another developer slaps your control on the page without implementing an interface he will get an exception which will let him know what he needs to implement in order for this control to properly work. Like so:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">BetterPage</span> <span class="p">:</span> <span class="n">Page</span><span class="p">,</span> <span class="n">IBetterControl</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="kt">int</span> <span class="n">MaximumResults</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">int</span> <span class="n">Heigh</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
    <span class="k">public</span> <span class="kt">int</span> <span class="n">Width</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>

    <span class="k">protected</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">OnLoad</span><span class="p">(</span><span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">MaximumResults</span> <span class="p">=</span> <span class="m">4</span><span class="p">;</span>
        <span class="k">base</span><span class="p">.</span><span class="nf">OnLoad</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This way if user intentionally leaves a 0 for MaximumResults property, User Control will work as intended.</p>

<h3 id="exposing-events-in-your-user-control">Exposing events in your user control.</h3>

<p>Let’s say your user control is doing account authentication, it’s always nice if it provides an event to which a parent page can subscribe and act. For example when user successfully authenticates page would execute a method which will redirect to some other page. That way your User Control stays independent from implementation and does only one thing that it meant to do.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">event</span> <span class="n">EventHandler</span> <span class="n">SuccessfulLogin</span><span class="p">;</span>
<span class="k">protected</span> <span class="k">void</span> <span class="nf">OnLoginButtonClick</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">if</span><span class="p">(</span><span class="n">txtUsername</span><span class="p">.</span><span class="n">Text</span> <span class="p">==</span> <span class="s">"user"</span> <span class="p">&amp;&amp;</span> <span class="n">txtPassword</span><span class="p">.</span><span class="n">Text</span> <span class="p">==</span> <span class="s">"password"</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">FormsAuthentication</span><span class="p">.</span><span class="nf">SetAuthCookie</span><span class="p">(</span><span class="s">"user"</span><span class="p">,</span><span class="k">true</span><span class="p">);</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">SuccessfulLogin</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
            <span class="nf">SuccessfulLogin</span><span class="p">(</span><span class="k">this</span><span class="p">,</span> <span class="n">EventArgs</span><span class="p">.</span><span class="n">Empty</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Subscribing:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;uc:LoginControl runat="server" OnSuccessfulLogin="OnSuccessfulLogin"&gt;&lt;/uc:LoginControl&gt;
</code></pre></div></div>

<p>And implementing on page</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">Login</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Web</span><span class="p">.</span><span class="n">UI</span><span class="p">.</span><span class="n">Page</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="k">void</span> <span class="nf">OnSuccessfulLogin</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">Response</span><span class="p">.</span><span class="nf">Redirect</span><span class="p">(</span><span class="n">FormsAuthentication</span><span class="p">.</span><span class="n">DefaultUrl</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>You can also create a method in the interface similar to the first part with properties. And that’s fine if you must force a page to execute some method. If the event is optional then I think eventhandlers are the way to go.</p>

<h3 id="other-thoughts">Other thoughts:</h3>

<h4 id="keep-it-simple">Keep it simple</h4>

<p>On a general note, it’s better to keep user controls simple. If your complexity grows and you get lost in settings that your control requires, it’s probably a good time to rethink your design and split some of the code into a page or another user control.</p>

<h4 id="put-code-behind-into-separate-libraries">Put code behind into separate libraries</h4>

<p>If you are going to be sharing code between projects. It’s a good idea to put code behind into a separate code project, that way if any of the logic changes it will impact all projects.</p>

<h4 id="create-an-internal-nuget-package">Create an internal NuGet package</h4>

<p>This is definitely a nice way to publish your user control markup and make it updatable with one simple command.</p>

<p><a href="http://docs.nuget.org/docs/creating-packages/creating-and-publishing-a-package">NuGet Creating Packages</a></p>

<h4 id="embed-your-javascript-as-webresource">Embed your javascript as webresource</h4>

<p>If you have a javascript on your user control with some logic, it would not be a bad idea to move that javascript into a code library and make it a webresource. That way javascript code is also centralized and easier to maintain.</p>

<p><a href="http://msdn.microsoft.com/en-us/library/bb398930.aspx">Walkthrough: Embedding a JavaScript File as a Resource in an Assembly</a></p>

<h4 id="minimize-your-controls-viewstate">Minimize your control’s viewstate.</h4>

<p>There is an awesome article that can help you do that here:</p>

<p><a href="http://weblogs.asp.net/infinitiesloop/archive/2006/08/03/Truly-Understanding-Viewstate.aspx">TRULY UNDERSTANDING VIEWSTATE</a></p>

<p>Let me know what you think, or if you have some other ideas please share!</p>

<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.maskalik.com%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.maskalik.com%2f" alt="kick it on DotNetKicks.com" /></a></p>


										
					<p>Posted in: asp.net</p>
						
				
					<p>Tagged with: asp.net, patterns, and user-control</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/asp-net/user-controls-design-patterns/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/asp-net/user-controls-design-patterns/]]></guid>
		<pubDate>2012-02-20T00:00:00+00:00</pubDate>
	</item>

	<item>
		<title><![CDATA[Building persistent identity and secure authentication module in ASP.NET]]></title>
		<description>
			<![CDATA[
				<p>I think it’s awesome when sites allow you to stay logged in for long periods of time. As well as asking to re-login when I try to go to some pages where higher level security is needed like account or credit cart pages. It makes me feel warm and secure inside.</p>

<p>Currently one of such examples is Amazon. Once you I log in and lets say come back in few days it will still say a cheerful “Hello Sergey, we have recommendations for you!”, but if I try to go to account page it will ask me to relogin.</p>

<p>In this post I’d like to show how simple and straight forward it is to create “dual” sessions in ASP.NET. One long term not critical session which is always there and doesn’t require SSL, and another which is secure. And if you haven’t logged in for short amount of time will ask you to re-login.</p>

<p>First we have to look at how ASP.NET handles authentication. If you don’t have forms authentication enabled you turn it on like this in web.config</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;authentication</span> <span class="na">mode=</span><span class="s">"Forms"</span> <span class="nt">/&gt;</span>
</code></pre></div></div>

<p>By default asp.net binds a series of modules in the machine.config that fires depending on your configuration settings. So when the above statement is included it will first run a System.Web.Security.FormsAuthenticationModule on every request which will look if the authentication cookie is there. If cookie is not there default module creates an empty HttpContext.User. And if cookie exists it will decrypt value from the cookie and setup HttpContext.User with that information.</p>

<p>So that’s all nice and standard but how do we have two sessions and create a custom identity that will tell us non secure user information like name as well as keep track if user has a secure session.</p>

<p>Asp.net provides the following authentication extensibility points in order of execution:</p>

<ol>
  <li>HttpModules can subscribe to AuthenticateRequest event of the context</li>
  <li>In Global.asax Application_AuthenticateRequest method will get executed once the user identity has been validated.</li>
</ol>

<p>FormsAuthenticationModule will set a default identity if HttpContext.User in not set in one of those modules.</p>

<p>Let’s begin, first lets create a custom static helper class which will abstract SignIn functionality and creating of two sessions. We’ll call it CustomAuthentication.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">CustomAuthentication</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">SetAuthCookies</span><span class="p">(</span><span class="kt">string</span> <span class="n">userName</span><span class="p">,</span> <span class="kt">string</span> <span class="n">fullName</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="kt">var</span> <span class="n">context</span> <span class="p">=</span> <span class="n">HttpContext</span><span class="p">.</span><span class="n">Current</span><span class="p">;</span>

        <span class="n">FormsAuthenticationTicket</span> <span class="n">identityTicket</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">FormsAuthenticationTicket</span><span class="p">(</span><span class="m">1</span><span class="p">,</span> <span class="n">userName</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">.</span><span class="nf">AddDays</span><span class="p">(</span><span class="m">60</span><span class="p">),</span> <span class="k">true</span><span class="p">,</span> <span class="n">fullName</span><span class="p">);</span>
        <span class="kt">string</span> <span class="n">encryptedIdentityTicket</span> <span class="p">=</span> <span class="n">FormsAuthentication</span><span class="p">.</span><span class="nf">Encrypt</span><span class="p">(</span><span class="n">identityTicket</span><span class="p">);</span>
        <span class="kt">var</span> <span class="n">identityCookie</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">HttpCookie</span><span class="p">(</span><span class="s">"ASPXIDENT"</span><span class="p">,</span> <span class="n">encryptedIdentityTicket</span><span class="p">);</span>
        <span class="n">identityCookie</span><span class="p">.</span><span class="n">Expires</span> <span class="p">=</span> <span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">.</span><span class="nf">AddDays</span><span class="p">(</span><span class="m">60</span><span class="p">);</span>
        <span class="n">HttpContext</span><span class="p">.</span><span class="n">Current</span><span class="p">.</span><span class="n">Response</span><span class="p">.</span><span class="n">Cookies</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">identityCookie</span><span class="p">);</span>

        <span class="n">FormsAuthentication</span><span class="p">.</span><span class="nf">SetAuthCookie</span><span class="p">(</span><span class="n">userName</span><span class="p">,</span><span class="k">false</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>In this method we first create an “identity” cookie which is our long lived cookie, and not designed to be SSL secure but is still encrypted. It has additional data like full name of the person. And we also call regular FormsAuthentication.SetAuthCookie to create an authentication cookie which we set as secure in our web.config and will have 30 minutes expiration.</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;authentication</span> <span class="na">mode=</span><span class="s">"Forms"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;forms</span> <span class="na">loginUrl=</span><span class="s">"~/Account/Login.aspx"</span> <span class="na">timeout=</span><span class="s">"30"</span> <span class="na">requireSSL=</span><span class="s">"true"</span> <span class="nt">/&gt;</span>
<span class="nt">&lt;/authentication&gt;</span>
</code></pre></div></div>

<p>Ok so now on our login page if we call this method we’ll have 2 cookies created a default authentication and identity cookie.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">Login</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Web</span><span class="p">.</span><span class="n">UI</span><span class="p">.</span><span class="n">Page</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="k">void</span> <span class="nf">Page_Load</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">RegisterHyperLink</span><span class="p">.</span><span class="n">NavigateUrl</span> <span class="p">=</span> <span class="s">"Register.aspx?ReturnUrl="</span> <span class="p">+</span> <span class="n">HttpUtility</span><span class="p">.</span><span class="nf">UrlEncode</span><span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">QueryString</span><span class="p">[</span><span class="s">"ReturnUrl"</span><span class="p">]);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">void</span> <span class="nf">OnLoginClick</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">if</span><span class="p">(</span><span class="k">true</span><span class="p">)</span> <span class="c1">// this is where you would check if user is valid</span>
        <span class="p">{</span>
            <span class="n">CustomAuthentication</span><span class="p">.</span><span class="nf">SetAuthCookies</span><span class="p">(</span><span class="s">"mercury2269"</span><span class="p">,</span> <span class="s">"Sergey Maskalik"</span><span class="p">);</span>
            <span class="n">Response</span><span class="p">.</span><span class="nf">Redirect</span><span class="p">(</span><span class="s">"/"</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>
</code></pre></div></div>

<p>So now when we login we have two cookies one for identity and one for authentication. If you are going to be running a sample project, make sure you set up IIS Express to use ssl, which is pretty easy by clicking on the project name and pressing F4 to project properties and enabling SSL. The login page would not work otherwise.</p>

<p>When we login, we’ll now see two cookies:</p>

<p><img src="/uploads/12-02/custom_authenticaion_cookies.png" alt="Authentication Cookies" /></p>

<p>So, if we leave it right now we’ll have a generic identity which will expire in 30 minutes. But We want to override it with our own new born identity, so we’ll create a custom identity and HttpModule to get this done.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">CustomIdentity</span> <span class="p">:</span> <span class="n">GenericIdentity</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="kt">string</span> <span class="n">_fullName</span><span class="p">;</span>

    <span class="k">public</span> <span class="nf">CustomIdentity</span><span class="p">(</span><span class="kt">string</span> <span class="n">userName</span><span class="p">,</span> <span class="kt">string</span> <span class="n">fullName</span><span class="p">)</span> <span class="p">:</span> <span class="k">base</span> <span class="p">(</span><span class="n">userName</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">_fullName</span> <span class="p">=</span> <span class="n">fullName</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="kt">bool</span> <span class="n">HasIdentity</span>
    <span class="p">{</span>
        <span class="k">get</span> <span class="p">{</span> <span class="k">return</span> <span class="p">!</span><span class="kt">string</span><span class="p">.</span><span class="nf">IsNullOrWhiteSpace</span><span class="p">(</span><span class="n">_fullName</span><span class="p">);</span> <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="kt">string</span> <span class="n">FullName</span>
    <span class="p">{</span>
        <span class="k">get</span> <span class="p">{</span> <span class="k">return</span> <span class="n">_fullName</span><span class="p">;</span> <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">static</span> <span class="n">CustomIdentity</span> <span class="n">EmptyIdentity</span>
    <span class="p">{</span>
        <span class="k">get</span> <span class="p">{</span> <span class="k">return</span> <span class="k">new</span> <span class="nf">CustomIdentity</span><span class="p">(</span><span class="s">""</span><span class="p">,</span> <span class="s">""</span><span class="p">);</span> <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>We’ll reuse default established identity since that work is already done for us, and basically add two more properties which will say if current user has identity and if it has full name. And since identity cannot be null we’ll create a static helper property to return an empty identity.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">void</span> <span class="nf">OnAuthenticateRequest</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">string</span> <span class="n">identityCookieName</span> <span class="p">=</span> <span class="s">"ASPXIDENT"</span><span class="p">;</span>
    <span class="n">HttpApplication</span> <span class="n">app</span> <span class="p">=</span> <span class="p">(</span><span class="n">HttpApplication</span><span class="p">)</span><span class="n">sender</span><span class="p">;</span>

    <span class="c1">// Get the authentication cookie</span>
    <span class="n">HttpCookie</span> <span class="n">identityCookie</span> <span class="p">=</span> <span class="n">app</span><span class="p">.</span><span class="n">Context</span><span class="p">.</span><span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">[</span><span class="n">identityCookieName</span><span class="p">];</span>

    <span class="c1">// If the cookie can't be found don't issue custom authentication</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">identityCookie</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="c1">// decrypt identity ticket</span>
    <span class="n">FormsAuthenticationTicket</span> <span class="n">identityTicket</span> <span class="p">=</span> <span class="p">(</span><span class="n">FormsAuthenticationTicket</span><span class="p">)</span><span class="k">null</span><span class="p">;</span>
    <span class="k">try</span>
    <span class="p">{</span>
        <span class="n">identityTicket</span> <span class="p">=</span> <span class="n">FormsAuthentication</span><span class="p">.</span><span class="nf">Decrypt</span><span class="p">(</span><span class="n">identityCookie</span><span class="p">.</span><span class="n">Value</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">catch</span>
    <span class="p">{</span>
        <span class="n">app</span><span class="p">.</span><span class="n">Context</span><span class="p">.</span><span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">.</span><span class="nf">Remove</span><span class="p">(</span><span class="n">identityCookieName</span><span class="p">);</span>
        <span class="k">return</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="kt">string</span> <span class="n">name</span> <span class="p">=</span> <span class="s">""</span><span class="p">;</span>
    <span class="n">HttpCookie</span> <span class="n">authCookie</span> <span class="p">=</span> <span class="n">app</span><span class="p">.</span><span class="n">Context</span><span class="p">.</span><span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">[</span><span class="n">FormsAuthentication</span><span class="p">.</span><span class="n">FormsCookieName</span><span class="p">];</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">authCookie</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">try</span>
        <span class="p">{</span>
            <span class="n">FormsAuthenticationTicket</span> <span class="n">authTicket</span> <span class="p">=</span> <span class="n">FormsAuthentication</span><span class="p">.</span><span class="nf">Decrypt</span><span class="p">(</span><span class="n">authCookie</span><span class="p">.</span><span class="n">Value</span><span class="p">);</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">authTicket</span><span class="p">.</span><span class="n">Name</span> <span class="p">!=</span> <span class="n">identityTicket</span><span class="p">.</span><span class="n">Name</span><span class="p">)</span> <span class="k">return</span><span class="p">;</span>
            <span class="n">name</span> <span class="p">=</span> <span class="n">authTicket</span><span class="p">.</span><span class="n">Name</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="k">catch</span>
        <span class="p">{</span>
            <span class="n">app</span><span class="p">.</span><span class="n">Context</span><span class="p">.</span><span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">.</span><span class="nf">Remove</span><span class="p">(</span><span class="n">FormsAuthentication</span><span class="p">.</span><span class="n">FormsCookieName</span><span class="p">);</span>
            <span class="k">return</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="kt">var</span> <span class="n">customIdentity</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">CustomIdentity</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">identityTicket</span><span class="p">.</span><span class="n">UserData</span><span class="p">);</span>
    <span class="kt">var</span> <span class="n">userPrincipal</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">GenericPrincipal</span><span class="p">(</span><span class="n">customIdentity</span><span class="p">,</span> <span class="k">new</span> <span class="kt">string</span><span class="p">[</span><span class="m">0</span><span class="p">]);</span>
    <span class="n">app</span><span class="p">.</span><span class="n">Context</span><span class="p">.</span><span class="n">User</span> <span class="p">=</span> <span class="n">userPrincipal</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Ok so now when user is logged in we will have a custom identity set, which can be access on pages like so:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="n">CustomIdentity</span><span class="p">)</span><span class="n">HttpContext</span><span class="p">.</span><span class="n">Current</span><span class="p">.</span><span class="n">User</span><span class="p">.</span><span class="n">Identity</span>
</code></pre></div></div>

<p>We’ll create a helper method to abstract this for us and make it nice and tidy.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">IdentityHelper</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">static</span> <span class="n">CustomIdentity</span> <span class="n">CurrentUser</span>
    <span class="p">{</span>
        <span class="k">get</span>
        <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">HttpContext</span><span class="p">.</span><span class="n">Current</span><span class="p">.</span><span class="n">User</span><span class="p">.</span><span class="n">Identity</span> <span class="k">is</span> <span class="n">CustomIdentity</span><span class="p">)</span>
                <span class="k">return</span> <span class="p">(</span><span class="n">CustomIdentity</span><span class="p">)</span><span class="n">HttpContext</span><span class="p">.</span><span class="n">Current</span><span class="p">.</span><span class="n">User</span><span class="p">.</span><span class="n">Identity</span><span class="p">;</span>

            <span class="k">return</span> <span class="n">CustomIdentity</span><span class="p">.</span><span class="n">EmptyIdentity</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Now we’ll add module to web.config</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;system.webServer&gt;</span>
<span class="nt">&lt;modules</span> <span class="na">runAllManagedModulesForAllRequests=</span><span class="s">"true"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;add</span> <span class="na">name=</span><span class="s">"CustomAuthentication"</span> <span class="na">type=</span><span class="s">"CustomAuthenticationSample.Application.CustomAuthenticationModule, CustomAuthenticationSample"</span><span class="nt">/&gt;</span>
<span class="nt">&lt;/modules&gt;</span>
</code></pre></div></div>

<p>And that’s it! We can now access our new custom identity by simply calling our IdentityHelper class and make decisions based on it.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span><span class="p">(</span><span class="n">IdentityHelper</span><span class="p">.</span><span class="n">CurrentUser</span><span class="p">.</span><span class="n">HasIdentity</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">lblIdentityInfo</span><span class="p">.</span><span class="n">Text</span> <span class="p">=</span> <span class="s">"Whoo hoo User has identity, full name is: "</span> <span class="p">+</span> <span class="n">IdentityHelper</span><span class="p">.</span><span class="n">CurrentUser</span><span class="p">.</span><span class="n">FullName</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">if</span><span class="p">(</span><span class="n">IdentityHelper</span><span class="p">.</span><span class="n">CurrentUser</span><span class="p">.</span><span class="n">IsAuthenticated</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">lblIdentityInfo</span><span class="p">.</span><span class="n">Text</span> <span class="p">+=</span> <span class="s">"&lt;br /&gt;User has secure authentication session"</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Now when we login on secure page we’ll have
<img src="/uploads/12-02/https_identity.png" alt="secure pages" /></p>

<p>And if secure session is expired or not over https
<img src="/uploads/12-02/http_identity.png" alt="unsecure pages" /></p>

<p>So now we have a long lived session that will persist for 60 days and a secure session which will expire in 30 minutes.</p>

<p><strong>I’d like to hear your opinion and please post comments if you have any questions!</strong></p>

<p><a href="/uploads/12-02/CustomAuthenticationSample.zip">Project code sample</a></p>

<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.maskalik.com%2fasp-net%2fcustom-authentication-module"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.maskalik.com%2fasp-net%2fcustom-authentication-module" alt="kick it on DotNetKicks.com" /></a></p>


				<p>I think it’s awesome when sites allow you to stay logged in for long periods of time. As well as asking to re-login when I try to go to some pages where higher level security is needed like account or credit cart pages. It makes me feel warm and secure inside.</p>

<p>Currently one of such examples is Amazon. Once you I log in and lets say come back in few days it will still say a cheerful “Hello Sergey, we have recommendations for you!”, but if I try to go to account page it will ask me to relogin.</p>

<p>In this post I’d like to show how simple and straight forward it is to create “dual” sessions in ASP.NET. One long term not critical session which is always there and doesn’t require SSL, and another which is secure. And if you haven’t logged in for short amount of time will ask you to re-login.</p>

<p>First we have to look at how ASP.NET handles authentication. If you don’t have forms authentication enabled you turn it on like this in web.config</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;authentication</span> <span class="na">mode=</span><span class="s">"Forms"</span> <span class="nt">/&gt;</span>
</code></pre></div></div>

<p>By default asp.net binds a series of modules in the machine.config that fires depending on your configuration settings. So when the above statement is included it will first run a System.Web.Security.FormsAuthenticationModule on every request which will look if the authentication cookie is there. If cookie is not there default module creates an empty HttpContext.User. And if cookie exists it will decrypt value from the cookie and setup HttpContext.User with that information.</p>

<p>So that’s all nice and standard but how do we have two sessions and create a custom identity that will tell us non secure user information like name as well as keep track if user has a secure session.</p>

<p>Asp.net provides the following authentication extensibility points in order of execution:</p>

<ol>
  <li>HttpModules can subscribe to AuthenticateRequest event of the context</li>
  <li>In Global.asax Application_AuthenticateRequest method will get executed once the user identity has been validated.</li>
</ol>

<p>FormsAuthenticationModule will set a default identity if HttpContext.User in not set in one of those modules.</p>

<p>Let’s begin, first lets create a custom static helper class which will abstract SignIn functionality and creating of two sessions. We’ll call it CustomAuthentication.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">CustomAuthentication</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">SetAuthCookies</span><span class="p">(</span><span class="kt">string</span> <span class="n">userName</span><span class="p">,</span> <span class="kt">string</span> <span class="n">fullName</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="kt">var</span> <span class="n">context</span> <span class="p">=</span> <span class="n">HttpContext</span><span class="p">.</span><span class="n">Current</span><span class="p">;</span>

        <span class="n">FormsAuthenticationTicket</span> <span class="n">identityTicket</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">FormsAuthenticationTicket</span><span class="p">(</span><span class="m">1</span><span class="p">,</span> <span class="n">userName</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">,</span> <span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">.</span><span class="nf">AddDays</span><span class="p">(</span><span class="m">60</span><span class="p">),</span> <span class="k">true</span><span class="p">,</span> <span class="n">fullName</span><span class="p">);</span>
        <span class="kt">string</span> <span class="n">encryptedIdentityTicket</span> <span class="p">=</span> <span class="n">FormsAuthentication</span><span class="p">.</span><span class="nf">Encrypt</span><span class="p">(</span><span class="n">identityTicket</span><span class="p">);</span>
        <span class="kt">var</span> <span class="n">identityCookie</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">HttpCookie</span><span class="p">(</span><span class="s">"ASPXIDENT"</span><span class="p">,</span> <span class="n">encryptedIdentityTicket</span><span class="p">);</span>
        <span class="n">identityCookie</span><span class="p">.</span><span class="n">Expires</span> <span class="p">=</span> <span class="n">DateTime</span><span class="p">.</span><span class="n">Now</span><span class="p">.</span><span class="nf">AddDays</span><span class="p">(</span><span class="m">60</span><span class="p">);</span>
        <span class="n">HttpContext</span><span class="p">.</span><span class="n">Current</span><span class="p">.</span><span class="n">Response</span><span class="p">.</span><span class="n">Cookies</span><span class="p">.</span><span class="nf">Add</span><span class="p">(</span><span class="n">identityCookie</span><span class="p">);</span>

        <span class="n">FormsAuthentication</span><span class="p">.</span><span class="nf">SetAuthCookie</span><span class="p">(</span><span class="n">userName</span><span class="p">,</span><span class="k">false</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>In this method we first create an “identity” cookie which is our long lived cookie, and not designed to be SSL secure but is still encrypted. It has additional data like full name of the person. And we also call regular FormsAuthentication.SetAuthCookie to create an authentication cookie which we set as secure in our web.config and will have 30 minutes expiration.</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;authentication</span> <span class="na">mode=</span><span class="s">"Forms"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;forms</span> <span class="na">loginUrl=</span><span class="s">"~/Account/Login.aspx"</span> <span class="na">timeout=</span><span class="s">"30"</span> <span class="na">requireSSL=</span><span class="s">"true"</span> <span class="nt">/&gt;</span>
<span class="nt">&lt;/authentication&gt;</span>
</code></pre></div></div>

<p>Ok so now on our login page if we call this method we’ll have 2 cookies created a default authentication and identity cookie.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">partial</span> <span class="k">class</span> <span class="nc">Login</span> <span class="p">:</span> <span class="n">System</span><span class="p">.</span><span class="n">Web</span><span class="p">.</span><span class="n">UI</span><span class="p">.</span><span class="n">Page</span>
<span class="p">{</span>
    <span class="k">protected</span> <span class="k">void</span> <span class="nf">Page_Load</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">RegisterHyperLink</span><span class="p">.</span><span class="n">NavigateUrl</span> <span class="p">=</span> <span class="s">"Register.aspx?ReturnUrl="</span> <span class="p">+</span> <span class="n">HttpUtility</span><span class="p">.</span><span class="nf">UrlEncode</span><span class="p">(</span><span class="n">Request</span><span class="p">.</span><span class="n">QueryString</span><span class="p">[</span><span class="s">"ReturnUrl"</span><span class="p">]);</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">void</span> <span class="nf">OnLoginClick</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">if</span><span class="p">(</span><span class="k">true</span><span class="p">)</span> <span class="c1">// this is where you would check if user is valid</span>
        <span class="p">{</span>
            <span class="n">CustomAuthentication</span><span class="p">.</span><span class="nf">SetAuthCookies</span><span class="p">(</span><span class="s">"mercury2269"</span><span class="p">,</span> <span class="s">"Sergey Maskalik"</span><span class="p">);</span>
            <span class="n">Response</span><span class="p">.</span><span class="nf">Redirect</span><span class="p">(</span><span class="s">"/"</span><span class="p">);</span>
        <span class="p">}</span>
    <span class="p">}</span>
</code></pre></div></div>

<p>So now when we login we have two cookies one for identity and one for authentication. If you are going to be running a sample project, make sure you set up IIS Express to use ssl, which is pretty easy by clicking on the project name and pressing F4 to project properties and enabling SSL. The login page would not work otherwise.</p>

<p>When we login, we’ll now see two cookies:</p>

<p><img src="/uploads/12-02/custom_authenticaion_cookies.png" alt="Authentication Cookies" /></p>

<p>So, if we leave it right now we’ll have a generic identity which will expire in 30 minutes. But We want to override it with our own new born identity, so we’ll create a custom identity and HttpModule to get this done.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">CustomIdentity</span> <span class="p">:</span> <span class="n">GenericIdentity</span>
<span class="p">{</span>
    <span class="k">private</span> <span class="kt">string</span> <span class="n">_fullName</span><span class="p">;</span>

    <span class="k">public</span> <span class="nf">CustomIdentity</span><span class="p">(</span><span class="kt">string</span> <span class="n">userName</span><span class="p">,</span> <span class="kt">string</span> <span class="n">fullName</span><span class="p">)</span> <span class="p">:</span> <span class="k">base</span> <span class="p">(</span><span class="n">userName</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="n">_fullName</span> <span class="p">=</span> <span class="n">fullName</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="kt">bool</span> <span class="n">HasIdentity</span>
    <span class="p">{</span>
        <span class="k">get</span> <span class="p">{</span> <span class="k">return</span> <span class="p">!</span><span class="kt">string</span><span class="p">.</span><span class="nf">IsNullOrWhiteSpace</span><span class="p">(</span><span class="n">_fullName</span><span class="p">);</span> <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="kt">string</span> <span class="n">FullName</span>
    <span class="p">{</span>
        <span class="k">get</span> <span class="p">{</span> <span class="k">return</span> <span class="n">_fullName</span><span class="p">;</span> <span class="p">}</span>
    <span class="p">}</span>

    <span class="k">public</span> <span class="k">static</span> <span class="n">CustomIdentity</span> <span class="n">EmptyIdentity</span>
    <span class="p">{</span>
        <span class="k">get</span> <span class="p">{</span> <span class="k">return</span> <span class="k">new</span> <span class="nf">CustomIdentity</span><span class="p">(</span><span class="s">""</span><span class="p">,</span> <span class="s">""</span><span class="p">);</span> <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>We’ll reuse default established identity since that work is already done for us, and basically add two more properties which will say if current user has identity and if it has full name. And since identity cannot be null we’ll create a static helper property to return an empty identity.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">void</span> <span class="nf">OnAuthenticateRequest</span><span class="p">(</span><span class="kt">object</span> <span class="n">sender</span><span class="p">,</span> <span class="n">EventArgs</span> <span class="n">e</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">string</span> <span class="n">identityCookieName</span> <span class="p">=</span> <span class="s">"ASPXIDENT"</span><span class="p">;</span>
    <span class="n">HttpApplication</span> <span class="n">app</span> <span class="p">=</span> <span class="p">(</span><span class="n">HttpApplication</span><span class="p">)</span><span class="n">sender</span><span class="p">;</span>

    <span class="c1">// Get the authentication cookie</span>
    <span class="n">HttpCookie</span> <span class="n">identityCookie</span> <span class="p">=</span> <span class="n">app</span><span class="p">.</span><span class="n">Context</span><span class="p">.</span><span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">[</span><span class="n">identityCookieName</span><span class="p">];</span>

    <span class="c1">// If the cookie can't be found don't issue custom authentication</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">identityCookie</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span>
        <span class="k">return</span><span class="p">;</span>

    <span class="c1">// decrypt identity ticket</span>
    <span class="n">FormsAuthenticationTicket</span> <span class="n">identityTicket</span> <span class="p">=</span> <span class="p">(</span><span class="n">FormsAuthenticationTicket</span><span class="p">)</span><span class="k">null</span><span class="p">;</span>
    <span class="k">try</span>
    <span class="p">{</span>
        <span class="n">identityTicket</span> <span class="p">=</span> <span class="n">FormsAuthentication</span><span class="p">.</span><span class="nf">Decrypt</span><span class="p">(</span><span class="n">identityCookie</span><span class="p">.</span><span class="n">Value</span><span class="p">);</span>
    <span class="p">}</span>
    <span class="k">catch</span>
    <span class="p">{</span>
        <span class="n">app</span><span class="p">.</span><span class="n">Context</span><span class="p">.</span><span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">.</span><span class="nf">Remove</span><span class="p">(</span><span class="n">identityCookieName</span><span class="p">);</span>
        <span class="k">return</span><span class="p">;</span>
    <span class="p">}</span>

    <span class="kt">string</span> <span class="n">name</span> <span class="p">=</span> <span class="s">""</span><span class="p">;</span>
    <span class="n">HttpCookie</span> <span class="n">authCookie</span> <span class="p">=</span> <span class="n">app</span><span class="p">.</span><span class="n">Context</span><span class="p">.</span><span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">[</span><span class="n">FormsAuthentication</span><span class="p">.</span><span class="n">FormsCookieName</span><span class="p">];</span>
    <span class="k">if</span> <span class="p">(</span><span class="n">authCookie</span> <span class="p">!=</span> <span class="k">null</span><span class="p">)</span>
    <span class="p">{</span>
        <span class="k">try</span>
        <span class="p">{</span>
            <span class="n">FormsAuthenticationTicket</span> <span class="n">authTicket</span> <span class="p">=</span> <span class="n">FormsAuthentication</span><span class="p">.</span><span class="nf">Decrypt</span><span class="p">(</span><span class="n">authCookie</span><span class="p">.</span><span class="n">Value</span><span class="p">);</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">authTicket</span><span class="p">.</span><span class="n">Name</span> <span class="p">!=</span> <span class="n">identityTicket</span><span class="p">.</span><span class="n">Name</span><span class="p">)</span> <span class="k">return</span><span class="p">;</span>
            <span class="n">name</span> <span class="p">=</span> <span class="n">authTicket</span><span class="p">.</span><span class="n">Name</span><span class="p">;</span>
        <span class="p">}</span>
        <span class="k">catch</span>
        <span class="p">{</span>
            <span class="n">app</span><span class="p">.</span><span class="n">Context</span><span class="p">.</span><span class="n">Request</span><span class="p">.</span><span class="n">Cookies</span><span class="p">.</span><span class="nf">Remove</span><span class="p">(</span><span class="n">FormsAuthentication</span><span class="p">.</span><span class="n">FormsCookieName</span><span class="p">);</span>
            <span class="k">return</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>

    <span class="kt">var</span> <span class="n">customIdentity</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">CustomIdentity</span><span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">identityTicket</span><span class="p">.</span><span class="n">UserData</span><span class="p">);</span>
    <span class="kt">var</span> <span class="n">userPrincipal</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">GenericPrincipal</span><span class="p">(</span><span class="n">customIdentity</span><span class="p">,</span> <span class="k">new</span> <span class="kt">string</span><span class="p">[</span><span class="m">0</span><span class="p">]);</span>
    <span class="n">app</span><span class="p">.</span><span class="n">Context</span><span class="p">.</span><span class="n">User</span> <span class="p">=</span> <span class="n">userPrincipal</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Ok so now when user is logged in we will have a custom identity set, which can be access on pages like so:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="n">CustomIdentity</span><span class="p">)</span><span class="n">HttpContext</span><span class="p">.</span><span class="n">Current</span><span class="p">.</span><span class="n">User</span><span class="p">.</span><span class="n">Identity</span>
</code></pre></div></div>

<p>We’ll create a helper method to abstract this for us and make it nice and tidy.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">class</span> <span class="nc">IdentityHelper</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="k">static</span> <span class="n">CustomIdentity</span> <span class="n">CurrentUser</span>
    <span class="p">{</span>
        <span class="k">get</span>
        <span class="p">{</span>
            <span class="k">if</span> <span class="p">(</span><span class="n">HttpContext</span><span class="p">.</span><span class="n">Current</span><span class="p">.</span><span class="n">User</span><span class="p">.</span><span class="n">Identity</span> <span class="k">is</span> <span class="n">CustomIdentity</span><span class="p">)</span>
                <span class="k">return</span> <span class="p">(</span><span class="n">CustomIdentity</span><span class="p">)</span><span class="n">HttpContext</span><span class="p">.</span><span class="n">Current</span><span class="p">.</span><span class="n">User</span><span class="p">.</span><span class="n">Identity</span><span class="p">;</span>

            <span class="k">return</span> <span class="n">CustomIdentity</span><span class="p">.</span><span class="n">EmptyIdentity</span><span class="p">;</span>
        <span class="p">}</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Now we’ll add module to web.config</p>

<div class="language-xml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nt">&lt;system.webServer&gt;</span>
<span class="nt">&lt;modules</span> <span class="na">runAllManagedModulesForAllRequests=</span><span class="s">"true"</span><span class="nt">&gt;</span>
    <span class="nt">&lt;add</span> <span class="na">name=</span><span class="s">"CustomAuthentication"</span> <span class="na">type=</span><span class="s">"CustomAuthenticationSample.Application.CustomAuthenticationModule, CustomAuthenticationSample"</span><span class="nt">/&gt;</span>
<span class="nt">&lt;/modules&gt;</span>
</code></pre></div></div>

<p>And that’s it! We can now access our new custom identity by simply calling our IdentityHelper class and make decisions based on it.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span><span class="p">(</span><span class="n">IdentityHelper</span><span class="p">.</span><span class="n">CurrentUser</span><span class="p">.</span><span class="n">HasIdentity</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">lblIdentityInfo</span><span class="p">.</span><span class="n">Text</span> <span class="p">=</span> <span class="s">"Whoo hoo User has identity, full name is: "</span> <span class="p">+</span> <span class="n">IdentityHelper</span><span class="p">.</span><span class="n">CurrentUser</span><span class="p">.</span><span class="n">FullName</span><span class="p">;</span>
<span class="p">}</span>

<span class="k">if</span><span class="p">(</span><span class="n">IdentityHelper</span><span class="p">.</span><span class="n">CurrentUser</span><span class="p">.</span><span class="n">IsAuthenticated</span><span class="p">)</span>
<span class="p">{</span>
    <span class="n">lblIdentityInfo</span><span class="p">.</span><span class="n">Text</span> <span class="p">+=</span> <span class="s">"&lt;br /&gt;User has secure authentication session"</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Now when we login on secure page we’ll have
<img src="/uploads/12-02/https_identity.png" alt="secure pages" /></p>

<p>And if secure session is expired or not over https
<img src="/uploads/12-02/http_identity.png" alt="unsecure pages" /></p>

<p>So now we have a long lived session that will persist for 60 days and a secure session which will expire in 30 minutes.</p>

<p><strong>I’d like to hear your opinion and please post comments if you have any questions!</strong></p>

<p><a href="/uploads/12-02/CustomAuthenticationSample.zip">Project code sample</a></p>

<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fblog.maskalik.com%2fasp-net%2fcustom-authentication-module"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fblog.maskalik.com%2fasp-net%2fcustom-authentication-module" alt="kick it on DotNetKicks.com" /></a></p>


										
					<p>Posted in: asp.net</p>
						
				
					<p>Tagged with: asp.net, authentication, httpmodule, and iidentity</p>
						
			]]>
		</description>
		<link><![CDATA[https://blog.maskalik.com/asp-net/custom-authentication-module/]]></link>
		<author><![CDATA[Sergey Maskalik]]></author>
		<guid><![CDATA[/asp-net/custom-authentication-module/]]></guid>
		<pubDate>2011-12-18T00:00:00+00:00</pubDate>
	</item>


	</channel>
</rss>
