<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
  version="2.0">
  <channel>
    <title>Janne Mattila's blog</title>
    <atom:link
      href="https://docs.microsoft.com/archive/blogs/jannemattila/feed.xml"
      rel="self"
      type="application/rss+xml" />
    <link>https://docs.microsoft.com/archive/blogs/jannemattila/feed.xml</link>
    <description>From programmer to programmer -- Programming just for the fun of it</description>
    <lastBuildDate>Wed, 17 Apr 2019 04:00:56 GMT</lastBuildDate>
    <language>en-US</language>
    <sy:updatePeriod>hourly</sy:updatePeriod>
    <sy:updateFrequency>1</sy:updateFrequency>
    <item>
      <title>Playing with Kubernetes livenessProbe and readinessProbe probes</title>
      <link>https://docs.microsoft.com/archive/blogs/jannemattila/playing-with-kubernetes-livenessprobe-and-readinessprobe-probes</link>
      <pubDate>Thu, 07 Jun 2018 14:27:18 GMT</pubDate>
      <dc:creator><![CDATA[Janne Mattila]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/jannemattila/?p=1175</guid>
      <description><![CDATA[Disclaimer: Cloud is very fast moving target. It means that by the time you’re reading this post...]]></description>
      <content:encoded><![CDATA[<strong>Disclaimer: Cloud is very fast moving target. It means that by the time you’re reading this post everything described here could have been changed completely <img width="19" height="19" class="alignnone size-full wp-image-735" alt="Smiley" src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" />. Hopefully some things still apply to you! Enjoy the ride!</strong>

<hr />

Liveness and readiness probes are excellent way to make sure that your application stays healthy in your Kubernetes cluster.
If you're not familiar with it then please checkout some documentation before continuing:
<ul>
 	<li><a target="_blank" href="https://kubernetes.io/docs/tasks/configure-pod-container/configure-liveness-readiness-probes/" rel="noopener">Configure Liveness and Readiness Probes</a></li>
 	<li><a target="_blank" href="https://kubernetes.io/docs/user-guide/walkthrough/k8s201/#health-checking" rel="noopener">Kubernetes 201 -&gt; Health Checking</a></li>
 	<li><a target="_blank" href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/#container-probes" rel="noopener">Container probes</a></li>
</ul>
Now you should have pretty good idea what health check probes are and how you configure them.

However you might want to get some hands-on experience in order to understand them better.
And that's the reason why I've created this post... to help you understand how these work in practice
in many different scenarios.

Okay let's set up the scene. First let's take a look at the high level setup of Kubernetes Probe demo application:

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/High_level_demo_setup.png"><img width="801" height="356" class="alignnone wp-image-1265" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/High_level_demo_setup-1024x455.png" /></a>

In above diagram you'll see Service taking in requests and then forwarding them to the
actual application instances running in containers. And in this case since we are in Kubernetes
world we'll mean <a target="_blank" href="https://kubernetes.io/docs/concepts/services-networking/service/" rel="noopener">Kubernetes Service</a>.
Behind the service there are our worker bees a.k.a. containers that do the actual work in our application.
We'll then have a bit outsider friend which I've named "echo". This is used for reporting the
probe statuses, different events from containers etc. It's effectively just view to see what's going
on in our application.

Application that we're going to run in this example is <a target="_blank" href="https://github.com/JanneMattila/KubernetesProbeDemo" rel="noopener">Kubernetes Probe Demo</a>.
This we can use to learn more about the probes and other failure handling scenarios. It's ASP.NET Core 2.1
application which has the most plain front end page ever:

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/KubernetesProbeDemo_Front_page.png"><img width="800" height="389" class="alignnone wp-image-1185" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/KubernetesProbeDemo_Front_page-1024x498.png" /></a>

But more importantly it has API endpoint that enables us to poke around with it:
<code>/api/HealthCheck</code>

To get the current probe statuses use:
<code>GET /api/HealthCheck</code>

To get the current liveness probe status use (this is used by Kubernetes also):
<code>GET /api/HealthCheck/Liveness</code>

To get the current readiness probe status use (this is used by Kubernetes also):
<code>GET /api/HealthCheck/Readiness</code>

To change the status of the probes or close the application use this:
<code>POST /api/HealthCheck</code>

This expects json payload with following format:
<code>{
"readiness": boolean,
"liveness": boolean,
"shutdown": boolean
}</code>

First two ("readiness" and "liveness") control the probe states and third one ("shutdown") can be used
to close down the application (which causes that container to exit).
If you do not provide value for the properties in your payload then it uses default value of boolean (=false).

Application reports probe statuses and different events using webhooks. That's the reason
we had <a target="_blank" href="https://github.com/JanneMattila/Echo" rel="noopener">echo</a> in our above diagram.
You can use any online services that provide functinality to view webhook requests but
in this case we'll use this another ASP.NET Core 2.1 application for that purpose.
You don't need to clone the source of the echo if you just want to spin it up in your Kubernetes.
You can use this <a target="_blank" href="https://hub.docker.com/r/jannemattila/echo/" rel="noopener">echo container image</a> for that purpose.
Here is example Echo.yaml that can be used for deploying this to your cluster:
<script src="https://gist.github.com/JanneMattila/75d5ec456b3105736c510bc99a5883e0.js"></script>

Or just use this command to do the deployment:
<script src="https://gist.github.com/JanneMattila/bc2f340133d9df67910552db56445c1f.js"></script>

Now you should have echo running in <code>http://localhost:31111/</code>.
You can try to post data to see if it works correctly using the instructions given in the web page:

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/Postman_and_echo.png"><img width="800" height="728" class="alignnone wp-image-1205" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/Postman_and_echo-1024x932.png" /></a>

You can clean up your previous post just by refreshing the view in your browser.
For now leave one browser window open for this address since we're coming back to this view soon.

Okay now we have our helper service up and running and we're ready to deploy our primary
application. If you want to checkout the code then head to the <a target="_blank" href="https://github.com/JanneMattila/KubernetesProbeDemo" rel="noopener">GitHub</a>.

We'll use this yaml file:
<script src="https://gist.github.com/JanneMattila/58312dac39b7d6b809399bf0fdfcbe54.js"></script>

If you just want to deploy the application using example yaml and ready made container then
you can use these steps:
<script src="https://gist.github.com/JanneMattila/d258a7eda44c95abf93b1ccff45f50b8.js"></script>

On purpose we first get the yaml file to local filesystem so that we can then later edit that
according to our test scenarios.
After running above commands you should have application running and it should be
reachable from this address: <code>http://localhost:32001</code>

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/Deployed_KubernetesProbeDemo_Front_page.png"><img width="800" height="405" class="alignnone wp-image-1225" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/Deployed_KubernetesProbeDemo_Front_page-1024x518.png" /></a>

Now if you still have Echo open in your browser then it should start showing different events:

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/Echo_after_incoming_events.png"><img width="800" height="636" class="alignnone wp-image-1245" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/Echo_after_incoming_events-1024x814.png" /></a>

This could be the first time that you'll notice one interesting thing. Since we have configured
both liveness and readiness probes we can see both events in the view:

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/Echo_showing_liveness_and_readiness.png"><img width="800" height="343" class="alignnone wp-image-1255" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/Echo_showing_liveness_and_readiness-1024x440.png" /></a>

This might be a bit surprising at first since might think that
readiness probe is just used for the "start up readiness check" but it's not. Readiness checks are executed in regular intervals just as you have configured them.

If you check with kubectl your should see 3 instances of our application running:

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/kubectl_3_pods_running.png"><img width="799" height="198" class="alignnone wp-image-1285" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/kubectl_3_pods_running-1024x254.png" /></a>

And if you managed to get this far then you're actually ready to (finally!) try out some scenarios.

<strong>Scenario 1: Post "shutdown" command using the Rest API</strong>

<code>curl -d '{"shutdown":true}' -H "Content-Type: application/json" -X POST http://localhost:32001/api/HealthCheck</code>

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/wsl_curl_to_cause_shutdown.png"><img width="800" height="232" class="alignnone wp-image-1215" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/wsl_curl_to_cause_shutdown-1024x296.png" /></a>

If you then continue to update your Kubernetes Demo App view in your browser you should notice that the
application still continues to work even if one container just was forced to exit.

Kubernetes has noticed this and is bringing back new instance according to the defined replica count in your yaml file:

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/kubectl_3_pods_after_shutdown.png"><img width="798" height="160" class="alignnone wp-image-1275" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/kubectl_3_pods_after_shutdown-1024x205.png" /></a>

Conclusion: Kubernetes has bring that instance after it has exited. Read more about the <a target="_blank" href="https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/" rel="noopener">restartPolicy</a> in Pod Lifecycle documentation.

<strong>Scenario 2: Fail the liveness probe</strong>

<code>curl -d '{"readiness":true,"liveness":false}' -H "Content-Type: application/json" -X POST http://localhost:32001/api/HealthCheck</code>

Now you should notice this also in kubectl:

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/kubernetes_after_liveness.png"><img width="799" height="330" class="alignnone wp-image-1315" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/kubernetes_after_liveness-1024x423.png" /></a>

And also in echo since there are events related to the closing the background processing service and event related to app started:

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/ech_after_liveness_probe_failure.png"><img width="800" height="667" class="alignnone wp-image-1235" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/ech_after_liveness_probe_failure-1024x854.png" /></a>

Conclusion: If Kubernetes notices that liveness probe reports failure it will recycle the container to get it back on track.

<strong>Scenario 3: Fail the readiness probe</strong>

This one is a bit more complicated. First we'll take note about the current container name which is visible in the browser. Then
we'll post readiness probe failure for that specific container and observe what happens:

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/kubectl_after_readiness.png"><img width="800" height="665" class="alignnone wp-image-1295" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/kubectl_after_readiness-1024x851.png" /></a>

Here are the actual commands that I've used:
<script src="https://gist.github.com/JanneMattila/f06eac8d6aba8db4b3b5035428cc21d7.js"></script>

After I've set that to fail the readiness check you can still see that same name in your browser before
Kubernetes doesn't anymore route traffic to it. However Kubernetes doesn't recycle that container but
it waits and waits it to recover. You can refresh your browser (CTRL+F5) to see that container doesn't anymore
receive traffic:

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/KubernetesProbeDemo_refreshing_browser.gif"></a><a href="https://msdnshared.blob.core.windows.net/media/2018/06/KubernetesProbeDemo_refreshing_browser.gif"><img width="800" height="350" class="alignnone wp-image-1195" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/KubernetesProbeDemo_refreshing_browser.gif" /></a>

And if you use kubectl to check the status you'll see that pod is not reported to be ready:

<a href="https://msdnshared.blob.core.windows.net/media/2018/06/kubectl_after_readiness_2.png"><img width="800" height="159" class="alignnone wp-image-1305" alt="" src="https://msdnshared.blob.core.windows.net/media/2018/06/kubectl_after_readiness_2-1024x204.png" /></a>

Conclusion: Kubernetes waits patiently container to recover in case readiness check fails.

Those 3 scenarios were the ones I wanted to cover in this post. However you can continue with all sorts
of different scenarios and topics such as:
<ul>
 	<li>Change configuration so that container will crash at start up.
<ul>
 	<li>Example: Change value of readinessCheck from "true" to "true 123" (cannot be converted to boolean and causes failure in startup).</li>
 	<li>Deploy this update yaml and see how Kubernetes manages the situation (use e.g. "kubectl get pods" or "kubectl rollout status deployment kubernetesprobedemo").</li>
 	<li>Isn't this good place to catch configuration issues? Throw on startup to the rescue!</li>
</ul>
</li>
 	<li>Telemetry and probe events
<ul>
 	<li>If you collect telemetry from you application (e.g. Application Insights) then how do you handle telemetry
events caused just by probes (<a target="_blank" href="https://docs.microsoft.com/en-us/azure/application-insights/app-insights-api-filtering-sampling" rel="noopener">hint</a>)? You can calculate how much telemetry just your different services
and their many instances generate from these probes.</li>
</ul>
</li>
 	<li>App health monitoring libraries
<ul>
 	<li>This demo application didn't use any ready made libraries but you should definitely
check them out. Here's one good article in ASP.NET Core <a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/implement-resilient-applications/monitor-app-health" rel="noopener">Health monitoring</a>.</li>
</ul>
</li>
</ul>
You can find the source code used in this example application from GitHub:
<a target="_blank" href="https://github.com/JanneMattila/Echo" rel="noopener">JanneMattila / Echo</a>
<a target="_blank" href="https://github.com/JanneMattila/KubernetesProbeDemo" rel="noopener">JanneMattila / KubernetesProbeDemo </a>
and images from Docker Hub:
<a target="_blank" href="https://hub.docker.com/r/jannemattila/echo/" rel="noopener">JanneMattila / echo</a>
<a target="_blank" href="https://hub.docker.com/r/jannemattila/kubernetesprobedemo/" rel="noopener">JanneMattila / kubernetesprobedemo</a>

By the way... When I was drawing out the above diagram I've found out about <a target="_blank" href="https://gallery.technet.microsoft.com/Collection-of-Integration-e6a3f4d0" rel="noopener">Microsoft Integration Stencils Pack</a>. It contains really cool symbols and icons so I really recommend you to check it out.]]></content:encoded>
    </item>
    <item>
      <title>Blank ARM template starter kit</title>
      <link>https://docs.microsoft.com/archive/blogs/jannemattila/blank-arm-template-starter-kit</link>
      <pubDate>Mon, 19 Mar 2018 22:44:40 GMT</pubDate>
      <dc:creator><![CDATA[Janne Mattila]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/jannemattila/?p=1135</guid>
      <description><![CDATA[I've noticed that quite often it's hard to start developing your ARM templates so that you're at the...]]></description>
      <content:encoded><![CDATA[I've noticed that quite often it's hard to start developing your ARM templates so that you're at the same time preparing for the deployment automation from the beginning. Sure there are <a target="_blank" href="https://github.com/Azure/azure-quickstart-templates" rel="noopener">many templates available</a> and web is full of blogs that show different details of ARM templates but many times you have to think that "how does this land into my codebase so that it's still manageable and at least basics are well in-place". Many of my customers have been struggling with this topic and I decided to create "Blank ARM template starter kit" to (hopefully) ease the pain of getting started.

Idea of the Blank ARM template starter kit is simple. Provide solid starting point for your ARM template development. This is fully aligned with the target of automating this in your VSTS build and release pipelines. This lets you first worry on the resources to add to your template and secondly only worry how to further improve you deployment automation. So no need to start from scratch!

I tried to explain everything in <a target="_blank" href="https://github.com/JanneMattila/000-BlankApp" rel="noopener">https://github.com/JanneMattila/000-BlankApp</a> but just to give short recap about it. First grab a copy of the repository as <a target="_blank" href="https://github.com/JanneMattila/000-BlankApp/archive/master.zip" rel="noopener">zip</a> and then start taking these starter files into use. Typical development workflow for your ARM template development follows this pattern:
<ol>
 	<li>Create Git repository (or use existing if you have one)</li>
 	<li>Commit Blank ARM template starter kit files to the repository</li>
 	<li>Now you should have "clean" working state</li>
 	<li>Start loop
<ul>
 	<li>Add/Modify deployment script or ARM template</li>
 	<li>Execute deploy.ps1</li>
 	<li>Validate the change</li>
 	<li>Commit you change</li>
</ul>
</li>
</ol>
Of course when you are ready you should share you work using pull request &amp; code reviews and all the other ALM practices your team has in-place.

Hopefully this enables you to start building awesome apps faster <img width="19" height="19" class="alignnone size-full wp-image-735" alt="" src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" />.]]></content:encoded>
    </item>
    <item>
      <title>Legacy apps to Azure with PowerShell DSC and CI + CD</title>
      <link>https://docs.microsoft.com/archive/blogs/jannemattila/legacy-apps-to-azure-with-powershell-dsc-and-ci-cd</link>
      <pubDate>Tue, 18 Oct 2016 22:17:35 GMT</pubDate>
      <dc:creator><![CDATA[Janne Mattila]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/jannemattila/?p=1075</guid>
      <description><![CDATA[Disclaimer: Cloud is very fast moving target. It means that by the time you’re reading this post...]]></description>
      <content:encoded><![CDATA[<strong>Disclaimer: Cloud is very fast moving target. It means that by the time you’re reading this post everything described here could have been changed completely <img src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" class="alignnone size-full wp-image-735" width="19" height="19" />. Hopefully some things still apply to you! Enjoy the ride!</strong>

<hr />

I have been blogging about power of PowerShell, ARM and automation earlier. But every now and then I still come across to discussions which typically goes like this:
<blockquote>Yes, it works for those new fancy apps but I have this old legacy <em>&lt;InsertYourTechnologyOrAppHere /&gt;</em> which cannot be automated and cannot be put to cloud just like that.</blockquote>
Therefore, I decided to create demo which will show that you can do amazing things even with older technologies. CI + CD and automations apply even if your app is not built using "new" technologies.

Let’s jump directly into my demo application architecture:
<a href="https://msdnshared.blob.core.windows.net/media/2016/10/WindowsService.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/10/WindowsService.png" alt="Legacy app architecture" class="size-full wp-image-1085" width="721" height="286" /></a>

My application runs in Windows Server and it has two components:
<ul>
 	<li>Common Gateway Interface (CGI) app running under IIS
<ul>
 	<li>Written in C++</li>
 	<li>Reads information from registry</li>
</ul>
</li>
 	<li>Windows Service
<ul>
 	<li>Written in C++</li>
 	<li>Writes information to registry</li>
</ul>
</li>
</ul>
Basically, these components interact with each other via registry and we don’t want to (or as typically you cannot) modify source code at all so we’re stuck with this solution. This means that we need to leverage Infrastructure-as-a-Service (IaaS) in our solution since there we have free hands when it comes to server configuration.

Again, our code setup is the same as earlier in my solutions:
<a href="https://msdnshared.blob.core.windows.net/media/2016/10/SourceStructure.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/10/SourceStructure.png" alt="Source code structure" class="alignnone size-full wp-image-1086" width="227" height="538" /></a>

Structure has already familiar "deploy", "src" and "test" sub-folders.

Deploy folder even has pretty much same content as earlier but there is one new thing underneath sub folder "DSC". We'll come back later to that.

Source folder has our legacy application components and test folder has simple release test which we will use in our release process.

Our CI is almost same as in the previous examples (so no re-inventing wheel in here <img src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" class="alignnone size-full wp-image-735" width="19" height="19" />):
<a href="https://msdnshared.blob.core.windows.net/media/2016/10/CI.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/10/CI.png" alt="Build definition" class="alignnone size-full wp-image-1095" width="643" height="424" /></a>

And of course, our CD follows the same footprints as earlier:
<a href="https://msdnshared.blob.core.windows.net/media/2016/10/CD.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/10/CD.png" alt="Release definition" class="alignnone size-full wp-image-1105" width="946" height="551" /></a>

Only new thing in the release definition is our PowerShell <a target="_blank" href="https://github.com/pester/Pester">Pester</a> testing task titled as "<a target="_blank" href="https://marketplace.visualstudio.com/items?itemName=richardfennellBM.BM-VSTS-PesterRunner-Task">Pester Test Runner</a>". It will validate that our release was successful and environment is running as it should. But more about that later (see I’m postponing all the good stuff to the end <img src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" class="alignnone size-full wp-image-735" width="19" height="19" />).
<h3>How is the Windows Server configuration handled?</h3>
This is the part where the DSC comes relevant. If you’re completely new to the topic, then you might want to check these first:
<a target="_blank" href="https://msdn.microsoft.com/en-us/powershell/dsc/overview">Windows PowerShell Desired State Configuration Overview</a>
<a target="_blank" href="https://msdn.microsoft.com/en-us/powershell/dsc/builtinresource">Built-In Windows PowerShell Desired State Configuration Resources</a>

Similarly, from Azure Automation perspective:
<a target="_blank" href="https://azure.microsoft.com/en-us/documentation/articles/automation-dsc-overview/">Azure Automation DSC Overview</a>
<a target="_blank" href="http://social.technet.microsoft.com/wiki/contents/articles/34380.getting-started-with-azure-automation-dsc.aspx">Getting Started With Azure Automation DSC</a>

Okay so now I assume that you know what's DSC all about and why it's very interesting piece when automating environment configuration and setup.

In my demo, I have this one extra sub folder in "deploy/DSC" which I already mentioned earlier. This folder contains <em>dscExtension.ps1</em> file:
<script src="https://gist.github.com/JanneMattila/a3a18e135dd533f62801f47c0d01bb86.js"></script>

This file basically contains configuration to:
<ul>
 	<li>Ensure that correct Windows features are installed (e.g. IIS and friends)</li>
 	<li>Ensure that IIS is configured to be CGI app friendly</li>
 	<li>Download our apps from Azure Storage to the VM</li>
 	<li>Install and configure our apps</li>
</ul>
First one is straightforward and basic DSC scenario. Second one requires a bit more tweaking of the IIS and <a target="_blank" href="https://www.iis.net/configreference">IIS Configuration Reference</a> is great help on that. Third and fourth ones are purely your application specific from the installation point of view. I only had few extra lines to get the applications files downloaded to the VM.
<h3>How did those applications land into the virtual machine?</h3>
In our <em>deploy.ps1</em> file we had part that took our compiled application and created Zip package out of them. This package was then copied over to Azure Storage and <a target="_blank" href="https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-shared-access-signature-part-1/">SAS Token</a> is then used to grant temporary access to those resources using "<em>fixed SAS token url</em>". This url is passed (with the help of PowerShell of course!) into the ARM process and that lands into our DSC process as easily downloadable content.
<h3>What was that Pester in CD?</h3>
Pester is very handy PowerShell testing framework which you can use in your unit tests and as in this case, release tests. I have simple validation script to check that this newly created environment is as expected. And if it’s not then it would fail the release process. This way I can easily validate that the environment creation works as planned and that my DSC has configured all the things required correctly. And how did Pester know that environment specific url then? Well it was passed by <em>deploy.ps1</em> as environment variable in the CD using <a href="https://github.com/Microsoft/vsts-tasks/blob/master/docs/authoring/commands.md" target="_blank">VSTS Logging Commands</a>. 
<h3>How does the final output look like?</h3>
<a href="https://msdnshared.blob.core.windows.net/media/2016/10/EndResult.gif"><img src="https://msdnshared.blob.core.windows.net/media/2016/10/EndResult.gif" alt="Result as animated gif :)" class="alignnone size-full wp-image-1116" width="356" height="222" /></a>
<h3>Closing words</h3>
In this demo, I presented few new tools that you should take into use. DSC is extremely powerful if you combine that with ARM and PowerShell you can build cool Infrastructure-as-a-Service solutions.

As promised you can find the source code used in this example application from GitHub at <a href="https://github.com/JanneMattila/300-WindowsService" target="_blank">JanneMattila / 300-WindowsService</a>.

Anyways... Happy hacking!]]></content:encoded>
    </item>
    <item>
      <title>Enhance ARM deployments with PowerShell</title>
      <link>https://docs.microsoft.com/archive/blogs/jannemattila/enhance-arm-deployments-with-powershell</link>
      <pubDate>Fri, 26 Aug 2016 08:10:28 GMT</pubDate>
      <dc:creator><![CDATA[Janne Mattila]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/jannemattila/?p=1005</guid>
      <description><![CDATA[Disclaimer: Cloud is very fast moving target. It means that by the time you’re reading this post...]]></description>
      <content:encoded><![CDATA[<strong>Disclaimer: Cloud is very fast moving target. It means that by the time you’re reading this post everything described here could have been changed completely <img src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" class="alignnone size-full wp-image-735" height="19" width="19" />. Hopefully some things still apply to you! Enjoy the ride!</strong>

<hr />

Azure Resource Manager templates (ARM) is excellent way to deploy your infrastructure to Azure (see example from my <a target="_blank" href="https://blogs.msdn.microsoft.com/jannemattila/2016/08/08/simple-web-app-application-lifecycle-management-with-vsts-and-azure/">previous blog post</a> to get started). However sometimes it might feel a bit of static when you need to build infrastructure that uses some shared elements or something that needs to be injected at runtime to the deployment.

But no worries PowerShell comes to the rescue! And by that I mean that we need to leverage scripting capabilities of PowerShell in our deployment pipeline. We’re not going to be in using pure static ARM templates and we’re not going to be using pure PowerShell either in our deployment but instead we want to pick best of both worlds. This lets us to get dynamic scripting characteristics to our deployment.

One very common scenario which people first bump into is the use of <a target="_blank" href="https://azure.microsoft.com/en-us/documentation/services/key-vault/">Key Vault</a> in deployments. You of course want to securely manage your app secrets (source control is big no-no <img src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" class="alignnone size-full wp-image-735" height="19" width="19" />) but it’s a bit of challenge to manage it. If you look at the <a target="_blank" href="https://github.com/Azure/azure-quickstart-templates">Quick start ARM templates on GitHub</a> or documentation about Key Vault (<a target="_blank" href="https://azure.microsoft.com/en-us/documentation/articles/resource-manager-keyvault-parameter/#reference-a-secret-with-static-id">example one</a>) you get instructed to use Key Vault as static reference which will not work in practice when you need to work with real multi-environment systems. Those static references of course work when you have single simple environment but when you want to deploy this to <em>n</em> environments then it’s not going to scale. And this is the part where I’ll use PowerShell magic to make it multi-environment friendly.

So let’s use exactly same deployment method as I had in my previous blog post. First I have some source assets:
<img src="https://msdnshared.blob.core.windows.net/media/2016/08/SourceAssets.png" alt="Source assets of our solution" class="size-full wp-image-1045 alignnone" height="379" width="267" />
Second I have CI:
<img src="https://msdnshared.blob.core.windows.net/media/2016/08/CI.png" alt="CI" class="size-full wp-image-1035 alignnone" height="343" width="528" />
Third I have CD:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/CDOverview.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/CDOverview.png" alt="CD Overview" class="size-full wp-image-1025 alignnone" height="422" width="922" /></a>
Now this is the part where we must pay a bit more attention. Change to the previous post is that now my process has two scripts:

<em>deploy-initial.ps1</em>: This is responsible of creating resource group and Key Vault if it doesn’t exist.
<em>deploy.ps1</em>: This is responsible of creating resources to the existing resource group and leveraging existing information from Key Vault.

Idea behind above split is to make sure that we create Key Vault resource first and dependent resources afterwards. And when the Key Vault is created it is also initialized with required contents. After that initial creation Key Vault secrets are managed directly to Key Vault (in another words outside from this script). This model also allows you to create the Key Vault beforehand in you want to. It would mean that <em>deploy-initial.ps1</em> wouldn't actually do anything since resources have been already earlier created.

Of course we need to pass the initial password to the release task and for that we can use release variables:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/CD_Variables.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/CD_Variables.png" alt="CD Variables" class="size-full wp-image-1015 alignnone" height="305" width="498" /></a>

<em>deploy-initial.ps1</em> uses following parameters:
<table class="table table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Example values</th>
</tr>
</thead>
<tbody>
<tr>
<td>-ResourceGroupName</td>
<td>yourservice-dev-rg</td>
</tr>
<tr>
<td>-VaultName</td>
<td>yourservice-dev-kv</td>
</tr>
<tr>
<td>-Location</td>
<td>"North Europe"</td>
</tr>
<tr>
<td>-AdminPassword</td>
<td>(ConvertTo-SecureString -String "$(AdminPassword)" -Force -AsPlainText)</td>
</tr>
<tr>
<td>-ServicePrincipal</td>
<td>"abcdefgh-abcd-abcd-abcd-abcdabcdabcd"</td>
</tr>
</tbody>
</table>
Above values are just examples and for the -ServicePrincipal you need to have your real SPN guid. That can be retrieved with following query:
<script src="https://gist.github.com/JanneMattila/06c96cb9660df6a1b85185b90932fee7.js"></script>
And why is that required then? Well even in the SPN creates the Key Vault it doesn’t have access rights to it for the required operations. Therefore, we need to <a href="https://github.com/JanneMattila/200-UbuntuDocker/blob/master/deploy/deploy-initial.ps1#L52-L56" target="_blank">explicitly grant access rights</a> to the Key Vault to our SPN and for that you need to have identifier.

Entire beef of the <em>deploy-initial.ps1</em> is this (<a href="https://github.com/JanneMattila/200-UbuntuDocker/blob/master/deploy/deploy-initial.ps1" target="_blank">full source is available at GitHub</a>):
<script src="https://gist.github.com/JanneMattila/29aca82253994045218275e5079a24f1.js"></script>

After <em>deploy-initial.ps1</em> has done it’s magic we can move to next step which is <em>deploy.ps1</em>. Now this script can already rely that Key Vault is up and running and configured correctly. So now we can use Key Vault to retrieve secrets and pass them on directly to the deployment part as parameters:
<script src="https://gist.github.com/JanneMattila/d75c925f53e24ff0a97c703cfe2b2cd9.js"></script>

It’s also very nice way to pass any other parameters to your deployment if you need to. Example different SKUs for different environment, different scaling per environment etc.
Maybe needless to say but passing parameters for ARM deployments gives you that required flexibility and dynamic behavior which you definitely want.

<h4>Bonus part</h4>
And since we have now Key Vault secrets available in our CD process we can do whatever we want with them. To give you wild and crazy demo I’ll just show that you can upload some custom bash script to the server and run it as part of your CD process (you could even generate that script in your deployment script <img src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" class="alignnone size-full wp-image-735" height="19" width="19" />). This highlighted text is coming from bash script output:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/CD_custombash.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/CD_custombash.png" alt="CD Custom bash script" class="alignnone size-full wp-image-1065" height="388" width="919" /></a>
Check out the source <a target="_blank" href="https://github.com/JanneMattila/200-UbuntuDocker/blob/master/deploy/deploy.ps1#L52-L85">here</a>.

<h3>Closing words</h3>
In this blog post I wanted to demonstrate PowerShell + ARM combination and the capabilities it provides. With this you should be able to enhance your deployment logic beyond the plain ARM capabilities.

You can find the source code used in this example application from GitHub at <a target="_blank" href="https://github.com/JanneMattila/200-UbuntuDocker">JanneMattila / 200-UbuntuDocker</a>.

Anyways... Happy hacking!]]></content:encoded>
    </item>
    <item>
      <title>Simple web app application lifecycle management with VSTS and Azure</title>
      <link>https://docs.microsoft.com/archive/blogs/jannemattila/simple-web-app-application-lifecycle-management-with-vsts-and-azure</link>
      <pubDate>Mon, 08 Aug 2016 22:21:27 GMT</pubDate>
      <dc:creator><![CDATA[Janne Mattila]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/jannemattila/?p=775</guid>
      <description><![CDATA[Disclaimer: Cloud is very fast moving target. It means that by the time you’re reading this post...]]></description>
      <content:encoded><![CDATA[<strong>Disclaimer: Cloud is very fast moving target. It means that by the time you’re reading this post everything described here could have been changed completely <img src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" width="19" height="19" class="alignnone size-full wp-image-735" />. Hopefully some things still apply to you! Enjoy the ride!</strong>

<hr />

I wanted to create small and simple web application which I could use to demo few features of VSTS and Azure. Here are few things that I had on my mind:
<ul>
 	<li><a target="_blank" href="https://en.wikipedia.org/wiki/Continuous_integration">Continuous Integration (CI)</a></li>
 	<li><a target="_blank" href="https://en.wikipedia.org/wiki/Continuous_delivery">Continuous Delivery (CD)</a></li>
 	<li><a target="_blank" href="https://en.wikipedia.org/wiki/Infrastructure_as_Code">Infrastructure as Code</a></li>
 	<li><a target="_blank" href="https://en.wikipedia.org/wiki/DevOps">DevOps</a></li>
</ul>
I also wanted to make the example app so simple that it would be easier to focus to the development process and not just focus to the app itself. Application is purely <em>placeholder</em> Node.js application which prints out simple text every time. No other components in this application just to keep it bare minimum.

So let’s get started! First let’s look at the high level steps that what we need to do next:
<ol>
 	<li>Connect VSTS and Azure</li>
 	<li>Create repository for our application assets</li>
 	<li>Create build definition for continuous integration</li>
 	<li>Create release definition for continuous delivery</li>
 	<li>Code-Build-Deploy -loop</li>
</ol>
<h3>1. Connect VSTS and Azure</h3>
In order to deploy easily from VSTS to Azure we need to set up service endpoint into VSTS. There are plenty of documentation about this:
<a target="_blank" href="https://go.microsoft.com/fwlink/?LinkID=623000&amp;clcid=0x409">Automating Azure Resource Group deployment using a Service Principal in Visual Studio Online: Build/Release Management</a>
Or you can directly use this script (link was in above blog post) which has all the steps documented as PowerShell code <img src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" width="19" height="19" class="alignnone size-full wp-image-735" />:
<a target="_blank" href="https://github.com/Microsoft/vsts-tasks/blob/master/Tasks/DeployAzureResourceGroup/SPNCreation.ps1">https://github.com/Microsoft/vsts-tasks/blob/master/Tasks/DeployAzureResourceGroup/SPNCreation.ps1 </a>
Other useful information: <a target="_blank" href="https://azure.microsoft.com/en-us/documentation/articles/resource-group-authenticate-service-principal/">Use Azure PowerShell to create a service principal to access resources</a>

So hopefully you have now managed to create service principal and only thing you need to do in VSTS is to put those magical GUIDs and keys to this dialog:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/VSTSconnectionToAzure.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/VSTSconnectionToAzure.png" alt="Setup VSTS connection to Azure" width="994" height="624" class="size-full wp-image-955 alignnone" /></a>
After that you’re good to proceed to real work!
<h3>2. Create repository for our application assets</h3>
Okay now we have VSTS and Azure connected so we’re ready to create simple web app. First I’ll create Git repo to VSTS and put my source assets there (see link to the GitHub repo at the end of the blog post to get the source):
<img src="https://msdnshared.blob.core.windows.net/media/2016/08/GitStructure.png" alt="GitStructure" width="443" height="666" class="size-full wp-image-855 alignnone" />
I have following folder structure under my repository:
<ul>
 	<li>deploy: this folder contains code and configuration files to create all the necessary resources to Azure (infrastructure code)</li>
 	<li>src: this is actual source of the application</li>
 	<li>test: Ooops… Missing in action <img src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" width="19" height="19" class="size-full wp-image-735 alignnone" />!</li>
</ul>
This structure means that I have all the necessary assets in the repository in order to create the infrastructure for the application and assets which define the application itself (a.k.a. normal source code).

For all the developers the <em>src</em> folder is easy to understand since it contains the app source code. Deploy on the other hand can be something new. It has <a target="_blank" href="https://azure.microsoft.com/en-us/documentation/articles/resource-group-overview/">Azure Resource Manager (ARM)</a> template and template parameter files and deployment helper PowerShell script. If ARM is something new to you, then please visit the <a target="_blank" href="https://azure.microsoft.com/en-us/documentation/articles/resource-group-overview/">Azure Resource Manager overview</a> page to familiarize yourself to the topic. After that you can browse many readymade ARM templated directly from GitHub in <a target="_blank" href="https://github.com/Azure/azure-quickstart-templates">Azure / azure-quickstart-templates</a>.

This demo ARM template contains only single Azure Web App and App Service plan. Those can be quite easily done directly within Visual Studio 2015 using the <em>JSON Outline view</em>:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/VSandJSONOutlineView.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/VSandJSONOutlineView.png" alt="Visual Studio 2015 and JSON Outline View" width="1278" height="895" class="size-full wp-image-945 alignnone" /></a>

Now we have assets in place in order to develop app locally and run infrastructure test deployments to Azure locally using <em>deploy.ps1</em>. But that’s only local development and next step is to automate the process and execute those steps in hosted build environment.
<h3>3. Create build definition for continuous integration</h3>
First we’ll create new build definition into VSTS. It will be connected to our newly created git repository and we’re now only focused for building master branch (to make this case very simple). Our build definition has following 3 build steps:

1. step is to create Web Deploy package from our web app using <em>msbuild</em> and <em>Publishing.pubxml</em> (file in repository):
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/BuildDefinition1.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/BuildDefinition1.png" alt="Build Definition step 1" width="1070" height="413" class="size-full wp-image-825 alignnone" /></a>
<blockquote><em>Question: Why do you create this Web Deploy package and not just create connection directly from Visual Studio?</em>
Answer: Good question! I did that because it might not be yet known at development time where this will be deployed. You might start with 1 target environment (development) but later on get multiple environment so creating publishing profiles for them is no-go in my opinion. Target environments should not be "hardcoded" to source control.</blockquote>
2. step is to publish <em>deploy</em> artifact that can be later on used in Release management. Deploy artifact contains ARM template, template parameter file and deployment helper PowerShell script:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/BuildDefinition2.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/BuildDefinition2.png" alt="Build Definition step 2" width="672" height="266" class="size-full wp-image-826 alignnone" /></a>

3. step is to publish Web Deploy package as app artifact so that we can use it later on in Release management:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/BuildDefinition3.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/BuildDefinition3.png" alt="Build Definition step 3" width="866" height="275" class="size-full wp-image-835 alignnone" /></a>

Then you can also change build number format to something that suites you but I prefer this: "<em>1.0.$(Rev:r)</em>".

That's it for the build! Of course we now need to validate that build works correctly:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/Build.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/Build.png" alt="Build summary page" width="845" height="474" class="size-full wp-image-805 alignnone" /></a>

Remember to validate that build artifacts are as they should be:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/Build2.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/Build2.png" alt="Build summary and artifacts view" width="625" height="346" class="size-full wp-image-815 alignnone" /></a>

Then we just check the <em>Continuous Integration (CI)</em> checkbox which means that build kicks off right away when code is committed to the repository:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/BuildDefinition4.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/BuildDefinition4.png" alt="Build Definition and CI" width="500" height="437" class="size-full wp-image-845 alignnone" /></a>

Now we're ready with build definition and we’re ready proceed to continuous delivery!
<h3>4. Create release definition for continuous delivery</h3>
First we'll create new release definition and connect it to the previously created build:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/ReleaseManagement2.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/ReleaseManagement2.png" alt="Release Management artifacts" width="716" height="387" class="size-full wp-image-885 alignnone" /></a>

Now all those build artifacts we previously published from build are available for us to use in the release definition. This we will use later on.

I have 2 release management tasks in our environment:

1. task is Azure PowerShell script to use previously created Azure connection and our deployment script coming from build artifact:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/ReleaseManagementStep1.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/ReleaseManagementStep1.png" alt="Release Definition step 1" width="952" height="367" class="size-full wp-image-895 alignnone" /></a>
We also pass script arguments to the script to control the target resource group and deployment location in Azure.

2. task deploys our previously created Web Deploy Package which has been passed to the release management as build artifact:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/ReleaseManagementStep2.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/ReleaseManagementStep2.png" alt="Release Definition step 2" width="906" height="388" class="size-full wp-image-905 alignnone" /></a>

Similarly, you can have multiple environments in your release definition if you want to target multiple different environments:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/ReleaseManagement1.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/ReleaseManagement1.png" alt="Release Management with multiple environments" width="1520" height="700" class="alignleft size-full wp-image-875" /></a>

NOTE: This part is especially something that I know will change in the future. But at the time of writing this blog post this was the experience I got. Above disclaimer applies here <img src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" width="19" height="19" class="size-full wp-image-735 alignnone" />.

You might be wondering that why do I have <em>Azure Resource Group Deployment</em> step disabled in the above picture. Reasoning for that is the how ARM really works. If you deploy resources using ARM template, then it might be that ARM deployment itself goes fine but the actual resources are not yet available at the time you’re trying to use them. This “small gap” can be timewise small (~seconds) but potentially painful if your release fails due to web app not able to respond on time etc. Therefore <em>deploy.ps1</em> tries to minimize this problem by verifying that required resources are as they should. It tries to do that by doing simple web request to the web app and verifying that it’s okay before proceeding. You might want to read the official documentation about this and not just believe me:
<a target="_blank" href="https://azure.microsoft.com/en-us/documentation/articles/resource-manager-common-deployment-errors/#understand-when-a-deployment-is-ready">Understand when a deployment is ready</a> – Clip from document: <em>“...you should expect that the deployment status succeeds some time before your deployment can be used”</em>.

Again this is something that can change in the future and especially the VSTS build and deploy task can be enhanced to support retry logic and timeouts etc. But for now to increase reliability of the release you could solve this by using own deployment script. Also this script can be further enhanced to validate the infrastructure even broader if needed (and not just the web app).

Now our release definition is ready and we can proceed to the actual work!
<h3>5. Code-Build-Deploy -loop</h3>
Yes I know I’m missing <em>Test</em> from the above loop <img src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" width="19" height="19" class="size-full wp-image-735 alignnone" />. But in order to keep this example simple I simplified the loop a bit. But now let’s take a look how you would do changes to the infrastructure and to the code.

First let’s look at the case where you need to scale up the resources from "Free" to "Basic":
1. You would change the deployment configuration files to have new values.
2. Push this change to the remote branch and create pull request to the target branch (again I’m slightly simplifying to only have topic branch and master branch but you might also have dev branch in between in real life).
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/PullRequest.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/PullRequest.png" alt="Pull request view" width="1277" height="713" class="size-full wp-image-865 alignnone" /></a>
3. After the pull request is approved our CI process starts and that in turn starts CD process.
4. After CD has finished I can validate the change in the Azure Portal:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/AzurePortal.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/AzurePortal.png" alt="AzurePortal" width="458" height="192" class="size-full wp-image-795 alignnone" /></a>

This means that I don’t need to go to Azure Portal to change the configuration because it’s all managed from code.

Exactly same model applies for source code changes. First you change some code and run the normal process to get that approved:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/SourceDiff.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/SourceDiff.png" alt="Source diff view" width="1095" height="288" class="size-full wp-image-935 alignnone" /></a>

After CI and CD it lands into the website:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/SimpleWebAppV2.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/SimpleWebAppV2.png" alt="SimpleWebAppV2" width="577" height="147" class="size-full wp-image-925 alignnone" /></a>

And even better... you can now monitor state of your deployments directly from VSTS user interface if you have multiple environments in your release definition:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/ReleaseStatus.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/ReleaseStatus.png" alt="Release status view per environment" width="751" height="340" class="size-full wp-image-915 alignnone" /></a>

You can combine this with approvals to have better control what gets deployed and where:
<a href="https://msdnshared.blob.core.windows.net/media/2016/08/Approvers.png"><img src="https://msdnshared.blob.core.windows.net/media/2016/08/Approvers.png" alt="Approvers view" width="585" height="333" class="size-full wp-image-785 alignnone" /></a>

So you get approvals, audits etc which means this is pretty powerful model to build your solution!

<h3>Closing words</h3>
This was one way to combine source code management and infrastructure code management into single code repository. This by all means is not the only way to solve this but I think this model could work in many cases. You could of course have separate repos and deployments could happen in different release definitions etc but that’s just how you want to orchestrate and run your development. VSTS and Azure are very flexible to suite your needs.

As promised you can find the source code used in this example application from GitHub at <a target="_blank" href="https://github.com/JanneMattila/100-SimpleWebApp">JanneMattila / 100-SimpleWebApp</a>.

Anyways... Happy hacking!]]></content:encoded>
    </item>
    <item>
      <title>Run Survo Solver inside browser using Web workers</title>
      <link>https://docs.microsoft.com/archive/blogs/jannemattila/run-survo-solver-inside-browser-using-web-workers</link>
      <pubDate>Wed, 15 Jun 2016 10:12:10 GMT</pubDate>
      <dc:creator><![CDATA[Janne Mattila]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/jannemattila/?p=745</guid>
      <description><![CDATA[In 2007 I started this blog with post Solving small puzzles (with just a few lines of code). Years...]]></description>
      <content:encoded><![CDATA[In 2007 I started this blog with post <a href="https://blogs.msdn.microsoft.com/jannemattila/2007/01/07/solving-small-puzzles-with-just-a-few-lines-of-code/" target="_blank">Solving small puzzles (with just a few lines of code)</a>. Years later I noticed that there was actually comment at the blog post asking for the code of the app. Unfortunately, I’ve trashed that code so couldn’t get that back anymore. But I decided to implement it again and decided to add some extra flavor to it <img class="alignnone size-full wp-image-735" src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" width="19" height="19" />.

So I went and implemented survo solver using <a href="http://www.typescriptlang.org/" target="_blank">TypeScript </a>+ Javascript and <a href="https://en.wikipedia.org/wiki/Web_worker" target="_blank">Web workers</a> which means that you can run it directly in your browser (actually I implemented this over a year ago but forgot to publish the blog post).

You can try the solver in <a href="http://jannemattila.github.io/SurvoSolver/index.html" target="_blank">here </a>and check the source from <a href="https://github.com/JanneMattila/jannemattila.github.io/tree/master/SurvoSolver" target="_blank">here</a>. Solver user interface looks like this:

<a href="http://jannemattila.github.io/SurvoSolver/index.html" target="_blank"><img class=" size-full wp-image-755 alignnone" src="https://msdnshared.blob.core.windows.net/media/2016/06/SurvoSolverUI.png" alt="Survo Solver user interface" width="713" height="517" /></a>

In order to have lots of puzzles for my solvers I created <a href="https://github.com/JanneMattila/jannemattila.github.io/blob/master/SurvoSolver/data/puzzles.json" target="_blank">puzzles.json</a> data file. That file contains puzzles from <a href="http://www.survo.fi/puzzles/" target="_blank">http://www.survo.fi/puzzles/</a> and that local data file is used by the web worker solvers.

Hopefully this demo app gave you few ideas to think about. First: If you can run this kind of processing in browser (without any software installations) then what kind of things you can actually use this? Second: Browser performance is improving a lot as we speak and things like <a href="https://en.wikipedia.org/wiki/WebAssembly" target="_blank">WebAssembly </a>are also coming in the future. These two things in mind you can start building you own "distributed processing apps" <a href="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png"><img class="alignnone size-full wp-image-735" src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" width="19" height="19" /></a>. Maybe even apps like <a href="https://en.wikipedia.org/wiki/SETI@home" target="_blank">SETI@home</a> running directly in the browser! And that would be pretty cool.

Anyways… Happy hacking!]]></content:encoded>
    </item>
    <item>
      <title>Finally (some) piece of mind with My Pocket Solitaire</title>
      <link>https://docs.microsoft.com/archive/blogs/jannemattila/finally-some-piece-of-mind-with-my-pocket-solitaire</link>
      <pubDate>Mon, 06 Jun 2016 12:17:04 GMT</pubDate>
      <dc:creator><![CDATA[Janne Mattila]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/jannemattila/?p=685</guid>
      <description><![CDATA[This post continues My Pocket Solitaire series.

Previously I have been writing about My Pocket...]]></description>
      <content:encoded><![CDATA[This post continues <a title="All posts about My Pocket Solitaire" href="http://blogs.msdn.com/jannemattila/tag/my-pocket-solitaire/" target="_blank">My Pocket Solitaire</a> series.

Previously I have been writing about My Pocket Solitaire and how it has been coming back to me several times over the years. But finally some time ago I published new version of <a title="My Pocket Solitaire Store link" href="http://apps.microsoft.com/windows/app/my-pocket-solitaire/fd32ad9b-511a-4716-8b0e-9e1b3acff212" target="_blank">My Pocket Solitaire to Store</a> (application requires Windows 10) which includes two features which have given me (some) piece of mind after the release <img class="alignnone wp-image-735 size-full" src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" width="19" height="19" />:
<ul>
	<li>See how many solutions are still available</li>
	<li>Navigate between the solutions</li>
</ul>
I'll show what I mean by those features. First let's take a look at the start up position:
<img class=" size-full wp-image-695 alignnone" src="https://msdnshared.blob.core.windows.net/media/2016/06/StartOfGame.png" alt="Start of Game" width="664" height="576" />

Immediately you will see from the top that how many solutions are still available from the start position. That gets updated automatically when you make moves:
<img class=" size-full wp-image-705 alignnone" src="https://msdnshared.blob.core.windows.net/media/2016/06/FirstMove.png" alt="First move" width="664" height="576" />

Also you can see that certain positions are highlighted with white rectangle. Those indicate that "<em>this move will lead to solution</em>". This allows quite easy navigation between different solutions. Of course it's now quite easy to play the game and get to the winning state:
<img class=" size-full wp-image-715 alignnone" src="https://msdnshared.blob.core.windows.net/media/2016/06/EndOfGame.png" alt="End state of game" width="664" height="576" />
<h3>Technical solution</h3>
How was this achieved then? <em>Originally</em> I was thinking to embed those solutions into the application package. That would have of course made the application package quite big and that wasn't what I wanted. So I started to look for alternative solutions.

I could of course create Web App into Azure which could provide these solutions to client. But then I thought that it would be a bit too much this time. Because this time I wanted "<em>serverless</em>" backend <img class=" size-full wp-image-735 alignnone" src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" width="19" height="19" />.

Therefore I came up with the solution to put the game solution data to the Azure Blob Storage and address then directly from client using "known urls". After all I knew in the client how many moves player has done (I call this "level") and each board state can be identified with unique identifier. Combining these two I have way to create "fixed" urls which point into Blob Storage. And when I set the data to be "public" I can directly address those blobs from any client. This means that I have single file in Blob Storage for each board combination which leads to solutions. Board position which doesn't lead to solution would be 404 (Not found) and that is handled in the client as "<em>does not lead to solution</em>".

In order to push these solutions to the Blob Storage I created simple .NET Application which pushed the data into Azure. And in Client it was easy to create fixed url HTTP requests and receive solutions counts from storage. Retrieving single board state is quite fast so user interface updates actually quite nicely. I also cache retrieved solutions for the duration of the gaming session so it's fast to navigate the sames moves again and again.

End results is quite nice user interface with minimal maintenance on the backend. Exactly what I wanted <img class=" size-full wp-image-735 alignnone" src="https://msdnshared.blob.core.windows.net/media/2016/06/Smiley.png" alt="Smiley" width="19" height="19" />!

Anyways... Happy hacking!

BR,

J]]></content:encoded>
    </item>
    <item>
      <title>My Pocket Solitaire, MapReduce and Azure HDInsight</title>
      <link>https://docs.microsoft.com/archive/blogs/jannemattila/my-pocket-solitaire-mapreduce-and-azure-hdinsight</link>
      <pubDate>Wed, 29 Oct 2014 13:31:20 GMT</pubDate>
      <dc:creator><![CDATA[Janne Mattila 2]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/jannemattila/2014/10/29/my-pocket-solitaire-mapreduce-and-azure-hdinsight/</guid>
      <description><![CDATA[This post continues My Pocket Solitaire series.  In my previous post I explained how you can create...]]></description>
      <content:encoded><![CDATA[<p>This post continues <a title="All post about My Pocket Solitaire" href="http://blogs.msdn.com/jannemattila/archive/tags/my+pocket+solitaire/" target="_blank">My Pocket Solitaire</a> series. </p> <p>In my <a href="http://blogs.msdn.com/b/jannemattila/archive/2014/10/01/solving-my-pocket-solitaire-using-bottom-up-method.aspx" target="_blank">previous post</a> I explained how you can create solver which uses bottom up approach to solve this interesting problem. Now we're going to continue from that using MapReduce as our solving algorithm. If MapReduce is new concept to you then I would definitely recommend that you check out the <a href="http://en.wikipedia.org/wiki/MapReduce" target="_blank">Wikipedia article</a> about it before reading this post. I'm going to take use of the concepts and terms mentioned in there so it might be a bit challenging without that base information.</p> <p>Now we know (based on the previous posts) that we can solve My Pocket Solitaire nicely using bottom up approach. This gives us chance to identify steps we used during that process and now we can come up with new ways of running the same algorithm in different environment. If you recall my pseudo algorithm in previous post then we identified these following steps:</p> <ul> <li>We have list of unique positions in level one  <li>We execute moves for the each of the positions in the list  <li>We come up with new list of positions (includes possible duplicates)  <li>Remove duplicates away  <li>We have now list of unique positions in level two </li></ul> <p>And if you then slightly modify that above list of steps into this format:</p> <ul> <li>List of items  <li>Map each item with function  <li>We have new list of items based on output of function  <li>Reduce items from list based on function  <li>We have final output of items </li></ul> <p>This list awfully starts to look like Map and Reduce –like algorithm. So what if we built new version of our solving routine using MapReduce then? What we have to do in order to achieve that? First we will have to understand a bit more how you can put this kind of task into <a href="http://en.wikipedia.org/wiki/Apache_Hadoop">Apache Hadoop</a>. To get easiest start on that journey you're quite easily routed into solution called <a href="http://hadoop.apache.org/docs/current/hadoop-mapreduce-client/hadoop-mapreduce-client-core/HadoopStreaming.html">Hadoop Streaming</a>. Especially if you don’t have Java knowledge and you don't want to learn a lot of new stuff in order to get this implemented. I especially like the <i>Practical Help</i> section of <a href="http://wiki.apache.org/hadoop/HadoopStreaming">Hadoop Streaming Wiki Page</a> which gives you simple and direct way to get started with development locally and then learn more after that. Their script sample actually directly translates in my head into this: <script src="https://gist.github.com/JanneMattila/d5382d40acf500fece04.js"></script><noscript><pre>type SolverInit.txt | SolverMapper.exe | SolverReducer.exe</pre></noscript>
<p>This means that we have some kind of "SolverInit.txt" providing input into our process which is then executed through our "SolverMapper.exe" and that output is then put through "SolverReducer.exe". Output of reducer would be then again something that our solver would be able to use again when executed through MapReduce.</p>
<p>In order to implement this we have to now understand more about the input format. So what is this "SolverInit.txt" file then? Again we take a look at <a href="http://hadoop.apache.org/docs/current/hadoop-mapreduce-client/hadoop-mapreduce-client-core/HadoopStreaming.html">Hadoop Streaming documentation</a> which clearly says that input is coming in standard input stream (stdin) as lines into MapReduce processes and each line contains key-value pair. Key is until first tab on that line and rest of the line is considered to be value (this is the default setup but it can be changed). </p>
<p>So now we need to come up with format that has each game position in one line and key would position of the board. And since we want to now calculate again the magic number (which we already managed to solve in previous post) then we need to have count of solutions behind that key as counter. We also put there moves so that we can later validate that is this correct solution path. This leads us into this format for the "SolverInit.txt": <script src="https://gist.github.com/JanneMattila/5358f23ea32d863413b8.js"></script><noscript><pre>65536	1	</pre></noscript>
<p>Key for that is coming from board position (final board position in string format is 000000000000000010000000000000000) which is then converted using Bin-&gt;Dec conversion (from bits to number). You might be wondering that why I chose this format and not directly the string format… well reason is that since I was doing this in my local laptop and was forced to squeeze the data elements in order to be able to execute my algorithms <img class="wlEmoticon wlEmoticon-smile" style="border-top-style: none; border-bottom-style: none; border-right-style: none; border-left-style: none" alt="Smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/2541.wlEmoticon-smile_120EAB63.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/2541.wlEmoticon_2D00_smile_5F00_120EAB63.png">. And even if you start to utilize distributed processing model like this you still have the responsibility to keep in mind that how do you balance with the CPU, network data transfer need and storage use. But I might do another post with even simpler set up later.</p>
<p>"SolverMapper.exe" and "SolverReducer.exe" implementations have actually quite small responsibility in this entire solution. Mapper takes board positions as input from single line and performs all the possible available backward moves and outputs these new board positions as new lines to the output stream. Reducer in turn reads incoming lines and if there are multiple lines with same key (note: Hadoop hands these lines in sorted order of keys) then it will output just single line with value which is sum of all those duplicate lines.</p>
<p>So if we now think conceptually this MapReduce in My Pocket Solitaire context we can maybe best describe the process using this kind of batch file (lines omitted for simplicity): <script src="https://gist.github.com/JanneMattila/b78a65f92f7a32e50dfb.js"></script><noscript><pre>type SolverInit.txt |^
SolverMapper.exe | sort | SolverReducer.exe |^
SolverMapper.exe | sort | SolverReducer.exe |^
SolverMapper.exe | sort | SolverReducer.exe |^
SolverMapper.exe | sort | SolverReducer.exe |^
SolverMapper.exe | sort | SolverReducer.exe |^
SolverMapper.exe | sort | SolverReducer.exe |^
SolverMapper.exe | sort | SolverReducer.exe |^
SolverMapper.exe | sort | SolverReducer.exe |^
SolverMapper.exe | sort | SolverReducer.exe |^
SolverMapper.exe | sort | SolverReducer.exe |^
SolverMapper.exe | sort | SolverReducer.exe |^
SolverMapper.exe | sort | SolverReducer.exe |^
SolverMapper.exe | sort | SolverReducer.exe
</pre></noscript>
<p>That pretty much demonstrates that what kind of process this MapReduce streaming actually is!</p>
<h4>How to run this in HDInsight then?</h4>
<p>Okay now we have some understanding that how could we run this streaming job but what's the best way to do it then? And here comes the nice part of <a href="http://azure.microsoft.com/en-us/services/hdinsight/">Azure HDInsight</a>. You can actually built nice PowerShell script that runs this entire solving process as automated process. You just need to have Azure subscription and you're good to go! You might want to read this <a href="http://azure.microsoft.com/en-us/documentation/articles/hdinsight-hadoop-develop-deploy-streaming-jobs/">excellent article</a> before you proceed because I won’t go necessarily through all the details to set you up. </p>
<p>Of course I can login to the management portal and create HDInsight clusters etc from there but since I'm now going to demo how you can do this using just script then we need to do something extra to set it up. In order to script to work without you providing credentials to it, it needs use certificate in order to access the service. When access is solved in script then script would have to create needed storage account, create HDInsight cluster, run the entire MapReduce algorithm loop for 32 levels and then get the final output file out from storage. And of course when this process is completed it will release all the resources created during the script execution. And while script is doing the heavy work (or more precisely Azure is doing the heavy work <img class="wlEmoticon wlEmoticon-smile" style="border-top-style: none; border-bottom-style: none; border-right-style: none; border-left-style: none" alt="Smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/2541.wlEmoticon-smile_120EAB63.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/2541.wlEmoticon_2D00_smile_5F00_120EAB63.png">) then you can be somewhere else doing something completely different.</p>
<p>So in order to get the automatic login to work you have to download so called publish settings. You can get it using Azure PowerShell and executing following command there: <script src="https://gist.github.com/JanneMattila/a122ceac22c7f99ae16c.js"></script><noscript><pre># Get Azure publish settings file using this command:
Get-AzurePublishSettingsFile</pre></noscript>
<p>This will open up browser and it will spit out you file from Azure which will contain management certificate in there. This file allows you to run these scripts as unattended. But this of course means that you have make sure that proper security is applied when handling this file. Read more information from <a href="http://msdn.microsoft.com/en-us/library/dn790375.aspx">here</a>. In my solver script I have the call to import this publish settings file in order to demonstrate that how this full end to end process can be implemented. My script expects that to be saved into same folder as the script itself using name "Subscription.publishsettings".</p>
<p>What to expect when you then execute "Solve.bat" (which is wrapper to start the real PowerShell script to make sure that it actually doesn't just open that script file but rather executes it): <script src="https://gist.github.com/JanneMattila/de9b5b1fcc6c1c7453ff.js"></script><noscript><pre>@powershell.exe -NoProfile -InputFormat none -ExecutionPolicy unrestricted -File %~dp0Solve.ps1</pre></noscript>
<p>Well you should see PowerShell script starting the execution and providing updates about the progress:</p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/3750.HDInsightProcessing1_78D4D49A.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/3750.HDInsightProcessing1_5F00_78D4D49A.png" target="_blank"><img title="HDInsight Cluster created using PowerShell script" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="PowerShell script creates and run solver algorithm" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/3252.HDInsightProcessing1_thumb_37CB7698.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/3252.HDInsightProcessing1_5F00_thumb_5F00_37CB7698.png" width="640" height="377"></a></p>
<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/7418.HDInsightProcessing2_56A47B27.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/7418.HDInsightProcessing2_5F00_56A47B27.png" target="_blank"><img title="PowerShell script at work and solving this puzzle" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Script is processing solving puzzle" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/2133.HDInsightProcessing2_thumb_486892E8.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/2133.HDInsightProcessing2_5F00_thumb_5F00_486892E8.png" width="640" height="267"></a></p>
<p>If you want to run this script by yourself then you can just get <a href="https://github.com/JanneMattila/jannemattila.github.io/tree/master/HDInsight" target="_blank">all the resources from here</a>.</p>
<p>Here’s the full "Solve.ps1" script that makes all these tricks: <script src="https://gist.github.com/JanneMattila/15f22ae80100e8e56c59.js"></script><noscript><pre># Full Solve.ps1 will be here if you view this blog post through web browser <img class="wlEmoticon wlEmoticon-smile" style="border-top-style: none; border-bottom-style: none; border-right-style: none; border-left-style: none" alt="Smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/2541.wlEmoticon-smile_120EAB63.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/2541.wlEmoticon_2D00_smile_5F00_120EAB63.png"></pre></noscript>
<p><strong><u>NOTE</u></strong>: If you want to use this script then you have to modify top part of in order to use your correct Azure Subscription name and correct management certificate. And you have to also change the Azure resource names (storage, HDInsight) so that you have unique names for those resources.</p>
<p>After the process you end up with "<em>Input32/part-00000</em>" file in your local folder: <script src="https://gist.github.com/JanneMattila/50a11e453faa0175137f.js"></script><noscript><pre>6442450943	10215411760019992	OQDPKIPD2PUWGUXVZXUWMKXJJLP2AIHJ1M5W7Y6XR4WYMK4RJLCKSQBJQELJJB
8589410303	10215411760019992	EQHJAIPDNPQOSQ4R1YR4CA7YXZ2PAIJHM1LJ1YQEFD6XYWGIP25WDPP2UW2PPN
8589869055	40861647040079968	SQ4RWYR47YZXUWFRMKXV5WJL1M6XMKP2HJGUAIUW2PPDRFCKKIQ3DPOQBJJX3Q
8589926399	10215411760019992	OQDPGIUGWU5WXVZX7YXZ1YR4JHGIFRMKRFTRCKRFPDACCKDF6XUWFRQSWY4RRT
8589934589	10215411760019992	SQ4RWYR47YZXUWFRMKXV5WJL1M6XMKP2HJGUAIUW2PPDRFCKKIQ3DPOQBJJXX6</pre></noscript>
<p>And that of course contains that magical number in the third row.</p>
<p>Okay we have now demonstrated that we can use HDInsight to run our Hadoop Streaming tasks. Of course this kind of solving task is far from optimal (in performance wise and just by pure solution wise) for our problem but it’s still quite cool way to run the actual solving process <img class="wlEmoticon wlEmoticon-smile" style="border-top-style: none; border-bottom-style: none; border-right-style: none; border-left-style: none" alt="Smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/2541.wlEmoticon-smile_120EAB63.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/2541.wlEmoticon_2D00_smile_5F00_120EAB63.png">. Now go and implement your own algorithms and logics using Azure PowerShell!</p>
<p>Anyways... Happy hacking! <br><br>J</p>]]></content:encoded>
    </item>
    <item>
      <title>Solving My Pocket Solitaire using Bottom-Up method</title>
      <link>https://docs.microsoft.com/archive/blogs/jannemattila/solving-my-pocket-solitaire-using-bottom-up-method</link>
      <pubDate>Wed, 01 Oct 2014 12:26:46 GMT</pubDate>
      <dc:creator><![CDATA[Janne Mattila 2]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/jannemattila/2014/10/01/solving-my-pocket-solitaire-using-bottom-up-method/</guid>
      <description><![CDATA[This post continues My Pocket Solitaire series.   In my previous post I went through how to solve...]]></description>
      <content:encoded><![CDATA[<p>This post continues <a title="All post about My Pocket Solitaire" href="http://blogs.msdn.com/jannemattila/archive/tags/my+pocket+solitaire/" target="_blank">My Pocket Solitaire</a> series. </p>  <p>In my <a href="http://blogs.msdn.com/b/jannemattila/archive/2014/06/16/solving-my-pocket-solitaire-using-top-down-method.aspx" target="_blank">previous post</a> I went through how to solve this puzzle using top-down approach. However as I explained it’s quite inefficient way to just “<em>brute force</em>” the tree from Top-Down and try to get possible solutions.</p>  <p>So what if we would like to know that <em>how many unique solutions there are in this puzzle</em>? Getting solution for that question using Top-Down method would take very long time… therefore we need other ways to answer that question. This brings us to Bottom-Up method which is pretty good fit for this kind of problem. More about <a href="http://en.wikipedia.org/wiki/Top-down_and_bottom-up_design" target="_blank">Top-Down and Bottom-Up design in Wikipedia</a>.</p>  <p>Idea of bottom-up solving starts from the core idea that since we know the desired target state of the board (a.k.a. end state) then we can use that information to remove a lot of unwanted board states during processing. If you compare this to Top-Down then you don’t actually know that does this certain selected tree path ever lead to target board state. And since you have to process the tree to last possible state before you can say that did we reach the target state or no… you’ll do a lot of unnecessary work. And in simple terms…. if you do a lot of unnecessary work you end up being slow and vise versa <img class="wlEmoticon wlEmoticon-smile" style="border-top-style: none; border-bottom-style: none; border-right-style: none; border-left-style: none" alt="Smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/2022.wlEmoticon-smile_6C1608C5.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/2022.wlEmoticon_2D00_smile_5F00_6C1608C5.png" />. In Bottom-Up method we can remove a lot of unnecessary work because we <strong>*know*</strong> that we’re starting from <strong>*valid*</strong> end position and all the paths to the root contribute to the final solution count.</p>  <p>Of course there is downside in this solution <strong>=&gt;</strong>This&#160; is more complex solution than the standard Top-Down approach. So if you want to use this kind of algorithms in your own applications then you need to pay more attention when implementing it. Next I’ll try to describe Bottom-Up approach so that it would make sense to you. Here’s the <a href="http://en.wikipedia.org/wiki/Pseudocode">Pseudocode</a> of it:</p>  <div class="myEditorContainerClass" style="height: 250px"><div id="myEditor2" class="myEditorClass"><pre>Initialize list of previous board states with target state of board
Initialize list of board states to empty

Loop 31 times
  Clear list of board states
  For each board state in list of previous board states
    Restore board state to current board state
    Get list of valid backward moves from this current board state
    For each move in valid backward moves list
      Make backward move from this current board state
      Store new board state to list of board states
		
  Aggegate all board states in the list of board states
  Set list of previous board states to be list of board states
  
End result is at the list of previous board states</pre></div></div>
<script type="text/javascript">
var editor2 = ace.edit("myEditor2");
editor2.setTheme("ace/theme/textmate");
editor2.getSession().setMode("ace/mode/text");
editor2.getSession().setUseWrapMode(true);
editor2.setReadOnly(true);
</script>

<p>First we have create lists where we store information about board states that the algorithm is currently working on. Then we start loop which we’ll repeat 31 times (depth of the solution tree <img class="wlEmoticon wlEmoticon-smile" style="border-top-style: none; border-bottom-style: none; border-right-style: none; border-left-style: none" alt="Smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/2022.wlEmoticon-smile_6C1608C5.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/2022.wlEmoticon_2D00_smile_5F00_6C1608C5.png" />). Inside that loop we’ll restore previously stored board state. Then we’ll do all the possible backward moves from that board state so that we get new board states but all of them are one level up in the solution tree (and thus the Bottom-Up naming). Since we’re restoring one-by-one all the previously stored board states and then getting all board states of one level up from those we’ll might be getting duplicate board states at the end. Therefore we need to “aggregate” (or “group”) those duplicates away. And when we have repeated this logic for 31 times we’ll be having list with 5 items which describe the board state where all the paths led to. You might be wondering that how come 5 items in the list since only 1 would be correct answer but I’ll answer that later. </p>

<p>Let’s walkthrough the implementation step-by-step. So first we set the board to end state:</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/1805.Backward-moves-from-target-state_002F254F.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/1805.Backward_2D00_moves_2D00_from_2D00_target_2D00_state_5F00_002F254F.png"><img title="Backward moves from target state" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Backward moves from target state" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/5633.Backward-moves-from-target-state_thumb_0B5B404A.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/5633.Backward_2D00_moves_2D00_from_2D00_target_2D00_state_5F00_thumb_5F00_0B5B404A.png" width="480" height="480" /></a></p>

<p>From this end state we have to get valid backward moves. Valid moves are highlighted in the above image with red arrows. </p>

<p>Next we try to remove duplicates board states but there isn’t yet duplicates in this first round. Then we’ll store these 4 board states to list and continue with next iteration of the loop. Again we’ll get valid backward moves but this time we have to repeat the process for all 4 board states that we have stored earlier. This will give us then 12 new board states in this iteration (see <a href="http://blogs.msdn.com/b/jannemattila/archive/2014/06/16/solving-my-pocket-solitaire-using-top-down-method.aspx" target="_blank">previous post</a> which has table and graph about the growing ratio). And again there are no duplicates in this round so we can continue to next iteration. which gives us 60 new board states and no duplicates. However next iteration is interesting since we’ll get 400 new board states but when we get rid of the duplicates we will be left with only 296 new board states. This means that there are quite many paths that lead to exactly same board state. And since we’re now focusing to answer the question that “<em>how many unique solutions there are in this puzzle”</em> we can safely get rid of the duplicates. And if you can get rid of 100+ unnecessary calculations in one level you can just imagine what this does to performance in the long run! But of course we cannot just blindly remove duplicates because that would lead to wrong end result. We have to aggregate those solution counts together before we ignore the duplicate. This just means that if two paths come together then you have to make sure that you count them together that you know how many times you can end up to the final position from this particular position.</p>

<p>Then we’ll just keep repeating above formula until we’re left to the last position on the board. Maybe surprisingly there are suddenly five board positions still left. One of them is the real solution where the last missing piece is really in the middle of board. Other four solutions are marked with yellow color: 
  <br /><img title="Board" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Board" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/4812.Board_2CDA6FD9.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/4812.Board_5F00_2CDA6FD9.png" width="218" height="246" /></p>

<h3>Magic number</h3>

<p>And this solution with the green color will give us magical number of 40861647040079968 (formatted: 40’861’647’040’079’968). That is so large number that Excel displays it like this: 4.086E+16. So you can say that this game has 40 <a title="Peta" href="http://en.wikipedia.org/wiki/Peta-" target="_blank">peta</a>solutions! Similarly you end up to these <em>yellow </em>(from above picture) start positions and they have each 10215411760019992 solutions (I mean that if you would start from that position you would end up to final position with this many different routes). If you them sum up these four <em>yellow</em> start up position solutions then it will lead again to same magic number 40861647040079968 <img class="wlEmoticon wlEmoticon-smile" style="border-top-style: none; border-bottom-style: none; border-right-style: none; border-left-style: none" alt="Smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/2022.wlEmoticon-smile_6C1608C5.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/2022.wlEmoticon_2D00_smile_5F00_6C1608C5.png" />.</p>

<h3>How long does it take to calculate this?</h3>

<p>If you want to compare this to the Top-Down approach (or Bottom-Up but without “grouping” of similar board positions) then I think below picture tells it all. X-axis is the depth of the tree in processing and Y-axis is the number of board positions:</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/6574.Bottom-Up_03D2618E.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/6574.Bottom_2D00_Up_5F00_03D2618E.png" target="_blank"><img title="Bottom-Up" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Bottom-Up" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/5554.Bottom-Up_thumb_7359F092.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/5554.Bottom_2D00_Up_5F00_thumb_5F00_7359F092.png" width="640" height="472" /></a></p>

<p>From that it’s quite easy to see that you optimize the performance a lot because you can eliminate duplicate board positions away and thus don’t waste any energy on processing them.</p>

<p>I have implemented this <a href="http://en.wikipedia.org/wiki/Algorithm">Algorithm</a> in C++ using different mechanisms such as:</p>

<ol>
  <li>Single thread </li>

  <li>Multithread </li>

  <li><a href="http://msdn.microsoft.com/en-us/library/dd492418.aspx" target="_blank">Parallel Patterns Library (PPL)</a> </li>

  <li>Mapper-Reducer – Multiple processes (more about this in future posts) </li>
</ol>

<p>Multithread approach takes on my laptop 1,5 hours! This is not bad if you take into consideration complexity of the given task.</p>

<p>Hopefully you got an idea how you could use Bottom-Up method to solve some tough problems. In future posts I’ll open up more different implementations such as mapper-reducer etc.</p>

<p>Anyways... Happy hacking! 
  <br />

  <br />J</p>]]></content:encoded>
    </item>
    <item>
      <title>Solving My Pocket Solitaire using Top-Down method</title>
      <link>https://docs.microsoft.com/archive/blogs/jannemattila/solving-my-pocket-solitaire-using-top-down-method</link>
      <pubDate>Mon, 16 Jun 2014 13:19:53 GMT</pubDate>
      <dc:creator><![CDATA[Janne Mattila 2]]></dc:creator>
      <guid
        isPermaLink="false">https://blogs.msdn.microsoft.com/jannemattila/2014/06/16/solving-my-pocket-solitaire-using-top-down-method/</guid>
      <description><![CDATA[This post continues My Pocket Solitaire series.   This time we’re starting to open up the solving...]]></description>
      <content:encoded><![CDATA[<p>This post continues <a title="All post about My Pocket Solitaire" href="http://blogs.msdn.com/jannemattila/archive/tags/my+pocket+solitaire/" target="_blank">My Pocket Solitaire</a> series. </p>  <p>This time we’re starting to open up the solving logic for this puzzle. Playing of the game starts from the initial position:</p>  <div id="canvasSection"><canvas id="canvas1">No canvas support so cannot display the board :-( Sorry!</canvas></div>  <div id="caption1"></div>  <p>From that initial state you should end up into this target state:</p>  <div id="canvasSection"><canvas id="canvas2">No canvas support so cannot display the board :-( Sorry!</canvas></div>  <div id="caption2"></div>  <p>In order to achieve that you have to make series of valid moves where you jump over piece with another piece into empty space and then you remove the piece which got “jumped over” (read more from <a href="http://en.wikipedia.org/wiki/Peg_solitaire" target="_blank">here</a>). </p>  <p>Now we have actually defined all the necessary definitions what we need in order to proceed further:</p>  <ul>   <li>Initial state </li>    <li>Valid move </li>    <li>Target state </li> </ul>  <p>And us human beings tend to solve these kind of puzzles using “top-down” thinking. It’s easiest way to start but at the same time it’s extremely inefficient. But before we’ll talk more about the efficiency part let’s take a look at <a href="http://en.wikipedia.org/wiki/Pseudocode">Pseudocode</a> about this top-down solving logic: </p>  <div class="myEditorContainerClass" style="height: 220px">   <div class="myEditorClass" ID="myEditor1"><pre>Solve 
  Validate board state
  If board is at the target state
    Hurray!
  Else
    Get list of valid moves for current state
    For each move in valid moves list
      Make move
	  Recursively call Solve
      Undo move

Program
  Initialize board to initial state
  Call Solve</pre></div>
</div>
<script type="text/javascript">
var editor1 = ace.edit("myEditor1");
editor1.setTheme("ace/theme/textmate");
editor1.getSession().setMode("ace/mode/text");
editor1.getSession().setUseWrapMode(true);
editor1.setReadOnly(true);
</script>

<p>You can see that this <a href="http://en.wikipedia.org/wiki/Algorithm">Algorithm</a> is very simple and into some extend it even models “human thinking” (but when humans tend to get stuck they go back to the initial state instead of recovering to the previous state). Pseudo program starts from the line 12 and it first initializes board to initial state and then it calls <a href="http://en.wikipedia.org/wiki/Recursion" target="_blank">recursive</a> method called <em>Solve</em>. Solve follows simple logic:</p>

<ol>
  <li>Am I already at the target state? If yes then <em>Hurray</em>! </li>

  <li>If no which means we have to take all available valid moves from current board state </li>

  <li>For each of the available board moves make move and recursively call <em>Solve</em> </li>

  <li>When call returns back then undo previous move (recover to state where we still had options)</li>
</ol>

<p>This logic is easy to read and easy to implement. So if you’re just starting programming I think this is good exercise to get you started with algorithms <img class="wlEmoticon wlEmoticon-winkingsmile" style="border-top-style: none; border-bottom-style: none; border-right-style: none; border-left-style: none" alt="Winking smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/2262.wlEmoticon-winkingsmile_17EFBBEF.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/2262.wlEmoticon_2D00_winkingsmile_5F00_17EFBBEF.png" />.</p>

<p>However as I mentioned it’s inefficient. So how <strong>*bad*</strong> is the performance of this then? Well simple diagram demonstrates it pretty well (click image to see it larger):</p>

<p><a href="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/4743.Subtrees-top-down_3D679035.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/4743.Subtrees_2D00_top_2D00_down_5F00_3D679035.png" target="_blank"><img title="Subtrees top-down" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Subtrees top-down" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/4643.Subtrees-top-down_thumb_2B2CAA4B.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/4643.Subtrees_2D00_top_2D00_down_5F00_thumb_5F00_2B2CAA4B.png" width="629" height="480" /></a></p>

<p>X-axis of the diagram is tree level in solution. Meaning level 1 indicates initial state where there are 4 valid moves available (in another words 4 subtrees from that given position). Level 2 already has 12 subtrees etc. You can better see this from this table:</p>

<p><img title="Subtrees top-down 2" style="border-left-width: 0px; border-right-width: 0px; background-image: none; border-bottom-width: 0px; padding-top: 0px; padding-left: 0px; display: inline; padding-right: 0px; border-top-width: 0px" border="0" alt="Subtrees top-down 2" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/4578.Subtrees-top-down-2_0F0A4245.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/4578.Subtrees_2D00_top_2D00_down_2D00_2_5F00_0F0A4245.png" width="315" height="411" /></p>

<p><script src="http://jannemattila.github.io/MyPocketSolitaire/javascripts/require.js"></script><script>
		require.config({
			baseUrl: "http://jannemattila.github.io/MyPocketSolitaire/javascripts/"
		});
	
        require(["MyPocketSolitaireJS"],
        function (myPocketSolitaire) {
            myPocketSolitaire.Run({
                canvas: "canvas1",
                caption: "caption1"
            });
            myPocketSolitaire.Run({
                canvas: "canvas2",
                caption: "caption2",
                game: "3QZX7YR4FRMKJL577YR4WYHJUW4RAIGUJXXVPD1MUW2PMKSQCAAIPDDFFRRPOQ",
                animateMoves: false
            });
        });
    </script>Y-axis of the diagram is count of subtrees in <a href="http://en.wikipedia.org/wiki/Logarithmic_scale" target="_blank">logarithmic scale</a>. So it’s pretty easy to understand from the diagram that count of subtrees pretty much explodes. It just means that if you use this “top-down” method when solving this (or similar logical problems) you’ll end up into poor performance IF your target is to maximize the solving performance.</p>

<p>Quite often when I talk about this kind of logical problems with someone I get these kind of comments (or very similar): “<em>Just add some parallel execution to it and it’s way faster then</em>”. Well I don’t think that you should use horse power to solve problems if you’re using completely wrong algorithm <img class="wlEmoticon wlEmoticon-smile" style="border-top-style: none; border-bottom-style: none; border-right-style: none; border-left-style: none" alt="Smile" src="https://msdnshared.blob.core.windows.net/media/MSDNBlogsFS/prod.evol.blogs.msdn.com/CommunityServer.Blogs.Components.WeblogFiles/00/00/00/76/84/metablogapi/7266.wlEmoticon-smile_22B9BC8A.png" original-url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-00-76-84-metablogapi/7266.wlEmoticon_2D00_smile_5F00_22B9BC8A.png" />. First you implement better algorithm (and I prefer to do it with single thread approach since it has many advantages and maybe I’ll come back to this in the future posts) and then you can think how to leverage available horse power from the machine(s). But remember that horse power doesn’t ever fix bad algorithm.</p>

<p>And if you would like to know how many unique solutions there are in this board game then you wouldn’t get answer to your question when implemented using this method. In future posts we’ll cover that topic too.</p>

<p>Anyways... Happy hacking! 
  <br />

  <br />J</p>]]></content:encoded>
    </item>
  </channel>
</rss>