<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Tomas Jansson]]></title><description><![CDATA[Me, myself and I]]></description><link>https://blog.2mas.xyz/</link><image><url>https://blog.2mas.xyz/favicon.png</url><title>Tomas Jansson</title><link>https://blog.2mas.xyz/</link></image><generator>Ghost 6.44</generator><lastBuildDate>Tue, 09 Jun 2026 08:02:02 GMT</lastBuildDate><atom:link href="https://blog.2mas.xyz/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Introducing F# intro]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>A couple of months back I was asked if could do a introductory workshop about F# for <a href="https://www.activesolution.se/?ref=blog.2mas.xyz">Active Solution</a> during their internal conference in the Pyrenees, Spain. Of course I said yes and that was the start of this brand new workshop material for F#.</p>
<p>TL;DR: <a href="https://mastoj.github.io/FSharpIntro/?ref=blog.2mas.xyz#/">https://mastoj.github.</a></p>]]></description><link>https://blog.2mas.xyz/introducing-f-intro/</link><guid isPermaLink="false">5e382b29f81c630018abe077</guid><category><![CDATA[FSharp]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Sun, 21 May 2017 21:08:39 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>A couple of months back I was asked if could do a introductory workshop about F# for <a href="https://www.activesolution.se/?ref=blog.2mas.xyz">Active Solution</a> during their internal conference in the Pyrenees, Spain. Of course I said yes and that was the start of this brand new workshop material for F#.</p>
<p>TL;DR: <a href="https://mastoj.github.io/FSharpIntro/?ref=blog.2mas.xyz#/">https://mastoj.github.io/FSharpIntro/#/</a></p>
<p>When I have previously done introductory workshops in F# I have used the awesome material from <a href="http://www.fsharpworkshop.com/?ref=blog.2mas.xyz">http://www.fsharpworkshop.com/</a> by <a href="https://twitter.com/jorgefioranelli?ref=blog.2mas.xyz">Jorge Fioranelli</a>, but this time decided to create my own material. The reason for doing so is that I wanted the material to feel more like my own while presenting it, and I also wanted to contribute back to the community. Both Jorge&apos;s workshop and my have a lot of similarities and cover much of the same material, as they should since they are introductory workshops, but there are small differences in the way it is structured. I really do recommend the workshop by Jorge&apos;s as well, and I even think it make sense to go through both for repeated learning.</p>
<p>I felt that the workshop was well received, but I leave that to the kind people at Active Solution to confirm :). The initial plan was that I would get four hours, but due to some delays I got roughly 2-2.5 hours, so you will need at least four hours to cover everything in a workshop setting. It is likely that it will take even longer if you have an curious crowd, as I had, since that will most likely result in a lot of questions, which I think is more important to answer than actual progress in the workshop. So when doing the workshop I recommend time boxing the workshop and do as much as you can.</p>
<p>You can find the start of the workshop at this link <a href="https://mastoj.github.io/FSharpIntro/?ref=blog.2mas.xyz#/">https://mastoj.github.io/FSharpIntro/#/</a>, which contains all the presentation slides and links to github repo and exercises.</p>
<p>Let me know if you have any questions. If you find anything that is wrong in the material or have any question regarding the workshop, please comment here or open an issue on <a href="https://github.com/mastoj/FSharpIntro/issues?ref=blog.2mas.xyz">github</a>.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Setting up Event Store with kubernetes on google cloud]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>To prepare myself for my new job, which will involve some kubernetes stuff, I&apos;ve played around with it somewhat lately, as you could see in this <a href="https://blog.2mas.xyz/fsharp-suave-app-on-dotnet-core-on-kubernetes-on-google-cloud/">post</a>. This post is taking things one step further without making it that much more advanced. The goal for this post is</p>]]></description><link>https://blog.2mas.xyz/setting-up-event-store-with-kubernetes-on-google-cloud/</link><guid isPermaLink="false">5e382b29f81c630018abe075</guid><category><![CDATA[eventstore]]></category><category><![CDATA[kubernetes]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Wed, 23 Nov 2016 22:40:25 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>To prepare myself for my new job, which will involve some kubernetes stuff, I&apos;ve played around with it somewhat lately, as you could see in this <a href="https://blog.2mas.xyz/fsharp-suave-app-on-dotnet-core-on-kubernetes-on-google-cloud/">post</a>. This post is taking things one step further without making it that much more advanced. The goal for this post is to set up a <a href="http://geteventstore.com/?ref=blog.2mas.xyz">Event Store</a> cluster on google container engine with a simple script. A prerequisite to get any of this working is that you have installed <a href="https://cloud.google.com/sdk/?ref=blog.2mas.xyz"><code>gcloud</code></a> and <a href="https://cloud.google.com/container-engine/docs/quickstart?ref=blog.2mas.xyz"><code>kubectl</code></a>.</p>
<p>If you don&apos;t want to read the whole post and just go to the code you can look it up on <a href="https://github.com/mastoj/eventstore-kubernetes?ref=blog.2mas.xyz">github</a>. The <a href="https://github.com/mastoj/eventstore-kubernetes/tree/naive?ref=blog.2mas.xyz"><code>na&#xEF;ve</code></a> and <a href="https://github.com/mastoj/eventstore-kubernetes?ref=blog.2mas.xyz"><code>master</code></a> branches will be described in this post.</p>
<h2 id="disclaimer">Disclaimer</h2>
<p>What I will describe here will expose the Event Store cluster to the public and is something you <strong>should not</strong> do, I do it to make it easier to test that it works. I haven&apos;t done any performance tests or reliability tests on my setup either, which you should probably do before using it in production.</p>
<h2 id="theendgoal">The end goal</h2>
<p>I did two different approaches, which both will be covered in this post, that had the same end goal. I wanted to have a cluster of Event Store nodes running behind a <a href="http://kubernetes.io/docs/user-guide/services/?ref=blog.2mas.xyz#headless-services">headless kubernetes service</a> and nginx on top of that to add access to the public. Using a headless kubernetes service will result in a service registered with a dns registration that resolves to all the IPs for the associated containers, and this is exactly what EventStore needs to to discovery through dns.</p>
<h2 id="configuringnginx">Configuring nginx</h2>
<p>I put this section first since it is the same for both approaches.</p>
<h3 id="nginxconfiguraion">Nginx configuraion</h3>
<p>The configuration of nginx will be stored in a <code>configmap</code> and looks like this, <a href="https://github.com/mastoj/eventstore-kubernetes/blob/master/nginx/frontend.conf:?ref=blog.2mas.xyz">https://github.com/mastoj/eventstore-kubernetes/blob/master/nginx/frontend.conf:</a></p>
<pre><code>upstream es {
    server es.default.svc.cluster.local:2113;
}
server {
    listen 2113;
    location / {
        proxy_set_header    X-Real-IP $remote_addr;
        proxy_set_header    Host      $http_host;
        proxy_pass          http://es;
    }
}
</code></pre>
<p>If you know nginx, this is just basic configuration. First we create an <code>upstream</code> that can be references later on by our <code>proxy_pass</code> when someone is visiting the path <code>/</code>. The url <code>es.default.svc.cluster.local</code> is the dns registration that our Event Store node will get when we get to that point. The <code>server</code> section just defines that we should listen on port <code>80</code> and proxy the traffic to the <code>upstream </code> defined.</p>
<p>To create the <code>configmap</code> we can execute this command</p>
<pre><code>kubectl create configmap nginx-es-frontend-conf --from-file=nginx/frontend.conf
</code></pre>
<h3 id="thenginxdeployment">The nginx deployment</h3>
<p>This is basically the same as I used in the previous post, if you read that one. The <a href="https://github.com/mastoj/eventstore-kubernetes/blob/master/deployments/frontend-es.yaml?ref=blog.2mas.xyz">specification</a> looks like this:</p>
<pre><code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: frontend-es
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: frontend-es
        track: stable
    spec:
      containers:
        - name: nginx
          image: &quot;nginx:1.9.14&quot;
          lifecycle:
            preStop:
              exec:
                command: [&quot;/usr/sbin/nginx&quot;,&quot;-s&quot;,&quot;quit&quot;]
          volumeMounts:
            - name: &quot;nginx-es-frontend-conf&quot;
              mountPath: &quot;/etc/nginx/conf.d&quot;
      volumes:
        - name: &quot;nginx-es-frontend-conf&quot;
          configMap:
            name: &quot;nginx-es-frontend-conf&quot;
            items:
              - key: &quot;frontend.conf&quot;
                path: &quot;frontend.conf&quot;
</code></pre>
<p>It only contains one container, the <code>nginx</code> one, which uses the <code>configmap</code> created above for configuration. We only need one replica at the moment.</p>
<p>To create it we run the following command</p>
<pre><code>kubectl create -f deployments/frontend-es.yaml
</code></pre>
<h3 id="thenginxservice">The nginx service</h3>
<p>To create a public IP we need to create a service on top of this deployment. The <a href="https://github.com/mastoj/eventstore-kubernetes/blob/master/services/frontend-es.yaml?ref=blog.2mas.xyz">specification</a> for the service looks like this:</p>
<pre><code>kind: Service
apiVersion: v1
metadata:
  name: &quot;frontend-es&quot;
spec:
  selector:
    app: &quot;frontend-es&quot;
  ports:
    - protocol: &quot;TCP&quot;
      port: 2113
      targetPort: 2113
  type: LoadBalancer
</code></pre>
<p>To create the service and finish up the nginx part of the post we run the following command</p>
<pre><code>kubectl create -f services/frontend-es.yaml
</code></pre>
<h2 id="firstapproachthenaveone">First approach - the na&#xEF;ve one</h2>
<p>The first thing I wanted to do was to get a cluster up and running without persisting the data to disk, that is, only keep the data in the container. A cluster like that might work for development, but not in production. My grand masterplan was to just add persistent to that cluster after the cluster was up and running, which did not work. How to get persistent will be covered under <a href="#secondapproachaddingpersistentdata"><em>Second approach</em></a>. Before we get into the persistent part, let&apos;s get this cluster up and running.</p>
<h3 id="creatingthedeployment">Creating the deployment</h3>
<p>The <a href="https://github.com/mastoj/eventstore-kubernetes/blob/naive/deployments/eventstore.yaml?ref=blog.2mas.xyz">deployment file</a> is really simple:</p>
<pre><code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: es
spec:
  replicas: 3
  template:
    metadata:
      labels:
        app: es
    spec:
      containers:
        - name: es
          image: &quot;eventstore/eventstore&quot;
          env: 
            - name: EVENTSTORE_INT_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: EVENTSTORE_EXT_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: EVENTSTORE_INT_TCP_PORT
              value: &quot;1111&quot;
            - name: EVENTSTORE_EXT_TCP_PORT
              value: &quot;1112&quot;
            - name: EVENTSTORE_INT_HTTP_PORT
              value: &quot;2114&quot;
            - name: EVENTSTORE_EXT_HTTP_PORT
              value: &quot;2113&quot;
            - name: EVENTSTORE_CLUSTER_SIZE
              value: &quot;3&quot;
            - name: EVENTSTORE_CLUSTER_DNS
              value: &quot;es.default.svc.cluster.local&quot;
            - name: EVENTSTORE_CLUSTER_GOSSIP_PORT
              value: &quot;2114&quot;
            - name: EVENTSTORE_GOSSIP_ALLOWED_DIFFERENCE_MS
              value: &quot;600000&quot;
            - name: EVENTSTORE_INT_HTTP_PREFIXES
              value: &quot;http://*:2114/&quot;
            - name: EVENTSTORE_EXT_HTTP_PREFIXES
              value: &quot;http://*:2113/&quot;
          ports:
            - containerPort: 2113
            - containerPort: 2114
            - containerPort: 1111
            - containerPort: 1112
</code></pre>
<p>We use the Event Store docker image from <a href="https://hub.docker.com/r/eventstore/eventstore/?ref=blog.2mas.xyz">docker hub</a>. This image doesn&apos;t allow command line arguments, so we need to use environment variables to configure it. You can read about Event Store configuration <a href="http://docs.geteventstore.com/server/3.9.0/command-line-arguments/?ref=blog.2mas.xyz">here</a>. Every container (we are running three here) need to use their own IP during configuration, and with kubernetes we can access that data through <code>status.podIP</code> when we configure the environment variables.</p>
<p>Creating is as simple as before:</p>
<pre><code>kubectl create -f deployments/eventstore.yaml
</code></pre>
<p>That should create a three nodes, but as of this moment they will fail to find each other, and that is why we need the service.</p>
<h3 id="creatingtheservice">Creating the service</h3>
<p>Creating the service is even easier than the deployment. The <a href="https://github.com/mastoj/eventstore-kubernetes/blob/naive/services/eventstore.yaml?ref=blog.2mas.xyz">specification file</a> looks like this:</p>
<pre><code>kind: Service
apiVersion: v1
metadata:
  name: &quot;es&quot;
spec:
  selector:
    app: &quot;es&quot;
  ports:
    - protocol: &quot;TCP&quot;
      port: 2113
      targetPort: 2113
  clusterIP: None
</code></pre>
<p>We only expose the 2113 port, which means that we will only be able to talk over http to the event store cluster. To the service we name all the containers that has the label <code>app: &quot;es&quot;</code>. The last thing to know is that we set the <code>clusterIP</code> to <code>None</code>, this will not create one single IP in the DNS for this service, instead it will resolve to all the IPs of the containers and that is exactly what Event Store needs to be able to configure itself.</p>
<p>Again we are using <code>kubectl</code> to create the service:</p>
<pre><code>kubectl create -f services/eventstore.yaml
</code></pre>
<p>When this is created we should now be ready to test it.</p>
<h3 id="test">Test</h3>
<p>To test that it works run the following command:</p>
<pre><code>kubectl get services
</code></pre>
<p>In the result from that command you will find an <code>External IP</code>. To access Event Store, open the browser and go to <code>&lt;external ip&gt;:2113</code>. If everything works as expected you should now have access to Event Store.</p>
<h3 id="challengeswithapproachone">Challenges with approach one</h3>
<p>The major challenge is persistent data, how do you map one persistent volume to each node in the cluster? Leave a comment on the post if you have any idea.</p>
<p>Let us say that you solve the first problem, how do you make sure the nodes get the same persistent volume the next time you restart the cluster?</p>
<p>Both those two problems is what got me started working on the second approach.</p>
<p>There is a third problem, which we won&apos;t fix, and that is increasing the number of replicas won&apos;t work. The reason be that Event Store doesn&apos;t support elastic scaling, so increasing the number of replicas will only add &quot;clones&quot; to the cluster, not increase its size.</p>
<h2 id="secondapproachaddingpersistentdata">Second approach - adding persistent data</h2>
<p>We are still going to use deployments, but instead of letting the number of replicas define the number of nodes we will create one deployment with one replica per node. This way we can force each node to get access to the same persistent data volume when it is restarted, and using deployments will also handle restart for us.</p>
<h3 id="generatingdeployment">Generating deployment</h3>
<p>The difference from the first approach here is that we will generate the deployment from a template instead of creating one. For this to work we need both a template and a simple script that generates the deployments. The <a href="https://github.com/mastoj/eventstore-kubernetes/blob/master/templates/es_deployment_template.yaml?ref=blog.2mas.xyz">template file</a> looks like this:</p>
<pre><code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: es-${nodenumber}
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: es-${nodenumber}
        escluster: es
    spec:
      containers:
        - name: es-${nodenumber}
          image: &quot;eventstore/eventstore&quot;
          env: 
            - name: EVENTSTORE_INT_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: EVENTSTORE_EXT_IP
              valueFrom:
                fieldRef:
                  fieldPath: status.podIP
            - name: EVENTSTORE_INT_TCP_PORT
              value: &quot;1111&quot;
            - name: EVENTSTORE_EXT_TCP_PORT
              value: &quot;1112&quot;
            - name: EVENTSTORE_INT_HTTP_PORT
              value: &quot;2114&quot;
            - name: EVENTSTORE_EXT_HTTP_PORT
              value: &quot;2113&quot;
            - name: EVENTSTORE_CLUSTER_SIZE
              value: &quot;${nodecount}&quot;
            - name: EVENTSTORE_CLUSTER_DNS
              value: &quot;es.default.svc.cluster.local&quot;
            - name: EVENTSTORE_CLUSTER_GOSSIP_PORT
              value: &quot;2114&quot;
            - name: EVENTSTORE_GOSSIP_ALLOWED_DIFFERENCE_MS
              value: &quot;600000&quot;
            - name: EVENTSTORE_INT_HTTP_PREFIXES
              value: &quot;http://*:2114/&quot;
            - name: EVENTSTORE_EXT_HTTP_PREFIXES
              value: &quot;http://*:2113/&quot;
            - name: EVENTSTORE_DB
              value: &quot;/usr/data/eventstore/data&quot;
            - name: EVENTSTORE_LOG
              value: &quot;/usr/data/eventstore/log&quot;
          ports:
            - containerPort: 2113
            - containerPort: 2114
            - containerPort: 1111
            - containerPort: 1112
          volumeMounts:
            - mountPath: &quot;/usr/data/eventstore&quot;
              name: espd
      volumes:
        - name: espd
          gcePersistentDisk:
            pdName: esdisk-${nodenumber}
            fsType: ext4
</code></pre>
<p>The template looks almost the same as in the first case, but we have now added two; <code>nodenumber</code> and <code>nodecount</code>. We have also added a <code>gcePersistentDisk</code> which we mount to <code>usr/data/eventstore</code>, and that is the parent folder we use for logs and data in the configuration of Event Store, <code>EVENTSTORE_DB</code> and <code>EVENTSTORE_LOGS</code>. We have also added a new label <code>escluster</code> which will be used for the service to identify which nodes that should be included in the service.</p>
<p>To generate the actual deploy files we run a bash script that has the following content:</p>
<pre><code>    for ((c=1; c&lt;=$count; c++ ))
    do
        cat ../templates/es_deployment_template.yaml | sed -e &quot;s/\${nodenumber}/$c/&quot; | sed -e &quot;s/\${nodecount}/$count/&quot; &gt; .tmp/es_deployment_$c.yaml
    done
</code></pre>
<p>Running that will generate one file for each node, and each file has its own volume mounted. The script as a whole can be found <a href="https://github.com/mastoj/eventstore-kubernetes/blob/master/scripts/create_cluster.sh?ref=blog.2mas.xyz">here</a>.</p>
<p>When the files has been generated we can then run:</p>
<pre><code>    for ((c=1; c&lt;=$count; c++ ))
    do
        kubectl apply -f .tmp/es_deployment_$c.yaml
    done
</code></pre>
<p>This code will create one deployment per file. Since we are using deployments our pods will be restarted if they crashes.</p>
<h3 id="creatingtheservice">Creating the service</h3>
<p>This is exactly the same as in the first approach, but with a minor change. We will use the <code>escluster</code> label to identify the pods to add to the service. The file is <a href="https://github.com/mastoj/eventstore-kubernetes/blob/master/services/eventstore.yaml?ref=blog.2mas.xyz">here</a></p>
<h3 id="thecreateclusterscript">The create cluster script</h3>
<p>It is not reasonable to execute any of this by hand, so I created this <a href="https://github.com/mastoj/eventstore-kubernetes/blob/master/scripts/create_cluster.sh?ref=blog.2mas.xyz">script</a>. I will dissect it here:</p>
<pre><code>#!/bin/bash

function init {
    rm -rf .tmp
    mkdir -p .tmp
}

function validateInput {
    count=$1
    re=&apos;^[0-9]+$&apos;
    if ! [[ $count =~ $re ]] ; then
        echo &quot;error: Not a number&quot; &gt;&amp;2; exit 1
    fi
}
</code></pre>
<p>The first part is just some house keeping and validating input arguments. The plan is that you should be able to create a cluster of any size by running: <code>./create_cluster.sh &lt;size&gt;</code>.</p>
<pre><code>function createSpecs {
    local count=$1
    for ((c=1; c&lt;=$count; c++ ))
    do
        cat ../templates/es_deployment_template.yaml | sed -e &quot;s/\${nodenumber}/$c/&quot; | sed -e &quot;s/\${nodecount}/$count/&quot; &gt; .tmp/es_deployment_$c.yaml
    done
}

function createDeployments {
    local count=$1
    for ((c=1; c&lt;=$count; c++ ))
    do
        kubectl apply -f .tmp/es_deployment_$c.yaml
    done
}
</code></pre>
<p>The next part defines functions to generate the deployment files and how they should be executed.</p>
<pre><code>function createEsService {
    kubectl create -f ../services/eventstore.yaml
}
</code></pre>
<p>This finish of the Event Store part of the script by creating a service on top of the nodes created by deployment.</p>
<pre><code>function addNginxConfig {
    kubectl create configmap nginx-es-frontend-conf --from-file=../nginx/frontend.conf
}

function createFrontendDeployment {
    kubectl create -f ../deployments/frontend-es.yaml
}

function createFrontendService {
    kubectl create -f ../services/frontend-es.yaml
}
</code></pre>
<p>The next part is basically what we described in the section about <code>nginx</code> setup.</p>
<pre><code>function createDisks {
    local count=$1
    for ((c=1; c&lt;=$count; c++ ))
    do
        if gcloud compute disks list esdisk-$c | grep esdisk-$c; then
            echo &quot;creating disk: esdisk-$c&quot; 
            gcloud compute disks create --size=10GB esdisk-$c
        else
            echo &quot;disk already exists: esdisk-$c&quot;
        fi
    done
}
</code></pre>
<p>A simple helper function to create disks on google cloud.</p>
<pre><code>function createEsCluster {
    local count=$1
    createSpecs $count
    createDeployments $count
    createEsService
}

function createFrontEnd {
    addNginxConfig
    createFrontendDeployment
    createFrontendService
}
</code></pre>
<p>The last two functions is just to make it easier to read what is going on.</p>
<pre><code>init
validateInput $1 #sets the variable $count
createDisks $count
createEsCluster $count
createFrontEnd
</code></pre>
<p>With all the functions defined it is quite clear what is going on in this script.</p>
<h3 id="test">Test</h3>
<p>The easier way to test it is to create the cluster:</p>
<pre><code>./create_cluster.sh 5
</code></pre>
<p>Add some data to the cluster. You do that by finding the external IP of the nginx service and then follow the <a href="http://docs.geteventstore.com/introduction/3.9.0/?ref=blog.2mas.xyz">getting started instructions</a> for Event Store to add some data.</p>
<p>With that in place you can kill pods as you like to simulate failures with:</p>
<pre><code>kubectl delete pod --now &lt;pod id&gt;
</code></pre>
<p>When you kill a pod a new should be created, but this time it should use the same persistent disk as the old one.</p>
<p>You can even delete the whole cluster and rebuild it again. I have added <a href="https://github.com/mastoj/eventstore-kubernetes/blob/master/scripts/delete_cluster.sh?ref=blog.2mas.xyz">delete cluster script</a> that will delete everything but the disks. If you then create the cluster again the data you added should still be there, since we are using the same disks for the cluster.</p>
<p>If you want to change the size of the cluster you can actually do that as well, just delete the cluster and create it again with a larger cluster size and that should work.</p>
<p>Note that if you delete and create the cluster you might end up with a new IP.</p>
<h2 id="summary">Summary</h2>
<p>I wouldn&apos;t say that this is perfect, but it definitely a start. One drawback is that it doesn&apos;t allow for zero downtime increase of cluster size. It could probably be added, but it is out of scope for this post. I haven&apos;t tested the performance either, and that is probably something you should do before actually using it. As I mentioned earlier, in a production environment you shouldn&apos;t expose Event Store to the public.</p>
<p>There is probably a lot more comments one can have about this setup, but I leave that up to you. Feel free to come with both positive and negative comments :).</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[F# Suave app on dotnet core on Kubernetes on Google Cloud]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>I haven&apos;t been doing that much F# dotnet core development, but I think it was time for me to try it out. One of the scenarios that I think it will be used a lot is on <a href="http://kubernetes.io/?ref=blog.2mas.xyz">kubernetes</a>. I choose to run it on google cloud so I</p>]]></description><link>https://blog.2mas.xyz/fsharp-suave-app-on-dotnet-core-on-kubernetes-on-google-cloud/</link><guid isPermaLink="false">5e382b29f81c630018abe074</guid><category><![CDATA[Suave]]></category><category><![CDATA[FSharp]]></category><category><![CDATA[kubernetes]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Thu, 17 Nov 2016 11:25:50 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>I haven&apos;t been doing that much F# dotnet core development, but I think it was time for me to try it out. One of the scenarios that I think it will be used a lot is on <a href="http://kubernetes.io/?ref=blog.2mas.xyz">kubernetes</a>. I choose to run it on google cloud so I didn&apos;t have to set up the infrastructure myself. I could probably have used Azure as well since they now have support for it in preview, but I think that google&apos;s implementation looks more mature and easier to use from the command line. So let get this little tutorial started.</p>
<h2 id="creatingtheapplication">Creating the application</h2>
<p>Before we need start we need to install the latest dotnet core bits, which we find here: <a href="https://www.microsoft.com/net/download/core?ref=blog.2mas.xyz">https://www.microsoft.com/net/download/core</a>. Clicking on <code>Current</code> tab we will find the latest bits (1.1.0 as of this moment). With dotnet installed we can get going.</p>
<h3 id="createproject">Create project</h3>
<p>The first is to create the project. Just navigate to a folder where you want your project and run this command to create a new F# project:</p>
<pre><code>dotnet new -l F#
</code></pre>
<p>Note that the folder name will be the name of the project, in my case it is <code>suavecore</code> and that will also be the name of the dll file created.</p>
<h3 id="updatereferences">Update references</h3>
<p>I made some minor changes to the <a href="https://github.com/mastoj/suavecore/blob/master/project.json?ref=blog.2mas.xyz"><code>project.json</code> file</a>:</p>
<pre><code>{
    &quot;version&quot;: &quot;1.0.0-*&quot;,
    &quot;buildOptions&quot;: {
        &quot;debugType&quot;: &quot;portable&quot;,
        &quot;emitEntryPoint&quot;: true,
        &quot;compilerName&quot;: &quot;fsc&quot;,
        &quot;compile&quot;: {
            &quot;includeFiles&quot;: [
                &quot;Program.fs&quot;
            ]
        }
    },
    &quot;dependencies&quot;: {
        &quot;Microsoft.FSharp.Core.netcore&quot;: &quot;1.0.0-alpha-*&quot;,
        &quot;Suave&quot;: &quot;2.0.0-rc2&quot;
    },
    &quot;tools&quot;: {
        &quot;dotnet-compile-fsc&quot;: &quot;1.0.0-preview2.1-*&quot;
    },
    &quot;frameworks&quot;: {
        &quot;netcoreapp1.0&quot;: {
            &quot;dependencies&quot;: {
                &quot;Microsoft.NETCore.App&quot;: {
                    &quot;type&quot;: &quot;platform&quot;,
                    &quot;version&quot;: &quot;1.1.0&quot;
                },
                &quot;Microsoft.FSharp.Core.netcore&quot;: &quot;1.0.0-alpha-161111&quot;
            }
        }
    }
}
</code></pre>
<p>I basically changed to the latest version of all the packages and added a reference to <a href="https://suave.io/?ref=blog.2mas.xyz">Suave</a>.</p>
<p>After the update we need to run</p>
<pre><code>dotnet restore
</code></pre>
<p>to install the dependencies.</p>
<h3 id="implementingtheapplication">Implementing the application</h3>
<p>The application implemented is really simple, it is a basic <code>Hello World</code> application that also prints the host name. It is a single file application and it all fits in <a href="https://github.com/mastoj/suavecore/blob/master/Program.fs?ref=blog.2mas.xyz"><code>Program.fs</code></a>:</p>
<pre><code class="language-language-fsharp">open Suave
open System.Net

type CmdArgs = { IP: System.Net.IPAddress; Port: Sockets.Port }

[&lt;EntryPoint&gt;]
let main argv = 

    // parse arguments
    let args =
        let parse f str = match f str with (true, i) -&gt; Some i | _ -&gt; None

        let (|Port|_|) = parse System.UInt16.TryParse
        let (|IPAddress|_|) = parse System.Net.IPAddress.TryParse

        //default bind to 127.0.0.1:8083
        let defaultArgs = { IP = System.Net.IPAddress.Loopback; Port = 8083us }

        let rec parseArgs b args =
            match args with
            | [] -&gt; b
            | &quot;--ip&quot; :: IPAddress ip :: xs -&gt; parseArgs { b with IP = ip } xs
            | &quot;--port&quot; :: Port p :: xs -&gt; parseArgs { b with Port = p } xs
            | invalidArgs -&gt;
                printfn &quot;error: invalid arguments %A&quot; invalidArgs
                printfn &quot;Usage:&quot;
                printfn &quot;    --ip ADDRESS   ip address (Default: %O)&quot; defaultArgs.IP
                printfn &quot;    --port PORT    port (Default: %i)&quot; defaultArgs.Port
                exit 1

        argv |&gt; List.ofArray |&gt; parseArgs defaultArgs

    let log x = printfn &quot;%A&quot; x; x

    let getHostName() = 
        Dns.GetHostName()

    // start suave
    startWebServer
        { defaultConfig with
            bindings = [ HttpBinding.create HTTP args.IP args.Port ] }
        (Successful.OK (sprintf &quot;Hello world: %s&quot; (getHostName())))

    0
</code></pre>
<p>That is all we need to try the application. If you run</p>
<pre><code>dotnet run
</code></pre>
<p>you will start the application and you can now pay a visit to <a href="http://localhost:8083/?ref=blog.2mas.xyz">http://localhost:8083</a>.</p>
<h3 id="publishingtheapplication">Publishing the application</h3>
<p>The last thing we need to do is to publish the application, this will create the bits that we will add to our docker container later on. Run</p>
<pre><code>dotnet publish -C Release
</code></pre>
<p>to publish the application to <code>bin/Release/netcoreapp1.0/publish</code>. If you navigate to that folder it is now possible to run the publish commands by executing</p>
<pre><code>dotnet suavecore.dll
</code></pre>
<p>This will start the web server and you can now navigate to <a href="http://localhost:8083/?ref=blog.2mas.xyz">http://localhost:8083</a> again. Note that <code>suavecore</code> is the name of my project, if you have a different name of the project folder your name might differ.</p>
<h2 id="buildingthecontainer">Building the container</h2>
<p>To be able to run this on kubernetes later on we will create a docker container. I have <a href="https://beta.docker.com/?ref=blog.2mas.xyz">docker beta for OSX</a> installed to build and try out the container. If you are following along I assume you to have that installed.</p>
<h3 id="creatingthedockerfile">Creating the Dockerfile</h3>
<p>The <a href="https://github.com/mastoj/suavecore/blob/master/Dockerfile?ref=blog.2mas.xyz">Dockerfile</a> is based on the official dotnet core image from microsoft and looks like this:</p>
<pre><code>FROM microsoft/dotnet:core
COPY ./bin/Release/netcoreapp1.0/publish /app
WORKDIR /app
EXPOSE 8083
ENTRYPOINT [&quot;dotnet&quot;, &quot;suavecore.dll&quot;]
</code></pre>
<p>It is quite straightforward what is going on. We base our image on the one from Microsoft as mentioned, then we copy our published app to the <code>app</code> folder in the container. We expose port <code>8083</code> to be able to access it from the outside and lastly we set the entry point to the command to start the application.</p>
<h3 id="buildingthecontainer">Building the container</h3>
<p>Building a container is as simple as</p>
<pre><code>docker build . -t mastoj/suavecore:v1.5
</code></pre>
<p>The container is tagged with the name of my repo for this image on <a href="https://hub.docker.com/r/mastoj/suavecore/?ref=blog.2mas.xyz">docker hub</a> and a version number so we can access the correct version when publishing to kubernetes later on.</p>
<h3 id="testingthecontainer">Testing the container</h3>
<p>Before we publish the container it might be smart to try it out locally first. So to create a container of the newly created image we run</p>
<pre><code>docker run -p=8083:8083 --name suave mastoj/suavecore:v1.5 --ip 0.0.0.0
</code></pre>
<p>The command above will start a running container of our image and name it <code>suave</code>. It will also map port <code>8083</code> on our local machine to port <code>8083</code> on the container. Lastly we will pass the arguments <code>--ip 0.0.0.0</code> to the application to tell it to listen all request no matter what the IP is.</p>
<p>Again you can try <a href="http://localhost:8083/?ref=blog.2mas.xyz">http://localhost:8083</a>, but this time you should get a little bit different response since the host name of the container is probably not the same as your machine.</p>
<h3 id="publishthecontainer">Publish the container</h3>
<p>We are now ready to publish the container. For this tutorial we are using a public repo to keep things simple.</p>
<pre><code>docker push mastoj/suavecore:v1.5
</code></pre>
<p>This will upload the image to docker hub and making it accessible to the public.</p>
<h2 id="settingupgooglecloud">Setting up google cloud</h2>
<p>We are now ready to proceed to the google cloud and kubernetes part. The goal is to host the application with three replicas running behind nginx using https. To be able to try it out on <a href="https://cloud.google.com/?ref=blog.2mas.xyz">google cloud</a> you need to sign up and create a project. You also need to install the <a href="https://cloud.google.com/sdk/?ref=blog.2mas.xyz">sdk</a>.</p>
<h3 id="creatingthekubernetescluster">Creating the kubernetes cluster</h3>
<p>If you have the sdk installed it is really simple to set up a new basic cluster. To create a cluster named <code>k1</code> run the following</p>
<pre><code>gcloud container clusters create k1
</code></pre>
<p>When you have the cluster up and running you need to install <code>kubectl</code>, which is the CLI tool to work with kubernetes.</p>
<pre><code>gcloud components install kubectl
</code></pre>
<p>Now you should be all set to operate your google cloud container cluster, hopefully.</p>
<h3 id="secretsandconfigmaps">Secrets and configmaps</h3>
<p>For nginx to run correctly we need to configure it to use <code>https</code> and where our application is in the cluster.</p>
<p>The first part is generating <code>cert.pem</code> and <code>key.pem</code> files for tls to work. If you have <code>openssl</code> installed you can run:</p>
<pre><code>openssl req -newkey rsa:4096 -nodes -sha512 -x509 -days 3650 -nodes -out cert.pem -keyout key.pem
</code></pre>
<p>The result from this have I stored in a folder in the repo: <a href="https://github.com/mastoj/suavecore/tree/master/kubernetes/tls?ref=blog.2mas.xyz">https://github.com/mastoj/suavecore/tree/master/kubernetes/tls</a>. You should probably never publish these files, I&apos;m just doing it for demo purpose.</p>
<p>When we have the files we can create a secret that we will be able to mount in our containers when they run in the cluster. To create a secret you use <code>kubectl</code></p>
<pre><code>kubectl create secret generic tls-certs --from-file=tls/
</code></pre>
<p>We will see later how we access the secrets.</p>
<p>Next step is to add the nginx configuration. The configuration is a file, that we will mount when the container starts. The file is also in repo with the name <a href="https://github.com/mastoj/suavecore/blob/master/kubernetes/nginx/frontend.conf?ref=blog.2mas.xyz">frontend.conf</a>:</p>
<pre><code>upstream hello {
    server hello.default.svc.cluster.local;
}
server {
    listen 443;
    ssl    on;
    ssl_certificate     /etc/tls/cert.pem;
    ssl_certificate_key /etc/tls/key.pem;
    location / {
        proxy_pass http://hello;
    }
}
</code></pre>
<p>This configuration file will configure nginx to listen to <code>443</code> with <code>ssl</code> enabled and route the traffic to <code>hello.default.svc.cluster.local</code>, which is where our hello nodes will be. You can also see where <code>nginx</code> now expect the secrets to be located.</p>
<p>With this done we can now continue on to creating the deployments and services.</p>
<h3 id="creatingthedeployments">Creating the deployments</h3>
<p>If you want to know exactly what a deployment is you should read this: <a href="http://kubernetes.io/docs/user-guide/deployments/?ref=blog.2mas.xyz#what-is-a-deployment">http://kubernetes.io/docs/user-guide/deployments/#what-is-a-deployment</a>. I want go into details about all these concepts, just show you how to configure it.</p>
<h4 id="thefrontenddeployment">The frontend deployment</h4>
<p>The <a href="https://github.com/mastoj/suavecore/blob/master/kubernetes/deployments/frontend.yaml?ref=blog.2mas.xyz"><code>deployments/frontend.yaml</code></a> defines the deployment for the frontend, which is the nginx part of our application.</p>
<pre><code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: frontend
spec:
  replicas: 1
  template:
    metadata:
      labels:
        app: frontend
        track: stable
    spec:
      containers:
        - name: nginx
          image: &quot;nginx:1.9.14&quot;
          lifecycle:
            preStop:
              exec:
                command: [&quot;/usr/sbin/nginx&quot;,&quot;-s&quot;,&quot;quit&quot;]
          volumeMounts:
            - name: &quot;nginx-frontend-conf&quot;
              mountPath: &quot;/etc/nginx/conf.d&quot;
            - name: &quot;tls-certs&quot;
              mountPath: &quot;/etc/tls&quot;
      volumes:
        - name: &quot;tls-certs&quot;
          secret:
            secretName: &quot;tls-certs&quot;
        - name: &quot;nginx-frontend-conf&quot;
          configMap:
            name: &quot;nginx-frontend-conf&quot;
            items:
              - key: &quot;frontend.conf&quot;
                path: &quot;frontend.conf&quot;
</code></pre>
<p>In the file we first define that it is a <code>deployment</code> and some metadata. The interesting part is the <code>containers</code> part where we define that we will use <code>nginx</code> and also add a correct shutdown command when the container is stopped. In the <code>volumes</code> section we define that we want access to our <code>secret</code> named <code>tls-certs</code>, and the <code>configMap</code> named <code>nginx-frontend-conf</code>. For the <code>configMap</code> we are only interested in the key <code>frontend.conf</code> and we are going to name that file the same as the key. When we have defined the <code>volumens</code> we can reference them in the <code>volumeMounts</code> section of the file and define where they should go. That is it for the frontend deployment.</p>
<p>To create our deployment in the cluster run</p>
<pre><code>kubectl create -f deployments/frontend.yaml
</code></pre>
<h4 id="applicationdeployment">Application deployment</h4>
<p>The application deployment is defined in <a href="https://github.com/mastoj/suavecore/blob/master/kubernetes/deployments/hello.yaml?ref=blog.2mas.xyz"><code>deployments/hello.yaml</code></a></p>
<pre><code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: hello
spec:
  replicas: 3
  template:
    metadata:
      labels:
        app: hello
        track: stable
    spec:
      containers:
        - name: hello
          image: &quot;mastoj/suavecore:v1.5&quot;
          args: [&quot;--ip&quot;, &quot;0.0.0.0&quot;]
          ports:
            - name: http
              containerPort: 8083
</code></pre>
<p>This is a little bit simple deployment. What interesting here is the number of replicas, <code>3</code>, and that we are referencing the docker image we have created earlier. To create the deployment of the application we need to run</p>
<pre><code>kubectl create -f deployments/hello.yaml
</code></pre>
<h3 id="creatingservices">Creating services</h3>
<p>Next up is creating services, which allow us to balance the load requests between our nodes and expose the application to the public.</p>
<h4 id="thefrontendservice">The frontend service</h4>
<p>The <a href="https://github.com/mastoj/suavecore/blob/master/kubernetes/services/frontend.yaml?ref=blog.2mas.xyz"><code>services/frontend.yaml</code></a> is what defines the service for the frontend.</p>
<pre><code>kind: Service
apiVersion: v1
metadata:
  name: &quot;frontend&quot;
spec:
  selector:
    app: &quot;frontend&quot;
  ports:
    - protocol: &quot;TCP&quot;
      port: 443
      targetPort: 443
  type: LoadBalancer
</code></pre>
<p>We create the service with</p>
<pre><code>kubectl create -f services/frontend.yaml
</code></pre>
<p>When the service is created you can run the command</p>
<pre><code>kubectl get services
</code></pre>
<p>to check the status. There you will see the public ip when it is available.</p>
<h4 id="thehelloapplicationservice">The hello application service</h4>
<p>The definition in <a href="https://github.com/mastoj/suavecore/blob/master/kubernetes/services/hello.yaml?ref=blog.2mas.xyz"><code>services/hello.yaml</code></a> is similar to the <code>frontend</code> definition</p>
<pre><code>kind: Service
apiVersion: v1
metadata:
  name: &quot;hello&quot;
spec:
  selector:
    app: &quot;hello&quot;
  ports:
    - protocol: &quot;TCP&quot;
      port: 80
      targetPort: 8083
</code></pre>
<p>The difference here is that we don&apos;t have the <code>LoadBalancer</code> part, which means our app will NOT be accessible from the outside, you have to go through our frontend. We also routes the traffic from the service port <code>80</code> to the container port <code>8083</code> which our containers use. Creating the service is as easy as for the frontend</p>
<pre><code>kubectl create -f services/hello.yaml
</code></pre>
<h2 id="win">Win</h2>
<p>Everything should now be configured and up and running. You can find the public IP that you should be able to navigate to be executing</p>
<pre><code>kubectl get services
</code></pre>
<p>Remember that it is <code>https://&lt;your public ip&gt;</code>, and the cert we are using is self signed so you will probably get a warning about that as well.</p>
<p>The source code for everything is available here: <a href="https://github.com/mastoj/suavecore/?ref=blog.2mas.xyz">https://github.com/mastoj/suavecore/</a></p>
<p>If you have any comments or questions, feel free to post them at the comment section.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[F# will solve your everyday problem without a headache]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>The last couple of days I had two experiences that triggered this post. The first one was a question at work regarding how to model a finite state machine (FSM) in java or a language similar to java. The second one was a <a href="https://twitter.com/isaac_abraham/status/698178752560418816?ref=blog.2mas.xyz">tweet</a> by <a href="https://twitter.com/isaac_abraham?ref=blog.2mas.xyz">Isaac Abraham</a>:</p>
<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">It&apos;s</p></blockquote>]]></description><link>https://blog.2mas.xyz/fsharp-will-solve-your-everyday-problem-without-a-headache/</link><guid isPermaLink="false">5e382b29f81c630018abe073</guid><category><![CDATA[FSharp]]></category><category><![CDATA[functional]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Fri, 12 Feb 2016 23:43:57 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>The last couple of days I had two experiences that triggered this post. The first one was a question at work regarding how to model a finite state machine (FSM) in java or a language similar to java. The second one was a <a href="https://twitter.com/isaac_abraham/status/698178752560418816?ref=blog.2mas.xyz">tweet</a> by <a href="https://twitter.com/isaac_abraham?ref=blog.2mas.xyz">Isaac Abraham</a>:</p>
<blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">It&apos;s really disappointing in 2016 to read this &quot;F# tends to be used in domains that have a lot of scientific or financial computations.&quot;</p>&#x2014; Isaac Abraham (@isaac_abraham) <a href="https://twitter.com/isaac_abraham/status/698178752560418816?ref=blog.2mas.xyz">February 12, 2016</a></blockquote>
<script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script>
<p>The quote was from an <a href="http://ericlippert.com/2016/01/14/functional-style-follow-up/?ref=blog.2mas.xyz">interview</a> with Eric Lippert, a former member of the C# team.</p>
<p>So how are these two events related? They are related because the greater community still has a misconception of functional languages, and to find better solutions to problems we need to look further than C# and java. I agree with Isaac 100 % that it is disappointing, and sad, to read and hear this misconception of F# and functional programming. At the same time I do see a change happening for everyone, with a more functional approach in the front-end with libraries like react and more functional aspects in languages like java and C#. What I don&apos;t understand is why doesn&apos;t people try harder to stay ahead of the game and learn functional programming, even though they do like it when it gets accepted by the greater community. Almost every C# developer I know is now comfortable, and like, lambda expressions. More and more developers discover that immutability isn&apos;t that bad after all, but still don&apos;t use it as much since it is so easy to use mutability in the languages we use the most. Everyone is now comfortable with the <code>var</code> keyword in C#, but still want to write the whole type on the other side of the equal sign.</p>
<p>F#, and probably scala and other functional languages that are strongly type handle all this in better ways than we are used to in java and C#. So my answer to the question was how I should define an FSM in F#. This is a problem that is not scientific and it has nothing to do with finance. This is a real problem that anyone of us could have in almost any type of application where you need to model a FSM, and model a FSM is probably something we should do more often. Before we get to my answer to the question, let&apos;s look at one of the references in one of the other answers. One colleague linked to <a href="https://twitter.com/martinfowler?ref=blog.2mas.xyz">Martin Fowler&apos;s</a> book Domain-Specific Languages which you can read an example dealing with FSM here: <a href="http://www.informit.com/articles/article.aspx?p=1592379&amp;ref=blog.2mas.xyz">http://www.informit.com/articles/article.aspx?p=1592379</a>. Reading through the example gave me a headache and almost made my eyes bleed. The java code in the example is probably good java code, and I would probably think that all those fancy patterns where nice a couple of years back when the book was written. What is the problem with the code in the book? As I said, it is probably nice java code, but that doesn&apos;t mean it is readable. I took me a while to understand how the State Machine Model worked as described here: <a href="http://www.informit.com/articles/article.aspx?p=1592379&amp;seqNum=2&amp;ref=blog.2mas.xyz">http://www.informit.com/articles/article.aspx?p=1592379&amp;seqNum=2</a>. Why was it so? The main reason it was hard for me to understand the sample code there was probably all the noise and extra syntax. The noise and extra syntax distracted me from the actual model which can never be a good thing. Let&apos;s go to the actual FSM defined on page 3: <a href="http://www.informit.com/articles/article.aspx?p=1592379&amp;seqNum=3&amp;ref=blog.2mas.xyz">http://www.informit.com/articles/article.aspx?p=1592379&amp;seqNum=3</a>. The code here is definitely easier to understand since the level of noise has decreased due to the previous model, but it is still much noise. In fact, Fowler agree since he also provides multiple way to specify the model in other format than java code. There is one xml version, and two other versions. The only reason you need this is due to the fact that java is to verbose and the level of noise is too high.</p>
<h2 id="ftotherescue">F# to the rescue</h2>
<p>The whole purpose of this post is to show you that it is possible to solve real world problem with F# in more elegant ways than you would in languages like C# and java. I&apos;ll show you my code and then explain why I think it is better. I don&apos;t say that Fowler&apos;s java code is bad, more that the language might not be right tool.</p>
<script src="https://gist.github.com/mastoj/9dfc21848c449fadcc93.js"></script>
<p>Let me walk you through this piece of code. First I define a FSM module where all the general logic for implementing the FSM is defined. I define one type that represents the FSM. In the module I have also defined a set of helper functions that helps me create a FSM and also one <a href="https://gist.github.com/mastoj/9dfc21848c449fadcc93?ref=blog.2mas.xyz#file-fowler_fsm-fsx-L12">function</a> that handles an event given an event and a FSM as input. All the helper functions takes a FSM as the last argument, since that allows me to pipe that argument in making it possible to have a really nice DSL in the language. The helper functions takes the provided FSM and returns a new FSM based on the provided FSM and the extra input. <a href="https://gist.github.com/mastoj/9dfc21848c449fadcc93?ref=blog.2mas.xyz#file-fowler_fsm-fsx-L40"><code>registerTransition</code></a> takes mapping from one state to another given an event.</p>
<p>I defined all the valid events, commands and states on these lines: <a href="https://gist.github.com/mastoj/9dfc21848c449fadcc93?ref=blog.2mas.xyz#file-fowler_fsm-fsx-L54-L72">https://gist.github.com/mastoj/9dfc21848c449fadcc93#file-fowler_fsm-fsx-L54-L72</a>. I really don&apos;t think they need any explanation.</p>
<p>The creation of the FSM is done here: <a href="https://gist.github.com/mastoj/9dfc21848c449fadcc93?ref=blog.2mas.xyz#file-fowler_fsm-fsx-L75-L88">https://gist.github.com/mastoj/9dfc21848c449fadcc93#file-fowler_fsm-fsx-L75-L88</a>. As you can see I&apos;m using the helper functions which defines a really nice DSL for me.</p>
<p>When I have the FSM defined I can actually try that it works and that is done here: <a href="https://gist.github.com/mastoj/9dfc21848c449fadcc93?ref=blog.2mas.xyz#file-fowler_fsm-fsx-L90-L105">https://gist.github.com/mastoj/9dfc21848c449fadcc93#file-fowler_fsm-fsx-L90-L105</a>. First I define a helper infix operator that print the current state before calling the next function in each step.</p>
<p>As I hope you can see in this example there are many advantages compared to the java version:</p>
<ul>
<li>No nulls</li>
<li>Impossible to represent bad states</li>
<li>The ration of noise vs. relevant code is significantly lower</li>
<li>Shorter code, so it is easier to get the full picture</li>
<li>No need for an external dsl</li>
</ul>
<h2 id="wrapup">Wrap up</h2>
<p>F# (and most likely Scala) is a language you can, and should use, to solve your everyday problem. It will give you more concise code, easier to read code, and easier to maintain code. This will also have the positive side effect of less bugs. I understand that it might be a little bit weird at start since it is a whole new paradigm, but the reward is high on the other side. Learning to program functionally will help you write better programs in any language and you will also be ahead of the game when the functional features comes to java and C#. Note that even though those languages get some functional features they will never be as functional as F# and Scala since the base design of the languages are different. Do your self a favor and learn you some FP :)</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[F#, event sourcing and CQRS tutorial... and agents]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>Last year I wrote a post about <a href="https://blog.2mas.xyz/pure-application-in-fsharp/">Pure Functional Application</a> for the F# advent calendar, I really think it is a great initiative so I signed up again. This is my contribution to this year&apos;s F# advent calendar, you can find all the other excellent posts on <a href="https://twitter.com/sergey_tihon?ref=blog.2mas.xyz">@sergey_</a></p>]]></description><link>https://blog.2mas.xyz/fsharp-event-sourcing-and-cqrs-tutorial-and-agents/</link><guid isPermaLink="false">5e382b29f81c630018abe072</guid><category><![CDATA[FSharp]]></category><category><![CDATA[Event Sourcing]]></category><category><![CDATA[CQRS]]></category><category><![CDATA[functional]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Mon, 14 Dec 2015 13:15:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>Last year I wrote a post about <a href="https://blog.2mas.xyz/pure-application-in-fsharp/">Pure Functional Application</a> for the F# advent calendar, I really think it is a great initiative so I signed up again. This is my contribution to this year&apos;s F# advent calendar, you can find all the other excellent posts on <a href="https://twitter.com/sergey_tihon?ref=blog.2mas.xyz">@sergey_tihon</a>&apos;s blog: <a href="https://sergeytihon.wordpress.com/tag/fsadvent/?ref=blog.2mas.xyz">https://sergeytihon.wordpress.com/tag/fsadvent/</a></p>
<p>One would expect that I would write a totally different post this year, but instead I decided to make my last year&apos;s post more concrete. With that I mean I would like to introduce a tutorial for you to follow. I won&apos;t cover the whole tutorial in this post since it is described in the tutorial which you can find on <a href="https://github.com/mastoj/LibAAS?ref=blog.2mas.xyz">github</a>. The tutorial covers how it might be to work in a project where you have put in the time to set up the boilerplate for a project using CQRS and event sourcing in F#. It might not be production ready either, but it might give you some inspiration of how you can approach application development.</p>
<p>Covering the exercises in the tutorial here would be a little bit boring since they are covered in the tutorial so instead I thought I would explain how the in-memory event store is implemented using an F# agent. You can find the code I will cover in this folder on github: <a href="https://github.com/mastoj/LibAAS/tree/master/ex4/done/LibAAS.Infrastructure?ref=blog.2mas.xyz">https://github.com/mastoj/LibAAS/tree/master/ex4/done/LibAAS.Infrastructure</a>.</p>
<h2 id="agents">Agents</h2>
<p>I hope there are some people out there not that familiar with F# that follow along in this calendar since it is a great opportunity to learn some F#. I&apos;ll try to make this post understandable for most developers out there and that is why I&apos;ll write a short section about agents. Agents in F# is usually used as alias for <code>MailboxProcessor</code>, so you often see something like this in code where agents are used:</p>
<pre><code class="language-language-fsharp">type Agent&lt;&apos;TMessage&gt; = MailboxProcessor&lt;&apos;TMessage&gt;
</code></pre>
<p>The way I see agents is like in-process workers that can keep some kind of state. You can compare it to actors in the <a href="https://en.wikipedia.org/wiki/Actor_model?ref=blog.2mas.xyz">actor model</a> but much simpler. They are really great if all you need is a async worker inside your process or a nice way of storing state in your application.</p>
<p>Agents work with an inbox to which you can send messages, when a message arrives in the inbox the agent will read it an act upon it. The type of the message must be defined before hand and it can be of any type, a discriminated union is often used as message type. You can use simple types like <code>string</code> in this example</p>
<pre><code class="language-language-fsharp">type Agent&lt;&apos;T&gt; = MailboxProcessor&lt;&apos;T&gt;

let agent = Agent.Start(fun (inbox:Agent&lt;string&gt;) -&gt;
    let rec loop() =
        async {
            let! msg = inbox.Receive()
            match msg with
            | &quot;&quot; -&gt; 
                printfn &quot;Stopping agent&quot;
            | _ -&gt; 
                printfn &quot;Message recieved: %s&quot; msg
                return! loop() 
        }
    loop() 
)

let post (agent:Agent&lt;&apos;T&gt;) message = agent.Post message

&quot;hello&quot; |&gt; post agent
&quot;&quot; |&gt; post agent
&quot;hello&quot; |&gt; post agent
</code></pre>
<p>We first make an alias for the <code>MailboxProcessor</code> type. When the alias is created it can be used to start the agent with <code>Agent.Start</code>. The <code>Start</code> function takes a function as argument and this is the body of the agent. The structure you see in this simple example is probably the most common one as far as I know. The body is usually a recursive function in which you listen to new messages with the <code>inbox.Receive</code>, if you want to continue process after a message you just make a recursive call. You can define the recursive function to take a state parameter to keep track inside the agent between messages. I also defined a simple helper so it is easier to post messages to agents with the pipe operator. If you run the code above you should see two messages printed, the last one will not be printed since we are not doing a recursive call on empty messages and that stops the agent.</p>
<h2 id="eventstore">Event store</h2>
<p>What is an event store? Short answer: a data store that store events. It is almost that simple. The simplest possible event store need two functions:</p>
<ul>
<li>Get events given a stream id</li>
<li>Save events given a stream id, expected version and events</li>
</ul>
<p>The first function should return the list of events for the given stream id. A stream is just a way to group events that belong together.</p>
<p>The second function should append the events to a given stream with the stream id given that the version of the stream is the same as the expected version. A version of a stream is basically the number of events in the stream, this prevents concurrency issues and is also the transaction boundary when working against the event store.</p>
<p>That was a short introduction to what an event store is, there is plenty of more information online, but feel free to ask here if you have questions. Next up is the implementation of the event store in F#.</p>
<h2 id="eventstoreimplementation">Event store implementation</h2>
<p>The implementation I will describe here is using agents, mainly because it is a nice way to abstract away the basics of an event store. With that in place you can easily create different types of event stores by changing two functions as you&apos;ll see.</p>
<h3 id="themessages">The messages</h3>
<p>First let&apos;s define some simple helpers for our agent:</p>
<pre><code class="language-language-fsharp">module AgentHelper

type Agent&lt;&apos;T&gt; = MailboxProcessor&lt;&apos;T&gt;
let post (agent:Agent&lt;&apos;T&gt;) message = agent.Post message
let postAsyncReply (agent:Agent&lt;&apos;T&gt;) messageConstr = agent.PostAndAsyncReply(messageConstr)
</code></pre>
<p>Now when we got that out of our way we can start with the acutal implementation. We will start with the messages and some types that help us stay out of trouble.</p>
<pre><code class="language-language-fsharp">type StreamId = StreamId of int
type StreamVersion = StreamVersion of int

type SaveResult = 
    | Ok
    | VersionConflict

type Messages&lt;&apos;T&gt; = 
    | GetEvents of StreamId * AsyncReplyChannel&lt;&apos;T list option&gt;
    | SaveEvents of StreamId * StreamVersion * &apos;T list * AsyncReplyChannel&lt;SaveResult&gt;
    | AddSubscriber of string * (StreamId * &apos;T list -&gt; unit)
    | RemoveSubscriber of string
</code></pre>
<p>Just by reading this type definitions you can almost understand how the event store is supposed to work. We have a generic <code>Messages</code> type, where the generic parameter defines the type of event that we want to store in the event store. We have four actions we will be able to do against the event store:</p>
<ol>
<li>Get the events for a stream.</li>
<li>Save events for a stream.<br>
a. When saving you can have version conflict and to indicate that we use the <code>SaveResult</code> type.</li>
<li>You can add multiple subscribers, where the first string is an id of the subscriber (should probably be wrapped in a type). A subscriber will be called every time some events have been saved.</li>
<li>You can remove an existing subscriber based on the string id.</li>
</ol>
<h3 id="stateformat">State format</h3>
<p>To make the agent flexible we need to keep an internal state that can be provided when creating the agent. The definition of the state type looks like this:</p>
<pre><code class="language-language-fsharp">type internal EventStoreState&lt;&apos;TEvent,&apos;THandler&gt; = 
    {
        EventHandler: &apos;THandler
        GetEvents: &apos;THandler -&gt; StreamId -&gt; (&apos;TEvent list option * &apos;THandler) 
        SaveEvents: &apos;THandler -&gt; StreamId -&gt; StreamVersion -&gt; &apos;TEvent list -&gt; (SaveResult * &apos;THandler)
        Subscribers: Map&lt;string, (StreamId * &apos;TEvent list -&gt; unit)&gt;
    }
</code></pre>
<p>What I call <code>EventHandler</code> here is the the &quot;thing&quot; that stores the actual events, it can be an internal map or a connection to an external db. The methods <code>GetEvents</code> and <code>SaveEvents</code> uses the <code>EventHandler</code> to get or save events. The last thing in the state is the subscribers which we also need to keep track of.</p>
<h3 id="agentbody">Agent body</h3>
<p>Next up is the actual implementation of the agent. I give you the code right away and then walk you through it:</p>
<pre><code class="language-language-fsharp">let eventSourcingAgent&lt;&apos;T, &apos;TEventHandler&gt; (eventHandler:&apos;TEventHandler) getEvents saveEvents (inbox:Agent&lt;Messages&lt;&apos;T&gt;&gt;) = 
    let initState = 
        {
            EventHandler = eventHandler
            Subscribers = Map.empty
            GetEvents = getEvents
            SaveEvents = saveEvents
        }
    let rec loop state = 
        async {
            let! msg = inbox.Receive()
            match msg with
            | GetEvents (id, replyChannel) -&gt;
                let (events, newHandler) = state.GetEvents state.EventHandler id
                replyChannel.Reply(events)
                return! loop {state with EventHandler = newHandler}
            | SaveEvents (id, expectedVersion, events, replyChannel) -&gt;
                let (result, newHandler) = state.SaveEvents state.EventHandler id expectedVersion events
                if result = Ok then state.Subscribers |&gt; Map.iter (fun _ sub -&gt; sub(id, events)) else ()
                replyChannel.Reply(result)
                return! loop {state with EventHandler = newHandler}
            | AddSubscriber (subId, subFunction) -&gt;
                let newState = {state with Subscribers = (state.Subscribers |&gt; Map.add subId subFunction)}
                return! loop newState
            | RemoveSubscriber subId -&gt;
                let newState = {state with Subscribers = (state.Subscribers |&gt; Map.remove subId )}
                return! loop newState
        }
    loop initState
</code></pre>
<p>To create the agent we need the <code>eventHandler</code> a function to <code>getEvents</code> and <code>saveEvents</code>, nothing to fancy about that. The first thing we do in the function is to create the <code>initState</code> with the input and an empty <code>Map</code> for our subscribers. Next up is the recursive loop (remember it from the section above?). We first wait until there is a new message in the inbox, when we get one we match on the message type.</p>
<p>For <code>GetEvents</code> we use the <code>GetEvents</code> method on the state passing in the <code>EventHandler</code> and the id of the string. When we have the events we reply back to the callee and finish it of with a recursive call with the new state (if it has changed).</p>
<p><code>SaveEvents</code> works almost the same way, with the addition of notifying the subscribers if we manage to save the events. We also reply back to the callee with the result of the save operation before making the recursive call to wait for the next message.</p>
<p>The implementation of <code>AddSubscriber</code> and <code>RemoveSubscriber</code> do what you would expect them to, it adds or removes a subscriber for the <code>Subscribers</code> map we have in the state and make a recursive call to wait for the next message.</p>
<h3 id="inmemoryimplementation">In-memory implementation</h3>
<p>To make it a little bit easier for a user to work with an agent it make sense to hide it behind some kind of type, which also make it easier to swap for another implementation later, and that type looks like this:</p>
<pre><code class="language-language-fsharp">type EventStore&lt;&apos;TEvent, &apos;TError&gt; = 
    {
        GetEvents: StreamId -&gt; Result&lt;StreamVersion*&apos;TEvent list, &apos;TError&gt;
        SaveEvents: StreamId -&gt; StreamVersion -&gt; &apos;TEvent list -&gt; Result&lt;&apos;TEvent list, &apos;TError&gt;
        AddSubscriber: string -&gt; (StreamId * &apos;TEvent list -&gt; unit) -&gt; unit
        RemoveSubscriber: string -&gt; unit
    }
</code></pre>
<p>The <code>SaveEvents</code> and <code>GetEvents</code> method returns something of type <code>Result</code>, and that is taken from <a href="http://fsharpforfunandprofit.com/rop/?ref=blog.2mas.xyz">Railway Oriented Programming</a> which is a really nice way to handle errors in an application without introducing side effects like exceptions. The <code>Result</code> type is defined as:</p>
<pre><code class="language-language-fsharp">[&lt;AutoOpen&gt;]
module ErrorHandling
 
type Result&lt;&apos;TResult, &apos;TError&gt; = 
    | Success of &apos;TResult
    | Failure of &apos;TError

let ok x = Success x
let fail x = Failure x
</code></pre>
<p>Together with the type we have defined two helpers <code>ok</code> and <code>fail</code> to make it easier to create a <code>Result</code> through piping.</p>
<p>We also need a function to create a wrapper around an agent that create an instance of an <code>EventStore</code>.</p>
<pre><code class="language-language-fsharp">let createEventStore&lt;&apos;TEvent, &apos;TError&gt; (versionError:&apos;TError) agent =
    let getEvents streamId : Result&lt;StreamVersion*&apos;TEvent list, &apos;TError&gt; = 
        let result = (fun r -&gt; GetEvents (streamId, r)) |&gt; postAsyncReply agent |&gt; Async.RunSynchronously
        match result with
        | Some events -&gt; (StreamVersion (events |&gt; List.length), events) |&gt; ok
        | None -&gt; (StreamVersion 0, []) |&gt; ok

    let saveEvents streamId expectedVersion events : Result&lt;&apos;TEvent list, &apos;TError&gt; = 
        let result = (fun r -&gt; SaveEvents(streamId, expectedVersion, events, r)) |&gt; postAsyncReply agent |&gt; Async.RunSynchronously
        match result with
        | Ok -&gt; events |&gt; ok
        | VersionConflict -&gt; versionError |&gt; fail

    let addSubscriber subId subscriber = 
        (subId,subscriber) |&gt; AddSubscriber |&gt; post agent

    let removeSubscriber subId = 
        subId |&gt; RemoveSubscriber |&gt; post agent

    { GetEvents = getEvents; SaveEvents = saveEvents; AddSubscriber = addSubscriber; RemoveSubscriber = removeSubscriber}
</code></pre>
<p>It is nothing to complicated going on, the <code>getEvents</code> function takes a stream id and wrap it in a <code>GetEvents</code> message which is sent to the agent. After sending the message we wait for the reply and return the events together with the current version of the stream wrapped in a <code>Result</code> type. The <code>saveEvents</code> method works almost the same way, that is, we wrap the input in a <code>SaveEvents</code> message and pass it to the agent and wait for the reply. If we get a <code>VersionConflict</code> back we translate it to the provided error to keep this code isolated from other code.</p>
<p>Now we have all the pieces to put together our in-memory event store. The in-memory event store will use a simple map as a storage for the events for easy lookup.</p>
<pre><code class="language-language-fsharp">let createInMemoryEventStore&lt;&apos;TEvent, &apos;TError&gt; (versionError:&apos;TError) =
    let initState : Map&lt;StreamId, &apos;TEvent list&gt; = Map.empty

    let saveEventsInMap map id expectedVersion events = 
        match map |&gt; Map.tryFind id with
        | None -&gt; 
            (Ok, map |&gt; Map.add id events)
        | Some existingEvents -&gt;
            let currentVersion = existingEvents |&gt; List.length |&gt; StreamVersion
            match currentVersion = expectedVersion with
            | true -&gt; 
                (Ok, map |&gt; Map.add id (existingEvents@events))
            | false -&gt; 
                (VersionConflict, map)

    let getEventsInMap map id = Map.tryFind id map, map

    let agent = createEventStoreAgent initState getEventsInMap saveEventsInMap
    createEventStore&lt;&apos;TEvent, &apos;TError&gt; versionError agent
</code></pre>
<ul>
<li>The <code>initState</code> is of course an empty map since we don&apos;t have any events when we start.</li>
<li>The <code>saveEventsInMap</code> uses the <code>id</code> argument to lookup in the <code>map</code> argument (current state), if the result is <code>None</code> the entry is added to the map with the <code>events</code>. If the entry already exist we check the version before appending the <code>events</code> to the stream.</li>
<li>The <code>getEventsInMap</code> will just do a lookup in the <code>map</code> and returning an <code>Option</code> type together with the new map which is the same as the input.</li>
</ul>
<p>With these three functions we can now call the <code>createEventStore</code> function to create our in-memory event store and we are done.</p>
<h2 id="takingitoutforaspin">Taking it out for a spin</h2>
<p>The simplest way to actually try the event store out is to use it in a fsharp script. So in the same folder as the I have the files for the implementation I also have a simple script with the following content:</p>
<pre><code class="language-language-fsharp">#load &quot;AgentHelper.fs&quot;
#load &quot;ErrorHandling.fs&quot;
#load &quot;EventStore.fs&quot;

open EventStore

let inMemoryEventStore = createInMemoryEventStore&lt;string,string&gt; &quot;This is a version error&quot;
inMemoryEventStore.AddSubscriber &quot;FirstSubscriber&quot; (printfn &quot;%A&quot;)
let res0 = inMemoryEventStore.SaveEvents (StreamId 1) (StreamVersion 0) [&quot;Hello&quot;;&quot;World&quot;]
let res1 = inMemoryEventStore.SaveEvents (StreamId 1) (StreamVersion 1) [&quot;Hello2&quot;;&quot;World2&quot;]
let res2 = inMemoryEventStore.SaveEvents (StreamId 1) (StreamVersion 2) [&quot;Hello2&quot;;&quot;World2&quot;]

[res0;res1;res2] |&gt; List.mapi (fun i v -&gt; printfn &quot;%i: %A&quot; i v)
</code></pre>
<p>We keep it really simple and only storing strings, as well as using a string as our error indicator. Executing this code with mono <code>fsharpi --exec Script.fsx</code> or on Windows <code>fsi --exec Script.fsx</code> should give the following output:</p>
<pre><code>(StreamId 1, [&quot;Hello&quot;; &quot;World&quot;])
(StreamId 1, [&quot;Hello2&quot;; &quot;World2&quot;])
0: Success [&quot;Hello&quot;; &quot;World&quot;]
1: Failure &quot;This is a version error&quot;
2: Success [&quot;Hello2&quot;; &quot;World2&quot;]
</code></pre>
<p>The first two lines are from the subscriber and last in the script I print all the results.</p>
<h2 id="nowitisyourturn">Now it is your turn</h2>
<p>There is room for a lot of improvement here I guess, but it is a good starting point. Feel free to try the tutorial and also come with suggestion to what can simplify the infrastructure part. The goal of this implementation was to make it easy to use in a tutorial, and I think I manage that since the user only need to use code like the one in the last script.</p>
<p>With all this in place it shouldn&apos;t be that hard to implement an agent that is using <a href="https://geteventstore.com/?ref=blog.2mas.xyz">eventstore</a> or a event simple one backed by a SQL database. All you need to do is send in the connection as the <code>EventHandler</code> and then implement the <code>GetEvents</code> and <code>SaveEvents</code> method accepting the connection (<code>EventHandler</code>) as an argument and returning the result for these two methods together with the new <code>EventHandler</code> state, the state could be the same as the input to the function.</p>
<p>And this finishes of my contribution to this year&apos;s F# calendar. I hope you enjoyed the read and learned something. Let me know if you have any questions!</p>
<p>Merry Christmas!</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Npm build with F# FAKE]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>Most web project to day has some javascript in them, and you should really build the javascript to minify them and also to find stupid errors. It would be stupid to implement the build part all over again in F#, instead you should use the tooling that already exists, like</p>]]></description><link>https://blog.2mas.xyz/npm-build-with-fsharp-fake/</link><guid isPermaLink="false">5e382b29f81c630018abe070</guid><category><![CDATA[FSharp]]></category><category><![CDATA[FAKE]]></category><category><![CDATA[npm]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Sun, 15 Nov 2015 22:34:03 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>Most web project to day has some javascript in them, and you should really build the javascript to minify them and also to find stupid errors. It would be stupid to implement the build part all over again in F#, instead you should use the tooling that already exists, like <code>node</code> and <code>npm</code>. Even though <code>npm</code> is used to build the javascript application I still want to control the overall build flow with FAKE, and for that reason I created the <a href="http://fsharp.github.io/FAKE/apidocs/fake-npmhelper.html?ref=blog.2mas.xyz">FAKE NpmHelper</a>.</p>
<h2 id="configurefake">Configure FAKE</h2>
<p>The easiest way to get started is to install <code>node</code> and <code>npm</code> with <code>nuget</code> as part of the <code>build.cmd</code> before calling <code>build.fsx</code>. This will add <code>npm</code> to the default paths that is used by the helper. Don&apos;t worry, it is possible to override which <code>npm</code> file that should be used. A sample <code>build.cmd</code> can be found in my FAKE <a href="https://github.com/mastoj/FAKESimpleDemo?ref=blog.2mas.xyz">sample</a> and looks like this:</p>
<pre><code>echo off
cls
NuGet.exe &quot;Install&quot; &quot;FAKE&quot; &quot;-OutputDirectory&quot; &quot;packages&quot; &quot;-ExcludeVersion&quot;
NuGet.exe &quot;Install&quot; &quot;OctopusTools&quot; &quot;-OutputDirectory&quot; &quot;packages&quot; &quot;-ExcludeVersion&quot;
NuGet.exe &quot;Install&quot; &quot;Node.js&quot; &quot;-OutputDirectory&quot; &quot;packages&quot; &quot;-ExcludeVersion&quot;
NuGet.exe &quot;Install&quot; &quot;Npm.js&quot; &quot;-OutputDirectory&quot; &quot;packages&quot; &quot;-ExcludeVersion&quot;
&quot;packages\FAKE\tools\Fake.exe&quot; build.fsx %*
</code></pre>
<h2 id="supportedcommands">Supported commands</h2>
<p>There are only two supported commands where you get some type check, <code>Install</code> and <code>Run</code>. Below is the simplest possible sample to use those two.</p>
<pre><code class="language-language-fsharp">Npm (fun p -&gt;
  { p with
      Command = Install Standard
      WorkingDirectory = &quot;./src/FAKESimple.Web/&quot;
  })

Npm (fun p -&gt;
  { p with
      Command = (Run &quot;build&quot;)
      WorkingDirectory = &quot;./src/FAKESimple.Web/&quot;
  })
</code></pre>
<p>I figured those two commands are the one you usually would like to run in this kind of scenario, but if you do want to run any of the other <code>npm</code> commands you can do so by using the <code>Custom</code> command parameter and just pass in the string you like. Or if it is something you think is commonly used send a PR or ping me about it :).</p>
<p>That&apos;s all, let me know if you have any questions.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[React hot load and ASP.NET 5]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>One or two months ago I saw a <a href="https://www.youtube.com/watch?v=xsSnOQynTHs&amp;ref=blog.2mas.xyz">presentation</a> by <a href="https://twitter.com/dan_abramov?ref=blog.2mas.xyz">Dan Abramov</a> about hot loading and react. I have&apos;t done much react and I haven&apos;t done much webpack which is used to do this, but I know I wanted a sample for ASP.NET 5 and</p>]]></description><link>https://blog.2mas.xyz/react-hot-load-and-asp-net-5/</link><guid isPermaLink="false">5e382b29f81c630018abe071</guid><category><![CDATA[asp.net 5]]></category><category><![CDATA[react]]></category><category><![CDATA[react-hot-load]]></category><category><![CDATA[webpack]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Sun, 15 Nov 2015 22:09:39 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>One or two months ago I saw a <a href="https://www.youtube.com/watch?v=xsSnOQynTHs&amp;ref=blog.2mas.xyz">presentation</a> by <a href="https://twitter.com/dan_abramov?ref=blog.2mas.xyz">Dan Abramov</a> about hot loading and react. I have&apos;t done much react and I haven&apos;t done much webpack which is used to do this, but I know I wanted a sample for ASP.NET 5 and now I finally had the time to try it out. Even though the titles says ASP.NET 5 the solution can be used for basically any web project running on Windows.</p>
<h2 id="tldr">TL;DR</h2>
<p>I&apos;ve put together a small sample with react hot load and ASP.NET 5. You can find the code on <a href="https://github.com/mastoj/ReactHotLoadAspNet/?ref=blog.2mas.xyz">github</a>.</p>
<h2 id="whatisit">What is it?</h2>
<p><a href="http://gaearon.github.io/react-hot-loader/?ref=blog.2mas.xyz">React hot load</a> let you change the style files (css/less/scss) and javascript files on the server and see the result directly in the browser while keeping the browser state. This make it really easy to try things out and see the result directly instead of reloading the browser after every minor change. An example is when working with styling, instead of tweaking around in the dev tools you can just change the style file directly. Another example is if you&apos;re working with a javascript wizard, then it might be annoying to go through every step when you find an error, hot loading the javascript lets you continue where you are after you change the javascript.</p>
<p>Below is a demo showing the result. I use atom for changing less and jsx files since the support for jsx+ES6 in Visual Studio isn&apos;t the best yet.</p>
<p><img src="https://storage.ghost.io/c/7c/9f/7c9f0302-e2eb-4fec-95af-b7c64874855a/content/images/2015/11/Demo.gif" alt="Demo of react hot load" loading="lazy"></p>
<h2 id="howitsortofworksmyversion">How it sort of works (my version)</h2>
<p>I won&apos;t cover the details of how hot loading works but the short version of how it works is something like this. Instead of reading the javascript files you read them from a node server, the node server &quot;injects&quot; a &quot;wrapper&quot; between the physical file on disc and the one you pointed too from your web page that routes your javascript command to the file that is currently up to date. If you make a change to a file the wrapper will see this and make a rebuild swapping out what has changed while keeping the state. Keeping the state is possible because of the architecture of react.</p>
<h2 id="gotchas">Gotchas</h2>
<p>My goal was to get a sample up and running with both javascript and less since that is what I most likely will use in a real project, I also wanted everything to run with the latest version of everything. This caused some problems during the setup and here are a list of things that you need to do to your dev environment to get things working:</p>
<ul>
<li>I wanted to run regular npm tasks and to do so in Visual Studio you need the extension <a href="https://visualstudiogallery.msdn.microsoft.com/8f2f2cbc-4da5-43ba-9de2-c9d08ade4941?ref=blog.2mas.xyz">NPM Scripts Task Runner</a></li>
<li>For some reason <code>node 5</code> was needed, so install that.</li>
<li>To get <code>node 5</code> to play nice in Visual Studio you need to add the path for External Web Tools. You find that setting under <code>Tools-&gt;Options-&gt;Projects and Solutions-&gt;External Web Tools</code>. Just add the path to <code>node 5</code> above the line that points to external tools. It looks like <code>node 5</code> installs node modules directly under modules folder and not in a hierarchy as before. This makes Visual Studio to think that a lot of the packages are extraneous, but you can just ignore that.</li>
<li>One of the packages I used got some weird error if python wasn&apos;t installed, so python needs to be installed. I couldn&apos;t use version 3 of python so I installed version 2 from <a href="https://chocolatey.org/packages/python2?ref=blog.2mas.xyz">chocolatey</a>.</li>
<li>This last part is a little bit tricky and only works because I have both VS2013 and VS2015 I think. I got some error which I found the answer on at <a href="http://stackoverflow.com/questions/33183161/node-gyp-error-tracker-error-trk0005-failed-to-locate-cl-exe-the-system-c?ref=blog.2mas.xyz">stackoverflow</a>. <code>Npm</code> needed to run <code>cl.exe</code> for some task, but it didn&apos;t find it for VS2015 so changing <code>Npm</code> to use VS2013 helped as the SO answer says. The command to do so is <code>npm config set msvs_version 2013 --global</code>.</li>
</ul>
<h2 id="thesetup">The setup</h2>
<p>I won&apos;t cover the whole application and what it does, I&apos;ll just cover the pieces to get this up and running.</p>
<h3 id="thepackagejsonfile">The package.json file</h3>
<p>The file I ended up with looks like this</p>
<pre><code class="language-language-json">{
  &quot;version&quot;: &quot;0.0.0&quot;,
  &quot;name&quot;: &quot;&quot;,
  &quot;scripts&quot;: {
    &quot;start&quot;: &quot;node server.js&quot;,
    &quot;build&quot;: &quot;set NODE_ENV=production &amp;&amp; webpack -p --progress --colors&quot;
  },
  &quot;devDependencies&quot;: {
    &quot;babel-core&quot;: &quot;^6.1.2&quot;,
    &quot;babel-loader&quot;: &quot;^6.0.1&quot;,
    &quot;babel-preset-es2015&quot;: &quot;^6.1.2&quot;,
    &quot;babel-preset-react&quot;: &quot;^6.1.2&quot;,
    &quot;css-loader&quot;: &quot;^0.22.0&quot;,
    &quot;less&quot;: &quot;^2.5.3&quot;,
    &quot;less-loader&quot;: &quot;^2.2.1&quot;,
    &quot;react-hot-loader&quot;: &quot;^1.3.0&quot;,
    &quot;style-loader&quot;: &quot;^0.13.0&quot;,
    &quot;webpack&quot;: &quot;^1.12.2&quot;,
    &quot;webpack-dev-server&quot;: &quot;^1.12.1&quot;
  },
  &quot;dependencies&quot;: {
    &quot;jquery&quot;: &quot;2.1.4&quot;,
    &quot;marked&quot;: &quot;^0.3.5&quot;,
    &quot;react&quot;: &quot;^0.14.0&quot;,
    &quot;react-dom&quot;: &quot;^0.14.0&quot;
  }
}
</code></pre>
<p>I&apos;ve added to <code>npm</code> scripts to the file, <code>build</code> that should be used when packaging for production on a build server and <code>start</code> that is used to start the server for development. This only works with <a href="https://webpack.github.io/?ref=blog.2mas.xyz">webpack</a> so I installed that and all the loaders I needed to build <code>jsx</code> and <code>less</code> files.</p>
<h3 id="theserverjs">The server.js</h3>
<p>The <code>server.js</code> is a small node server that will host the javascript for us during development. It is started with the <code>start</code> script task defined in <code>package.json</code>.</p>
<pre><code class="language-language-javascript">var webpack = require(&apos;webpack&apos;);
var WebpackDevServer = require(&apos;webpack-dev-server&apos;);
var config = require(&apos;./webpack.config&apos;);

new WebpackDevServer(webpack(config), {
    publicPath: config.output.publicPath,
    hot: true,
    historyApiFallback: true,
    headers: { &apos;Access-Control-Allow-Origin&apos;: &apos;*&apos; }
}).listen(3000, &apos;localhost&apos;, function (err, result) {
    if (err) {
        console.log(err);
    }

    console.log(&apos;Listening at localhost:3000&apos;);
});
</code></pre>
<p>The server is based on this <a href="https://github.com/gaearon/react-hot-boilerplate/blob/master/server.js?ref=blog.2mas.xyz">boilerplate code</a> but I added <code>headers: { &apos;Access-Control-Allow-Origin&apos;: &apos;*&apos; }</code>. When I upgraded everything to the latest bits <code>CORS</code> was required.</p>
<h2 id="webpackconfiguration">Webpack configuration</h2>
<p>You can run <code>webpack</code> directly from the command line, but you usually use a configuration file to do so. This is my first time using <code>webpack</code> so it is most likely a guide to how you should do it, more a sample of how I got it to do what I wanted it to do. The <code>webpack.config.js</code> I ended up with looks like this:</p>
<pre><code class="language-language-javascript">var webpack = require(&apos;webpack&apos;);
var path = require(&apos;path&apos;);
var outFolder = path.resolve(__dirname, &quot;./wwwroot/app&quot;);
var isProduction = process.env.NODE_ENV === &apos;production &apos;;
var jsxLoaders = isProduction ?
    [&apos;babel?presets[]=es2015,presets[]=react&apos;] :
    [&apos;react-hot&apos;, &apos;babel?presets[]=es2015,presets[]=react&apos;]; // only react hot load in debug build
var entryPoint = &apos;./content/app.jsx&apos;;
var app = isProduction ? [entryPoint] : [
    &apos;webpack-dev-server/client?http://0.0.0.0:3000&apos;, // WebpackDevServer host and port
    &apos;webpack/hot/only-dev-server&apos;, // &quot;only&quot; prevents reload on syntax errors
    entryPoint
];

module.exports = {
    entry: {
        app: app
    },
    output: {
        path: outFolder,
        filename: &quot;[name].js&quot;,
        publicPath: &apos;http://localhost:3000/static/&apos;
    },
    devtool: &quot;source-map&quot;,
    minimize: true,
    module: {
        loaders: [{
            test: /\.(js|jsx)$/,
            loaders: jsxLoaders,
            exclude: /node_modules/
        },
        {
            test: /\.(css|less)$/,
            loaders: [&apos;style&apos;,&apos;css&apos;,&apos;less&apos;]
        }]
    },
    plugins: [
      new webpack.HotModuleReplacementPlugin()
    ],
    resolve: {
        extensions: [&quot;&quot;, &quot;.webpack.js&quot;, &quot;.web.js&quot;, &quot;.js&quot;, &quot;.jsx&quot;]
    },
    devServer: {
        headers: { &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot; }
    }
};
</code></pre>
<p>First I define some settings that differs depending on environment. The environment is set as an environment variable, see the <code>build</code> script task in the <code>package.json</code> file. One important part is this one:</p>
<pre><code class="language-language-javascript">var jsxLoaders = isProduction ?
    [&apos;babel?presets[]=es2015,presets[]=react&apos;] :
    [&apos;react-hot&apos;, &apos;babel?presets[]=es2015,presets[]=react&apos;]; // only react hot load in debug build
var entryPoint = &apos;./content/app.jsx&apos;;
var app = isProduction ? [entryPoint] : [
    &apos;webpack-dev-server/client?http://0.0.0.0:3000&apos;, // WebpackDevServer host and port
    &apos;webpack/hot/only-dev-server&apos;, // &quot;only&quot; prevents reload on syntax errors
    entryPoint
];
</code></pre>
<p>This is what make the actual server running, I used to port 3000 to host the files. I also needed to specify the <code>publicPath</code> under <code>output</code>, that&apos;s because the files are not served from the same application as the consumer of the files. As you can see, if we are doing a production build, by running <code>npm rum build</code>, we will only use the actual <code>app.jsx</code> as entry point. Also, we won&apos;t add <code>react-hot</code> (alias for <code>react-hot-loader</code>) to the list of <code>jsxLoaders</code> since I don&apos;t want hot loading enabled in production.</p>
<p>I won&apos;t try to cover <code>webpack</code> in more depth since all this is sort of new to me.</p>
<h3 id="theaspnetpart">The ASP.NET part</h3>
<p>If you haven&apos;t figured it out by now, the ASP.NET solution stays mainly the same to get this working. The trick is actually just to fire up a node server to host your static content and then point the <code>script</code> tags in your solution to that server. So my simple index page looks like this:</p>
<pre><code class="language-language-aspnet">@{
    // ViewBag.Title = &quot;Home Page&quot;;
}
&lt;html&gt;
&lt;head&gt;
    &lt;title&gt;Sample hot load demo&lt;/title&gt;
    &lt;link href=&quot;/static/&quot;/&gt;
&lt;/head&gt;
&lt;body&gt;
    &lt;div id=&quot;content&quot;&gt;&lt;/div&gt;
    @*&lt;script src=&quot;/static/app.js&quot;&gt;&lt;/script&gt;*@
    &lt;script src=&quot;http://localhost:3000/static/app.js&quot;&gt;&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</code></pre>
<p>As you can see I&apos;m pointing to <code>localhost:3000</code> instead of directly to disk, this is what makes everything above work. In production probably want to point to the file to disk, and that could probably be solved by tag helpers in ASP.NET 5, or using server side variables based on environment in any other version of ASP.NET.</p>
<h2 id="runningeverything">Running everything</h2>
<p>If you have cloned the <a href="https://github.com/mastoj/ReactHotLoadAspNet?ref=blog.2mas.xyz">repository</a> and want to try it out you can now either run start from the <code>Task Runner Explorer</code> if you have the <code>NPM Scripts Task Runner</code> installed, or you can run <code>npm run start</code> from the command line in the root of the web project.</p>
<p><img src="https://storage.ghost.io/c/7c/9f/7c9f0302-e2eb-4fec-95af-b7c64874855a/content/images/2015/11/TaskRunner.PNG" alt="Task Runner Explorer" loading="lazy"></p>
<p>This will start the node server for you. When the node server is up and running you can start the ASP.NET application. Now you can start to interact with the application in the browser and then try to change the <code>jsx</code> or <code>less</code> files, save and see the changes appear in the browser with no refresh of the page.</p>
<h2 id="summary">Summary</h2>
<p>React hot load looks to me like an awesome way to get fast feedback while doing web development with react. There was a little bit of hazzle to get it up and running on Windows but it is doable, and you probably only need to feel that pain once :). Let me know if you have any questions.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Take control of your build, CI and deployment with FSharp FAKE]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>I&apos;ve been using <a href="https://www.jetbrains.com/teamcity/?ref=blog.2mas.xyz">TeamCity</a> for quite a while and trusted it to do the right thing when it comes to building. It has a lot of built in feature to do so, but the moment you start to define your build inside TeamCity you have painted yourself into</p>]]></description><link>https://blog.2mas.xyz/take-control-of-your-build-ci-and-deployment-with-fsharp-fake/</link><guid isPermaLink="false">5e382b29f81c630018abe06e</guid><category><![CDATA[FAKE]]></category><category><![CDATA[FSharp]]></category><category><![CDATA[AppVeyor]]></category><category><![CDATA[Octopus Deploy]]></category><category><![CDATA[Azure]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Sun, 25 Oct 2015 22:43:46 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>I&apos;ve been using <a href="https://www.jetbrains.com/teamcity/?ref=blog.2mas.xyz">TeamCity</a> for quite a while and trusted it to do the right thing when it comes to building. It has a lot of built in feature to do so, but the moment you start to define your build inside TeamCity you have painted yourself into a corner. I still think TeamCity is a great tooling triggering my builds, but I have come to realize that I should start to put the actual definition of the builds outside of TeamCity, or whatever CI tool I am using.</p>
<h2 id="whybuildscripts">Why build scripts?</h2>
<p>Many people argue that it works just fine with using TeamCity and other CI tools to define the way you build, and it is when you have a set of smaller projects I think. The moment when you need to do more things in your build it make sense to put it in a separate script file and here are some of my reasons:</p>
<ul>
<li>You got your actual build process under source control together with your code instead of defined in a CI tool</li>
<li>It is easier to handle versioning</li>
<li>The way you build on the server is identical to the way you build locally</li>
<li>You will not be locked in to one CI tool, if you use TeamCity today it is quite easy to switch to AppVeyor tomorrow and TravisCI the day after that.</li>
</ul>
<h2 id="whatisfake">What is FAKE</h2>
<p><a href="http://fsharp.github.io/FAKE/?ref=blog.2mas.xyz">FAKE</a> is a domain specific language, <a href="https://en.wikipedia.org/wiki/Domain-specific_language?ref=blog.2mas.xyz">dsl</a>, for build tasks implemented in <a href="http://fsharp.org/?ref=blog.2mas.xyz">F#</a>. That it is implemented in F# doesn&apos;t mean you can only build F# projects, in fact you should event be able to build java project if you would like to. F#, along with many functional programming languages, is terrific when you want to create a dsl, since functional programming languages often are more expressive and not as verbose as OO languages. This is not an introduction to FAKE, and the documentation is <a href="http://fsharp.github.io/FAKE/?ref=blog.2mas.xyz">here</a> if you want to check it out. Later in the post I will go through what my FAKE script look like to solve the problems I imagined.</p>
<h2 id="thedemo">The demo</h2>
<p>The thing I wanted to try was this:</p>
<ul>
<li>Simple .NET Web app that includes some js building</li>
<li>GitHub as source control</li>
<li>AppVeyor as a CI engine to execute build</li>
<li>Octopus Deploy to handle deployment</li>
<li>Deploy to Azure Web App</li>
<li>Most of it configured in FAKE</li>
</ul>
<p>Illustration of the flow from code to deployment:</p>
<p><img src="https://storage.ghost.io/c/7c/9f/7c9f0302-e2eb-4fec-95af-b7c64874855a/content/images/2015/10/CodeToDeploy.JPG" alt="The build deploy process" loading="lazy"></p>
<p>I think the end result is really good since it is the first time I used FAKEand AppVeyor. If you want to see the sample app and also the builds scripts they are in this repo at github: <a href="https://github.com/mastoj/FAKESimpleDemo?ref=blog.2mas.xyz">https://github.com/mastoj/FAKESimpleDemo</a></p>
<h3 id="appveyor">Appveyor</h3>
<p>I could as well used TeamCity, but I thought I would try <a href="http://www.appveyor.com/?ref=blog.2mas.xyz">Appveyor</a> out. The goal of AppVeyor is:</p>
<blockquote>
<p>AppVeyor aims to give powerful Continuous Integration and Deployment tools to every .NET developer without the hassle of setting up and maintaining their own build server. - <a href="http://www.appveyor.com/about?ref=blog.2mas.xyz">About AppVeyor</a></p>
</blockquote>
<p>Their goal is the reason I think AppVeyor is interesting and I wanted to take it for a spin. The experience has been truly amazing with really fast build times and easy to get started, and another really positive aspect is that I don&apos;t have to think about maintaining the build server.</p>
<p>AppVeyor can do a lot more than I did, one might even argue that I should use AppVeyor instead of Octopus Deploy for deployment, but this is a proof of concept for a scenario were I still will have Octopus Deploy and I really like Octopus Deploy :).</p>
<p>When you configure AppVeyor you can do so in the UI or with a yml-file. Of course I choose to use a yml-file since I do want as much as I can in source control. The configuration file I created is minimal since I have FAKE that take care of the actual build process:</p>
<pre><code class="language-language-yml">environment:
  version: 1.0.0
assembly_info:
  patch: false
build_script:
  build.cmd
test: off
</code></pre>
<p>This specifies a environment variable <code>version</code> and that AppVeyor should not run tests or patch the assmebly information file. To start the build the <code>build.cmd default</code> commmand should be used. I can still run test and patch the assembly information file, but that is something I want to do from FAKE and not define in AppVeyor.</p>
<p>I alos added some environment settings in the UI like this:</p>
<p><img src="https://storage.ghost.io/c/7c/9f/7c9f0302-e2eb-4fec-95af-b7c64874855a/content/images/2015/10/AppVeyorEnv.PNG" alt="AppVeyor environment settings" loading="lazy"></p>
<p>The reason I added them there and not in source control is because that is not I want to have on GitHub. The same would apply if I needed some other &quot;secret&quot; settings during build, then I would add that a a environment setting in the UI. I do the same thing if I use TeamCity.</p>
<h3 id="octopusdeploy">Octopus Deploy</h3>
<p>I&apos;m not going to go through what Octopus Deploy and what you can do with it, all you nned to know is that it is a great tool for handling deployments to multiple different environments locally as well as in the cloud.</p>
<p>To deploy to an Azure Web App you need to create an account under Azure that is an Azure account. You create accounts in <code>Environment-&gt;Accounts</code>. To create an Azure account you will need a Management Certificate (.pfx) and your subscriptiong id. I don&apos;t remember which guide I followed to generate mine, but this might work: <a href="https://azure.microsoft.com/en-us/blog/obtaining-a-certificate-for-use-with-windows-azure-web-sites-waws/?ref=blog.2mas.xyz">https://azure.microsoft.com/en-us/blog/obtaining-a-certificate-for-use-with-windows-azure-web-sites-waws/</a></p>
<p>When that is done you just add your project and creates a deployment step of type <code>Deploy an Azure Web App</code> and you are good to go. The step configuration should like something like:</p>
<p><img src="https://storage.ghost.io/c/7c/9f/7c9f0302-e2eb-4fec-95af-b7c64874855a/content/images/2015/10/OctopusDeployStep.PNG" alt="Octopus deploy configuration" loading="lazy"></p>
<h3 id="fake">FAKE</h3>
<p>This is were all the magic happens. I will try to break down this file: <a href="https://github.com/mastoj/FAKESimpleDemo/blob/master/build.fsx?ref=blog.2mas.xyz">https://github.com/mastoj/FAKESimpleDemo/blob/master/build.fsx</a> and explain the different parts of it. I expect you to know the minimum basics of FAKE, that is, what is a target and how you set up a build process with the <code>==&gt;</code> operator.</p>
<h4 id="bootstrap">Bootstrap</h4>
<p>To get FAKE running easily I also have a bootstrap file <a href="https://github.com/mastoj/FAKESimpleDemo/blob/master/build.cmd?ref=blog.2mas.xyz"><code>build.cmd</code></a>.</p>
<pre><code>@echo off
cls
NuGet.exe &quot;Install&quot; &quot;FAKE&quot; &quot;-OutputDirectory&quot; &quot;packages&quot; &quot;-ExcludeVersion&quot;
NuGet.exe &quot;Install&quot; &quot;OctopusTools&quot; &quot;-OutputDirectory&quot; &quot;packages&quot; &quot;-ExcludeVersion&quot;
NuGet.exe &quot;Install&quot; &quot;Node.js&quot; &quot;-OutputDirectory&quot; &quot;packages&quot; &quot;-ExcludeVersion&quot;
NuGet.exe &quot;Install&quot; &quot;Npm.js&quot; &quot;-OutputDirectory&quot; &quot;packages&quot; &quot;-ExcludeVersion&quot;
&quot;packages\FAKE\tools\Fake.exe&quot; build.fsx %*
</code></pre>
<p>All this file does is installing the tools I need to build the project, and then calls the build script with the arguments provided.</p>
<p>I separated the build script into some modules to make it easier to follow and I thought I would go through this module by module.</p>
<h4 id="npmmodule">Npm module</h4>
<p>The demo application had a simple js-app (that alerted &quot;Hello&quot;) to show that it is possible to build js-apps with FAKE. I would be stupid if I did not use the tools from the js-community to do the heavy lifting here, so that is exactly what I did. You can find the <a href="https://github.com/mastoj/FAKESimpleDemo/blob/master/src/FAKESimple.Web/package.json?ref=blog.2mas.xyz"><code>package.json</code> here</a> and the <a href="https://github.com/mastoj/FAKESimpleDemo/blob/master/src/FAKESimple.Web/gulpfile.js?ref=blog.2mas.xyz"><code>gulpfile.js</code> here</a>. I won&apos;t cover those since it is a different topic. When npm and gulp was configured all I needed to do was trigger it from FAKE and to do so I wrote a simple <code>Npm</code> wrapper. (I might extract this and try to submit a PR to FAKE later). The code is quite simple:</p>
<pre><code class="language-language-fsharp">module Npm =
  open System

  let npmFileName =
    match isUnix with
      | true -&gt; &quot;/usr/local/bin/npm&quot;
      | _ -&gt; &quot;./packages/Npm.js/tools/npm.cmd&quot;

  type InstallArgs =
    | Standard
    | Forced

  type NpmCommand =
    | Install of InstallArgs
    | Run of string

  type NpmParams = {
    Src: string
    NpmFilePath: string
    WorkingDirectory: string
    Command: NpmCommand
    Timeout: TimeSpan
  }

  let npmParams = {
    Src = &quot;&quot;
    NpmFilePath = npmFileName
    Command = Install Standard
    WorkingDirectory = &quot;.&quot;
    Timeout = TimeSpan.MaxValue
  }

  let parseInsallArgs = function
    | Standard -&gt; &quot;&quot;
    | Forced -&gt; &quot; --force&quot;

  let parse command =
    match command with
    | Install installArgs -&gt; sprintf &quot;install%s&quot; (installArgs |&gt; parseInsallArgs)
    | Run str -&gt; sprintf &quot;run %s&quot; str

  let run npmParams =
    let npmPath = Path.GetFullPath(npmParams.NpmFilePath)
    let arguments = npmParams.Command |&gt; parse
    let result = ExecProcess (
                  fun info -&gt;
                    info.FileName &lt;- npmPath
                    info.WorkingDirectory &lt;- npmParams.WorkingDirectory
                    info.Arguments &lt;- arguments
                  ) npmParams.Timeout
    if result &lt;&gt; 0 then failwith (sprintf &quot;&apos;npm %s&apos; failed&quot; arguments)

  let Npm f =
    npmParams |&gt; f |&gt; run
</code></pre>
<p>The <code>Npm</code> function is the important part. There I take the default arguments, pass it through <code>f</code> which adds changes to the arguments and then that is passed to <code>run</code>. The <code>run</code> method parse the <code>Command</code> property and execute <code>Npm</code>. It doesn&apos;t get simpler than that.</p>
<h4 id="octohelpersmodule">OctoHelpers module</h4>
<p>There were two things I wanted to do with Octopus Deploy; create release and create deploy. This helper module is a wrapper around the <code>Octo</code> module in FAKE since there were a lot of similarities between the steps.</p>
<pre><code class="language-language-fsharp">module OctoHelpers =
  let executeOcto command =
    let serverName = environVar &quot;OCTO_SERVER&quot;
    let apiKey = environVar &quot;OCTO_KEY&quot;
    let server = { Server = serverName; ApiKey = apiKey }
    Octo (fun octoParams -&gt;
        { octoParams with
            ToolPath = &quot;./packages/octopustools&quot;
            Server   = server
            Command  = command }
    )
</code></pre>
<p>All that is going on here is that I read some things from environment variables that should be configured on AppVeyor (or the CI you use) and then execute an action against Octopus Deploy.</p>
<h4 id="appveyorhelpermodule">AppVeyorHelper module</h4>
<p>I extracted the things that dealt with AppVeyor integration to a separate module to keep my targets clean (I get to the targets soon). It is actually one thing I&apos;m doing on AppVeyor and that is publishing the artifacts to the nuget feed hosted by AppVeyor.</p>
<pre><code class="language-language-fsharp">module AppVeyorHelpers =
  let execOnAppveyor arguments =
    let result =
      ExecProcess (fun info -&gt;
        info.FileName &lt;- &quot;appveyor&quot;
        info.Arguments &lt;- arguments
        ) (System.TimeSpan.FromMinutes 2.0)
    if result &lt;&gt; 0 then failwith (sprintf &quot;Failed to execute appveyor command: %s&quot; arguments)
    trace &quot;Published packages&quot;

  let publishOnAppveyor folder =
    !! (folder + &quot;*.nupkg&quot;)
    |&gt; Seq.iter (fun artifact -&gt; execOnAppveyor (sprintf &quot;PushArtifact %s&quot; artifact))
</code></pre>
<p>The <code>publishOnAppveyor</code> function takes a folder and finds all the nuget packages in it. After that it executes the <code>appveyor</code> command to publish every package to the feed.</p>
<h4 id="settingsmodule">Settings module</h4>
<p>The module name isn&apos;t perfect, but what is. It contains all the variables that are used in the targets as well as two three helper functions:</p>
<pre><code class="language-language-fsharp">module Settings =
  let buildDir = &quot;./.build/&quot;
  let packagingDir = buildDir + &quot;FAKESimple.Web/_PublishedWebsites/FAKESimple.Web&quot;
  let deployDir = &quot;./.deploy/&quot;
  let testDir = &quot;./.test/&quot;
  let projects = !! &quot;src/**/*.csproj&quot; -- &quot;src/**/*.Tests.csproj&quot;
  let testProjects = !! &quot;src/**/*.Tests.csproj&quot;
  let packages = !! &quot;./**/packages.config&quot;

  let getOutputDir proj =
    let folderName = Directory.GetParent(proj).Name
    sprintf &quot;%s%s/&quot; buildDir folderName

  let build proj =
    let outputDir = proj |&gt; getOutputDir
    MSBuildRelease outputDir &quot;ResolveReferences;Build&quot; [proj] |&gt; ignore

  let getVersion() =
    let buildCandidate = (environVar &quot;APPVEYOR_BUILD_NUMBER&quot;)
    if buildCandidate = &quot;&quot; || buildCandidate = null then &quot;1.0.0&quot; else (sprintf &quot;1.0.0.%s&quot; buildCandidate)
</code></pre>
<p>The <code>getOutputDir</code> is used to get the name of the folder of a file, it says <code>proj</code> but it could be any file. I&apos;m using it to create one output folder per project instead of everything ending up in the same folder or under <code>bin/release</code> as it usually does when building from VS. It is using the convention that the parent folder name of a project file is the name of the project. The <code>build</code> function is a wrapper to build one single project at a time to be able to specify the output folder per project. I don&apos;t bother to explain the <code>getVersion</code> function.</p>
<h4 id="targetsmodule">Targets module</h4>
<p>This is where I define all the separate steps. When I have all my helpers settled it is quite straighforward:</p>
<pre><code class="language-language-fsharp">module Targets =
  Target &quot;Clean&quot; (fun() -&gt;
    CleanDirs [buildDir; deployDir; testDir]
  )

  Target &quot;RestorePackages&quot; (fun _ -&gt;
    packages
    |&gt; Seq.iter (RestorePackage (fun p -&gt; {p with OutputPath = &quot;./src/packages&quot;}))
  )

  Target &quot;Build&quot; (fun() -&gt;
    projects
    |&gt; Seq.iter build
  )

  Target &quot;Web&quot; (fun _ -&gt;
    Npm (fun p -&gt;
      { p with
          Command = Install Standard
          WorkingDirectory = &quot;./src/FAKESimple.Web/&quot;
      })

    Npm (fun p -&gt;
      { p with
          Command = (Run &quot;build&quot;)
          WorkingDirectory = &quot;./src/FAKESimple.Web/&quot;
      })
  )

  Target &quot;CopyWeb&quot; (fun _ -&gt;
    let targetDir = packagingDir @@ &quot;dist&quot;
    let sourceDir = &quot;./src/FAKESimple.Web/dist&quot;
    CopyDir targetDir sourceDir (fun x -&gt; true)
  )

  Target &quot;BuildTest&quot; (fun() -&gt;
    testProjects
    |&gt; MSBuildDebug testDir &quot;Build&quot;
    |&gt; ignore
  )

  Target &quot;Test&quot; (fun() -&gt;
    !! (testDir + &quot;/*.Tests.dll&quot;)
        |&gt; xUnit2 (fun p -&gt;
            {p with
                ShadowCopy = false;
                HtmlOutputPath = Some (testDir @@ &quot;xunit.html&quot;);
                XmlOutputPath = Some (testDir @@ &quot;xunit.xml&quot;);
            })
  )

  Target &quot;Package&quot; (fun _ -&gt;
    trace &quot;Packing the web&quot;
    let version = getVersion()
    NuGet (fun p -&gt;
          {p with
              Authors = [&quot;Tomas Jansson&quot;]
              Project = &quot;FAKESimple.Web&quot;
              Description = &quot;Demoing FAKE&quot;
              OutputPath = deployDir
              Summary = &quot;Does this work&quot;
              WorkingDir = packagingDir
              Version = version
              Publish = false })
              (packagingDir + &quot;/FAKESimple.Web.nuspec&quot;)
  )

  Target &quot;Publish&quot; (fun _ -&gt;
    match buildServer with
    | BuildServer.AppVeyor -&gt;
        publishOnAppveyor deployDir
    | _ -&gt; ()
  )

  Target &quot;Create release&quot; (fun _ -&gt;
    let version = getVersion()
    let release = CreateRelease({ releaseOptions with Project = &quot;FAKESimple.Web&quot;; Version = version }, None)
    executeOcto release
  )

  Target &quot;Deploy&quot; (fun _ -&gt;
    let version = getVersion()
    let deploy = DeployRelease(
                  { deployOptions with
                      Project = &quot;FAKESimple.Web&quot;
                      Version = version
                      DeployTo = &quot;Prod&quot;
                      WaitForDeployment = true})
    executeOcto deploy
  )

  Target &quot;Default&quot; (fun _ -&gt;
    ()
  )
</code></pre>
<p>The responsibility of each target is as follows:</p>
<ul>
<li><code>Clean</code> - removes all the output files so I get a clean build</li>
<li><code>RestorePackages</code> - gets all the packages from nuget</li>
<li><code>Build</code> - take my definition of project files and runs the build helper for each one</li>
<li><code>Web</code> - restore all the node modules and then builds the js-app using <code>Npm</code></li>
<li><code>CopyWeb</code> - copy the js-app to the web application so it can be added to the package for deployment</li>
<li><code>BuildTest</code> - same as <code>Build</code> but for the test projects</li>
<li><code>Test</code> - execute the tests</li>
<li><code>Package</code> - packages the web application to a nuget package that I can use for deployment</li>
<li><code>Publish</code> - publishes all the packages to the nuget feed, in this case AppVeyor</li>
<li><code>Create release</code> - creates a release on Octopus Deploy</li>
<li><code>Deploy</code> - deploy the release created</li>
<li><code>Default</code> - empty default step that I can always use to run everything</li>
</ul>
<p>There were many steps there, but I think it is nice to have that separation in place. I could probably combine some of the steps, but I like it as it is since it is easier to move things around if I want to.</p>
<h4 id="thebuildprocess">The build process</h4>
<p>The last part is to defined the dependencies between all the targets, and here it is:</p>
<pre><code class="language-language-fsharp">&quot;Clean&quot;
==&gt; &quot;RestorePackages&quot;
==&gt; &quot;Build&quot;
==&gt; &quot;Web&quot;
==&gt; &quot;CopyWeb&quot;
==&gt; &quot;BuildTest&quot;
==&gt; &quot;Test&quot;
==&gt; &quot;Package&quot;
==&gt; &quot;Publish&quot;
==&gt; &quot;Create release&quot;
==&gt; &quot;Deploy&quot;
==&gt; &quot;Default&quot;

RunTargetOrDefault &quot;Default&quot;
</code></pre>
<p>I most likely only want to run down to <code>Test</code> locally and need to make some adjustments to run everything locally, but it is doable. The important part is that I can create an actual artifact locally, and that I&apos;m doing it the same way as I would on the build server.</p>
<h2 id="summary">Summary</h2>
<p>This post became longer than I thought, but I hope you see the use of using FAKE. Once more I think F# shows that it is a good fit for many different problems, not just science and math. If I start a new .NET-project today I would definitely add FAKE as one of the first things. That gives me a reliable build that executes the same way on the server and locally as well as version control of the build process compared to having it all configured in the CI server.</p>
<p>If you find any improvements, please comment here or on GitHub. You should be able to clone the <a href="https://github.com/mastoj/FAKESimpleDemo?ref=blog.2mas.xyz">repo</a> and just execute <code>build.cmd Test</code> to get started.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Constraints in FSharp]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>Constraints in F# is a really powerful feature, but it is also an area that I think is missing some clear documentation about how to use it. This will be a short write up for future me when I need it, and I also it will help some lost souls</p>]]></description><link>https://blog.2mas.xyz/constraints-in-fsharp/</link><guid isPermaLink="false">5e382b29f81c630018abe06d</guid><category><![CDATA[FSharp]]></category><category><![CDATA[.NET]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Sun, 18 Oct 2015 06:57:19 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>Constraints in F# is a really powerful feature, but it is also an area that I think is missing some clear documentation about how to use it. This will be a short write up for future me when I need it, and I also it will help some lost souls out there.</p>
<h2 id="inlinefunctions">Inline functions</h2>
<p>F# will most of the time handle the types for you, also generics when it can do so. A simple example:</p>
<pre><code class="language-language-fsharp">let add x y = x + y
</code></pre>
<p>This will when it stands all by itself resolve to the have the type:</p>
<p>val add : x:int -&gt; y:int -&gt; int</p>
<p>That all the compiler can do when it is not provided any more information. If you instead write</p>
<pre><code class="language-language-fsharp">let add x y = x + y
add &quot;Hello &quot; &quot;world&quot;
</code></pre>
<p><code>add</code> will get the type</p>
<pre><code class="language-language-fsharp">val add : x:string -&gt; y:string -&gt; string
</code></pre>
<p>since you on line two specify that you will use it with strings. What should you do if you want to add it with any arguments that supports the <code>+</code> operator? This is where the <code>inline</code> keyword is useful (it can also be used in some optimization scenarios). So let us define the function again and adding the <code>inline</code> keyword:</p>
<pre><code class="language-language-fsharp">let inline add x y = x + y
</code></pre>
<p>The type for this version of add is a little bit more complicated:</p>
<pre><code class="language-language-fsharp">val inline add :
  x: ^a -&gt; y: ^b -&gt;  ^c
    when ( ^a or  ^b) : (static member ( + ) :  ^a *  ^b -&gt;  ^c)
</code></pre>
<p>What does this mean?</p>
<ul>
<li><code>x: ^a -&gt; y: ^b -&gt;  ^c</code> specify that the function takes two arguments and returns something. The argument has types <code>^a</code> and <code>^b</code> and the result have type <code>^c</code></li>
<li><code>when ( ^a or  ^b) : (static member ( + ) :  ^a *  ^b -&gt;  ^c)</code> is adding a constraint on the types <code>^a</code>, <code>^b</code> and <code>^c</code>. The constraint says that it must exist a static operator <code>+</code> that takes a tuple of type <code>^a *  ^b</code> and returns type <code>^c</code>.</li>
</ul>
<p>We got all that by adding the keyword <code>inline</code>, but why? When adding the <code>inline</code> keyword you basically say that whenever you see the function name somewhere in the code replace that name with this function definition. This basically gives you one new implementation of the function every time you use it. If you don&apos;t use <code>inline</code> you will only have one implementation and that is why you don&apos;t get it as generic as you would like. This is my simplified explanation, someone on the compiler team can probably explain it a lot more in detail.</p>
<h2 id="constrainingoninterfaces">Constraining on interfaces</h2>
<p>I won&apos;t go on with you can constrain the types on interfaces because it quite simple and there is more interesting constraint in the next section. I&apos;ll just throw the code at you</p>
<pre><code class="language-language-fsharp">type ISimpleInterface =
    abstract member Add: int -&gt; int -&gt; int

type SimpleClassA() =
    interface ISimpleInterface with
        member this.Add x y = x + y

type SimpleClassB() =
    interface ISimpleInterface with
        member this.Add x y = x + y

let doSimple&lt;&apos;T when &apos;T :&gt; ISimpleInterface&gt;  (x: &apos;T) = x.Add 5 5
let doSimple2 (x: ISimpleInterface) = x.Add 5 5

let a = new SimpleClassA()
let b = new SimpleClassB()
doSimple a
doSimple b
</code></pre>
<p>Here first define an interface and then two implementations of that interface. After that I defines two functions <code>doSimple</code> and <code>doSimple2</code>, which are basically identical. I prefer to use the second variant when possible.</p>
<h2 id="ifitwalkslikeaduckandquacklikeaduck">If it walks like a duck and quack like a duck</h2>
<p><a href="https://en.wikipedia.org/wiki/Duck_typing?ref=blog.2mas.xyz">Duck typing</a> can be achieved in F# by using constraint. This is really powerful since you can write functions that take in arguments and as long as the types of the arguments support doesn&apos;t violate the constraint you can use them without the need of an interface. Why would you want to do this you might ask? The reason I started to look into this was actually because I needed it at work. I am using the excellent <a href="http://fsprojects.github.io/FSharp.Data.SqlClient/?ref=blog.2mas.xyz"><code>SqlClient</code> type provider</a>, and wanted to use the <code>SqlProgrammabilityProvider</code> to read and update multiple tables using the pipe operator. The problem is that the <code>Update</code> method is defined on the generated table type and not as a static <code>Update</code> method. A simplified version of what I had looks somewhat like this:</p>
<pre><code class="language-language-fsharp">type SomeClass1() =
    member
       this.Add(a:int, b:int) = a + b

type SomeClass2() =
    member
        this.Add(a:int, b:int) = a + b
</code></pre>
<p>and I wanted an <code>add</code> method that could be applied to either <code>SomeClass1</code> or <code>SomeClass2</code> so I could write <code>someClassInstance |&gt; add 2 3</code>. To achieve that you use member constraints like this:</p>
<pre><code class="language-language-fsharp">type SomeClass1() =
    member
        this.Add(a:int, b:int) = a + b

type SomeClass2() =
    member
        this.Add(a:int, b:int) = a + b

let inline add (y:int) (z:int) (x: ^T when ^T : (member Add : int*int-&gt;int)) =
    (^T : (member Add : int*int-&gt;int) (x,y,z))

SomeClass1() |&gt; add 2 3
SomeClass2() |&gt; add 2 3
</code></pre>
<p>In the function definition I define that I the argument <code>x</code> must have an operator called <code>Add</code> that has type <code>int*int-&gt;int</code>. In the body of the function I specify that I will call the <code>Add</code> function on variable <code>x</code> with the input of <code>y</code> and <code>z</code>. It looks complicated until you get your head around it. It is also important to specify the method as <code>inline</code>. One thing that is good to know is that it doesn&apos;t work for curried functions even though you don&apos;t get a compile time error.</p>
<p>The case I had was a slightly more complicated since the <code>Update</code> method I wanted to use had some optional arguments. If you know that optional arguments is represented as <code>Option</code> types in F# the code isn&apos;t that surprising:</p>
<pre><code class="language-language-fsharp">type SomeClass1Option() =
    member
        this.Add(?a:int, ?b:int) = 
            match a,b with
            | Some x, Some y -&gt; x + y
            | _, _ -&gt; 0

type SomeClass2Option() =
    member
        this.Add(?a:int, ?b:int) = 
            match a,b with
            | Some x, Some y -&gt; x + y
            | _, _ -&gt; 0

let inline add (y:int) (z:int) (x: ^T when ^T : (member Add : int option*int option-&gt;int)) =
    (^T : (member Add : int option*int option-&gt;int) (x,Some y,Some z))

SomeClass1Option() |&gt; add 2 3
SomeClass2Option() |&gt; add 2 3
</code></pre>
<p>Given all this I ended up writing an <code>update</code> method that looks like this:</p>
<pre><code class="language-language-fsharp">let inline updateTable(table: ^T when ^T : (member Update : SqlConnection option*SqlTransaction option*int option -&gt; int)) = 
    (^T : (member Update : SqlConnection option*SqlTransaction option*int option-&gt; int) (table, None, None, None))
</code></pre>
<p>That method can be used with piping to call the <code>Update</code> method on any table generated with <code>SqlProgrammabilityProvider</code> with default arguments.</p>
<p>You can also write constraint on static operators, but I won&apos;t cover that. The documentation for constraints is found here: <a href="https://msdn.microsoft.com/en-us/library/dd233203.aspx?ref=blog.2mas.xyz">https://msdn.microsoft.com/en-us/library/dd233203.aspx</a>.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Suave as a service with Topshelf]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>As you can read in <a href="http://blog.tomasjansson.com/topshelf-fharp-api-improved/?ref=blog.2mas.xyz">Topshelf F# api improved</a> I started working on a demo, but it magically grown to include a change to the <code>Topshelf.FSharp</code> project. The good part with this is that to run <code>Suave</code> with <code>Topshelf</code> as a Windows service have never been easier than now.</p>]]></description><link>https://blog.2mas.xyz/suave-as-a-service-with-topshelf/</link><guid isPermaLink="false">5e382b29f81c630018abe06b</guid><category><![CDATA[FSharp]]></category><category><![CDATA[Topshelf]]></category><category><![CDATA[Suave]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Sun, 28 Jun 2015 17:14:00 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>As you can read in <a href="http://blog.tomasjansson.com/topshelf-fharp-api-improved/?ref=blog.2mas.xyz">Topshelf F# api improved</a> I started working on a demo, but it magically grown to include a change to the <code>Topshelf.FSharp</code> project. The good part with this is that to run <code>Suave</code> with <code>Topshelf</code> as a Windows service have never been easier than now. The example code will be made available official examples for Suave, I hope, but meanwhile you can find the code on <a href="https://github.com/mastoj/SuaveTopShelfDemo?ref=blog.2mas.xyz">github</a>.</p>
<h2 id="thecodetldr">The code &lt;tl;dr;&gt;</h2>
<pre><code>open Suave
open Suave.Http.Successful
open Suave.Web 
open Suave.Http
open Suave.Http.Applicatives
open Suave.Http.Successful
open Topshelf
open System
open System.Threading

[&lt;EntryPoint&gt;]
let main argv = 
    printfn &quot;%A&quot; argv

    let cancellationTokenSource = ref None

    let home = choose [path &quot;/&quot; &gt;&gt;= GET &gt;&gt;= OK &quot;Hello world&quot;]
    let mind = choose [path &quot;/mind&quot; &gt;&gt;= GET &gt;&gt;= OK &quot;Where is my mind?&quot;]
    let app = choose [ home; mind ]

    let start hc = 
        let cts = new CancellationTokenSource()
        let token = cts.Token
        let config = { defaultConfig with cancellationToken = token}

        startWebServerAsync config app
        |&gt; snd
        |&gt; Async.StartAsTask 
        |&gt; ignore

        cancellationTokenSource := Some cts
        true

    let stop hc = 
        match !cancellationTokenSource with
        | Some cts -&gt; cts.Cancel()
        | None -&gt; ()
        true

    Service.Default 
    |&gt; display_name &quot;ServiceDisplayName&quot;
    |&gt; instance_name &quot;ServiceName&quot;
    |&gt; with_start start
    |&gt; with_stop stop
    |&gt; with_topshelf
</code></pre>
<h2 id="whatisgoingon">What is going on?</h2>
<p>I don&apos;t think the code need much explanation, but here are some lines. First we create a <code>CancellationToken</code> which we pass to the <code>start</code> function. The <code>stop</code> can then use the <code>CancellationTokenSource</code> to cancel the <code>async</code> operation that we start in the <code>start</code> function. Right before <code>start</code> we define our <code>Suave</code> app, it consist of two web parts, <code>home</code> and <code>mind</code> which are combined to one app in <code>app</code>. When the <code>start</code> and <code>stop</code> functions are defined it is trivial to use the new updated version of <code>Topshelf.FSharp</code> to run the suave application as a service.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[Topshelf F# api improved]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>My plan was never to improve the F# api for <a href="http://topshelf-project.com/?ref=blog.2mas.xyz">Topshelf</a>, <a href="https://github.com/haf/Topshelf.FSharp?ref=blog.2mas.xyz">Topshelf.FSharp</a>, but <a href="https://twitter.com/henrikfeldt?ref=blog.2mas.xyz">Henrik Feldt</a> asked me to when he saw what I was doing when working with a <a href="http://suave.io/?ref=blog.2mas.xyz">Suave</a>, which Henrik is a core contributor of, demo where I host the application in <code>Topshelf</code>. I implemented a simple</p>]]></description><link>https://blog.2mas.xyz/topshelf-fharp-api-improved/</link><guid isPermaLink="false">5e382b29f81c630018abe06a</guid><category><![CDATA[FSharp]]></category><category><![CDATA[Topshelf]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Sun, 28 Jun 2015 17:05:01 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>My plan was never to improve the F# api for <a href="http://topshelf-project.com/?ref=blog.2mas.xyz">Topshelf</a>, <a href="https://github.com/haf/Topshelf.FSharp?ref=blog.2mas.xyz">Topshelf.FSharp</a>, but <a href="https://twitter.com/henrikfeldt?ref=blog.2mas.xyz">Henrik Feldt</a> asked me to when he saw what I was doing when working with a <a href="http://suave.io/?ref=blog.2mas.xyz">Suave</a>, which Henrik is a core contributor of, demo where I host the application in <code>Topshelf</code>. I implemented a simple Topshelf wrapper that had a nice, at least I think so, fluent api. The <code>Topshelf.FSharp</code> also had a fluent api, but it was somewhat more complicated so what I was asked to do was implement my concept in the existing <code>Topshelf.FSharp</code> project, and so I did (released as version 2.0.1 of the package).</p>
<h2 id="theapi">The API</h2>
<p>The already existing API was good, but there some things that could be improved. The major plus with the existing function was that it already had existing functions for basically do every possible configuration of the service, so all I had to do was to find a nicer way to improve the fluent part of the API. The goal I had in mind, and what I implemented in my demo was an API looking somewhat like this:</p>
<pre><code>Service.Default
|&gt; with_start start
|&gt; with_recovery (ServiceRecovery.Default |&gt; restart (min 10))
|&gt; with_stop stop
|&gt; run
</code></pre>
<p>It&apos;s really easy to follow and true to F#. There are many more functions you could execute before run to configure the service, but the most important ones are <code>with_start</code>, <code>with_stop</code> and <code>run</code>. The start and stop functions just take a single functions which are executed on start and stop and returns a bool and the run function is what executes the service and returns an <code>int</code> as expected. I won&apos;t cover any more details, but just look at the github repo if you want to know what configuration functions there is.</p>
<h2 id="underthehood">Under the hood</h2>
<p>So how do one build this type of API on top of another more OO oriented framework and one answer to this is to use a kind of builder pattern. All the functions before <code>run</code> function is executed just creates a specification of the service and what should happen when <code>run</code> is executed. The specification I ended up implementing for <code>Topshelf</code> look like this:</p>
<pre><code>type Service =
  { Start: HostControl -&gt; bool
    Stop: HostControl -&gt; bool
    HostConfiguration: (HostConfigurator -&gt; HostConfigurator) list }
  static member Default =
      { Start = (fun _ -&gt; true)
        Stop = (fun _ -&gt; true)
        HostConfiguration = [] }
</code></pre>
<p>For a service to work you need a start and stop function, and that is what <code>with_start</code> and <code>with_stop</code> do. All the functions, except from <code>run</code>, take the <code>Service</code> type as the last parameter as well as returning a new instance of a <code>Service</code> making it possible to pipe the specification between all the configuration steps. The static <code>Default</code> member makes it easy to start the configuration. To configure the service all the configuration functions add a function to the list of <code>HostConfiguration</code> describing what should be done when the service is instantiated. This is done by a base function <code>add_host_configuration_step</code> which all the configuration functions partially applies like below:</p>
<pre><code>let add_host_configuration_step step service =
    {service with HostConfiguration = step::service.HostConfiguration}

let enable_pause_and_continue =
    add_host_configuration_step (fun c -&gt; c.EnablePauseAndContinue();c)
</code></pre>
<p>To start the service there are a couple of things we need to do, but first the code and then the description of it</p>
<pre><code>let toAction1 f = new Action&lt;_&gt;(f)
let toFunc f = new Func&lt;_&gt;(f)

let service_control (start : HostControl -&gt; bool) (stop : HostControl -&gt; bool) () =
  { new ServiceControl with
    member x.Start hc =
      start hc
    member x.Stop hc =
      stop hc }

let create_service (hc:HostConfigurator) service_func =
  hc.Service&lt;ServiceControl&gt;(service_func |&gt; toFunc) |&gt; ignore

let run service =
  let hostFactoryConfigurator hc =
      let createdHc = service.HostConfiguration |&gt; List.fold (fun chc x -&gt; x chc) hc
      service_control service.Start service.Stop
      |&gt; create_service createdHc

  hostFactoryConfigurator |&gt; toAction1 |&gt; HostFactory.Run |&gt; int
</code></pre>
<p>First we need to figure out what the we need to run the service, and the <code>Topshelf</code> <code>HostFactory.Run</code> method takes an <code>Action&lt;HostConfigurator&gt;</code>. To create action from a F# lambda I have a simple helper function, <code>toAction1</code>. And to create the actual lambda that takes a <code>HostConfigurator</code> we just create a function that has a single parameter <code>let hostFactoryConfigurator hc</code>, and now we can send this function to <code>toAction1</code> and we have what we need to run the service. To run the actual configuration in the <code>hostFactoryConfigurator</code> we just left fold over the <code>HostConfiguration</code> list with the first <code>HostConfiguration</code> as initial state and apply the functions. When we&apos;ve done that we can just create our <code>ServiceControl</code> from the final <code>HostConfigurator</code>, after left fold, and pass in the start and stop functions and we&apos;re done.</p>
<h2 id="improvements">Improvements</h2>
<p>The api can be improved a little bit, but now it works in a nice way. The major improvements that can be added is validation and create separate types for start and stop so we don&apos;t mix them. The validation wasn&apos;t in the API when I started implemented the change so I didn&apos;t add them now either and I don&apos;t think they are crucial either.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[NDC Oslo 2015 wrap up]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>At NDC Oslo 2015 I had the opportunity to speak, and it was a fun experience. My talk, F# as our day job by 2016, was part of the functional track and it was a popular track. I had well over 100 people in the audience for my talk even</p>]]></description><link>https://blog.2mas.xyz/ndc-oslo-2015-wrap-up/</link><guid isPermaLink="false">5e382b29f81c630018abe069</guid><category><![CDATA[functional]]></category><category><![CDATA[FSharp]]></category><category><![CDATA[NDC]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Sat, 20 Jun 2015 12:02:55 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>At NDC Oslo 2015 I had the opportunity to speak, and it was a fun experience. My talk, F# as our day job by 2016, was part of the functional track and it was a popular track. I had well over 100 people in the audience for my talk even though it was the second last talk of the conference, and it is really nice to see a growing interest in the functional programming world. I stayed most of the time in the functional track room, and here are some of my takeaways.</p>
<h2 id="wearebecomingmorefunctional">We are becoming more functional!</h2>
<p>I think this is the third or fourth time there is a functional track at NDC, if you count NDC London as well, and I have never seen this much people for the tracks as I did this year. It started of great with a packed room for <a href="https://twitter.com/bryan_hunter?ref=blog.2mas.xyz">Bryan Hunter&apos;s</a> &quot;Lean and Functional Programming&quot; talk, a talk I really enjoyed. Even though the language you use is not the biggest problem, but it is one way that you can improve yourself, and choosing functional will most likely help with that.</p>
<p>Another talk that I really like was <a href="https://twitter.com/theburningmonk?ref=blog.2mas.xyz">Yan Cui&apos;s</a> &quot;A tour of the language landscape&quot;. Important parts here was that you need to put in the hours, and it is enough with 20 hours dedicated learning, to get of a good start. Of course 20 hours want make you a master, but after that you will most likely be able to start producing.</p>
<p>If you want to see a general talk about why should start doing functional I recommend <a href="https://twitter.com/venkat_s?ref=blog.2mas.xyz">Venkat Subramaniam&apos;s</a> &quot;Learning from Haskell&quot;. He explained to us things like &quot;C++ is not strongly typed, it is sadly typed&quot;, and why that is a problem. If you have a good strongly typed functional language with great type inference it will most likely feel as you are in a dynamic language, and this is the nature of languages like Haskell and also F#.</p>
<p>If you are a C# developer and want is interested in F# I do recommend the talk by <a href="https://twitter.com/ptrelford?ref=blog.2mas.xyz">Phillip Trelford</a> (or Sean&apos;s dad) where he showed &quot;F# for C# Developers&quot;. I can also pitch my own talk &quot;F# as our day job by 2016&quot; where I try to show some arguments to why I like F# more than C# and also some facts to back that up. That might be a good resource if you want to start using F# in your project.</p>
<p>If you&apos;re more into functional design I do recommend <a href="https://twitter.com/ScottWlaschin?ref=blog.2mas.xyz">Scott Wlaschin&apos;s</a> &quot;Enterprise Tic-Tac-Toc -- A functional approach&quot;, which was entertaining and a lot of useful information, as always when Scott presents). The &quot;Type-Driven Development&quot; by <a href="https://twitter.com/ploeh?ref=blog.2mas.xyz">Mark Seeman</a> i also a great talk for this topic.</p>
<h2 id="whatwillitryaftertheconference">What will I try after the conference</h2>
<p>Even though I have done some F# I haven&apos;t tried idiomatic web development with F# and that is something I definitely will try out after I saw <a href="https://twitter.com/tomaspetricek?ref=blog.2mas.xyz">Tomas Petricek</a> demoing <a href="http://suave.io/?ref=blog.2mas.xyz">suave</a> on stage. He basically implemented two applications and also deployed one of the to azure and heroku in about 45 minutes. Of course he had some small things prepared for building, but he basically implemented the whole backend in that time.</p>
<p>The next thing I&apos;ll looking at is <a href="http://elixir-lang.org/?ref=blog.2mas.xyz">elixir</a> and <a href="http://www.phoenixframework.org/?ref=blog.2mas.xyz">Phoenix</a>. The creator of elixir, <a href="https://twitter.com/josevalim?ref=blog.2mas.xyz">Jos&#xE9; Valim</a>, was at the conference and had a great talk about idioms for building distributed applications in elixir. The main reasons that is possible is because of the erlang vm which you use to run elixir. Elixir supposed to have nicer syntax and a great metaprogramming model to extend the language for your domain. The metaprogramming model was something <a href="https://twitter.com/chris_mccord?ref=blog.2mas.xyz">Chris McCord</a>, the author of Phoenix, demonstrated in one of his great technical talks. The other talk he had was an introduction to Phoenix which I also recommend.</p>
<h2 id="dontwaitforthecommunitybethecommunity">Don&apos;t wait for the community, be the community!</h2>
<p>My talk was almost the last talk of the conference it was supposed to be a &quot;call to action&quot; talk for functional developers in Norway. Now is the time to start doing functional programming if you haven&apos;t done it before. Of course it might slow you down for a period of time, but thinking like that will not make you in the long run. Improvement doesn&apos;t happen over night, you have to practice it and you will see that the new knowledge you get will arm you with new ways of thinking about problem.</p>
<p>If you don&apos;t have a community were you live, don&apos;t let that stop you instead you should <strong>be the community!</strong>. There are ton of material online and I promise you that there are other people where you live that are interested in functional programming in general and specifically F#. If it is a F# community you want to grow you can always reach out to the people at the <a href="http://fsharp.org/?ref=blog.2mas.xyz">F# foundation</a> or people on twitter and you will get help.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[ASP.NET 5: Hosting your application in Docker]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>A couple of weeks ago I had a presentation about ASP.NET 5 and MVC 6 at NNUG Oslo. The presentation wasn&apos;t recorded so I thought I just write some blog posts about it insted. This will be a serie of posts where I plan to go through</p>]]></description><link>https://blog.2mas.xyz/asp-net-5-hosting-your-application-in-docker/</link><guid isPermaLink="false">5e382b29f81c630018abe068</guid><category><![CDATA[asp.net 5]]></category><category><![CDATA[docker]]></category><category><![CDATA[.NET]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Mon, 18 May 2015 18:46:57 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>A couple of weeks ago I had a presentation about ASP.NET 5 and MVC 6 at NNUG Oslo. The presentation wasn&apos;t recorded so I thought I just write some blog posts about it insted. This will be a serie of posts where I plan to go through the features that I demonstrated during the presentation, plus some more features that I didn&apos;t have time to cover. I&apos;ll start with the basic and show one thing at a time and then add features as we go along. So let&apos;s get started.</p>
<p>Post in this serie:</p>
<ul>
<li><a href="http://blog.tomasjansson.com/asp-net-5-the-pipeline/?ref=blog.2mas.xyz">The pipeline</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-adding-mvc-to-an-application?ref=blog.2mas.xyz">Adding MVC to an application</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-setting-up-frontend-build-with-grunt/?ref=blog.2mas.xyz">Setting up frontend build (with grunt)</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-ioc-and-dependency-injection/?ref=blog.2mas.xyz">IoC and dependency injection</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-view-components/?ref=blog.2mas.xyz">View Components</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-self-hosting-the-application/?ref=blog.2mas.xyz">Self-hosting the application</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-hosting-your-application-in-docker/?ref=blog.2mas.xyz">Hosting your application in docker</a></li>
</ul>
<p>Source code: <a href="https://github.com/mastoj/OneManBlog?ref=blog.2mas.xyz">https://github.com/mastoj/OneManBlog</a></p>
<h2 id="thenextlogicalstepiscontainerhosting">The next logical step is container hosting</h2>
<p>Microsoft stepping in and partnering up with <a href="https://www.docker.com/?ref=blog.2mas.xyz">Docker</a> was great news for the future if you ask me. Hosting applications is a container is a nice mix between light weight hosting and isolation between the application. There exist some security issues with hosting in a container that a someone could take advantage of if the container is running on a host that is not isolated enough, but don&apos;t let us go into that discussion.</p>
<p>The goal of this post is to show you one way to host your ASP.NET 5 application inside a docker container. I will not go into details about how you should put this container into production, mainly because I need to figure out a nice way to do it myself first.</p>
<h2 id="dockermachineanddocker">Docker Machine and Docker</h2>
<p>To manage different &quot;hosting machines&quot; I use <a href="https://docs.docker.com/machine/?ref=blog.2mas.xyz">Docker Machine</a>, not because I have many machines but because it is easy to manage machines with Docker Machine. Installation is straightforward and the documentation is good so I want go into all details about Docker Machine, all we&apos;re going to do is create virtual machine that we can use to host our docker containers. To create a machine on VirtualBox you run the following command:</p>
<pre><code>$ docker-machine create --driver virtualbox dev
</code></pre>
<p>Note that it is recommended to use msysgit when running Docker Machine, on Windows I recommend using <a href="https://chocolatey.org/packages/ConEmu?ref=blog.2mas.xyz">ConEmu (install from Chocolatey)</a> and run bash inside ConEmu to use Docker Machine and Docker. To target this machine and start using Docker against it you run the following command:</p>
<pre><code>$ eval &quot;$(docker-machine env dev)&quot;
</code></pre>
<p>The last thing before we start defining our docker image is to find the IP of the current machine so we can test it later, execute the following and note down the IP (it is most likely 192.168.99.100):</p>
<pre><code>$ docker-machine ip
</code></pre>
<h2 id="updatingtheproject">Updating the project</h2>
<p>Before we create the container image definition file we need to update the project so we can host it in a linux container. We need one more dependency in our <code>project.json</code> file and one more command so we can start the application:</p>
<pre><code>&quot;dependencies&quot;: {
    &quot;Microsoft.AspNet.Mvc&quot;: &quot;6.0.0-beta4&quot;,
    &quot;Microsoft.AspNet.Server.IIS&quot;: &quot;1.0.0-beta4&quot;,
    &quot;Microsoft.AspNet.StaticFiles&quot;: &quot;1.0.0-beta4&quot;,
    &quot;Microsoft.AspNet.Server.WebListener&quot;: &quot;1.0.0-beta4&quot;,
    &quot;Microsoft.AspNet.Hosting&quot;: &quot;1.0.0-beta4&quot;,
    &quot;Kestrel&quot;: &quot;1.0.0-beta4&quot;
},
&quot;commands&quot;: {
    &quot;web&quot;: &quot;Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000&quot;,
    &quot;kestrel&quot;: &quot;Microsoft.AspNet.Hosting --server Kestrel --server.urls http://localhost:5001&quot;
},
</code></pre>
<p>The new part is the <code>Kestrel</code> package is a web server that runs on ASP.NET 5 applications on linux. To start a web server with <code>Kestrel</code> we add the <code>kestrel</code> command which we can use with dnx on linux.</p>
<h2 id="creatingthedockerfile">Creating the Dockerfile</h2>
<p>A docker image is sort of starting point for a container. You define images with <code>Dockerfile</code>s, which you can base on other images so you get a hiearchy of images basically. A running instance of an image is what is called a container, so they are almost the same thing but one is passive and one is active. We are going to base our image on the official <a href="https://registry.hub.docker.com/u/microsoft/aspnet/?ref=blog.2mas.xyz">ASP.NET image</a>, but we will add node, grunt and bower so we can build the application when we create the image. The <code>Dockerfile</code> we have define look like:</p>
<pre><code>FROM microsoft/aspnet:vs-1.0.0-beta4

COPY . /app
WORKDIR /app

RUN apt-get update -y &amp;&amp; apt-get install --no-install-recommends -y -q \
    curl \
    python \
    build-essential \
    git \
    ca-certificates

RUN mkdir /nodejs &amp;&amp; \
    curl http://nodejs.org/dist/v0.10.33/node-v0.10.33-linux-x64.tar.gz | \
    tar xvzf - -C /nodejs --strip-components=1

ENV PATH $PATH:/nodejs/bin

RUN npm install -g grunt-cli bower

RUN [&quot;dnu&quot;, &quot;restore&quot;]
RUN [&quot;npm&quot;, &quot;install&quot;, &quot;.&quot;]
RUN [&quot;grunt&quot;, &quot;default&quot;]

EXPOSE 5001

ENTRYPOINT [&quot;dnx&quot;, &quot;./&quot;, &quot;kestrel&quot;]
</code></pre>
<p>Let us go through this line by line (almost):</p>
<ul>
<li><code>COPY . /app</code>, I have put the <code>Dockerfile</code> in the same folder as the <code>project.json</code> file this command copies all the code on the host into the <code>/app</code> folder in the image.</li>
<li><code>WORKDIR /app</code>, just sets the current working directory for when we execute the rest of the commands.</li>
<li>The next two <code>RUN</code> commands and the <code>ENV</code> command installs and add <a href="https://nodejs.org/?ref=blog.2mas.xyz">nodejs</a> to the environment in the image.</li>
<li>When we have <code>nodejs</code> installs we can install <code>grunt</code> and <code>bower</code> using <code>npm</code> with the <code>RUN</code> command in the image.</li>
<li><code>RUN [&quot;dnu&quot;, &quot;restore&quot;]</code> installs all the packages.</li>
<li><code>RUN [&quot;npm&quot;, &quot;install&quot;, &quot;.&quot;]</code> installs all the javascript packages.</li>
<li><code>RUN [&quot;grunt&quot;, &quot;default&quot;]</code> execute the <code>grunt</code> build steps that I wrote about <a href="http://blog.tomasjansson.com/asp-net-5-setting-up-frontend-build-with-grunt/?ref=blog.2mas.xyz">here</a>.</li>
<li>In our command we specified that we will use port 5001 for <code>kestrel</code>, so we use <code>EXPOSE 5001</code> to expose that port from the image when we run it.</li>
<li>The last row, <code>ENTRYPOINT [&quot;dnx&quot;, &quot;./&quot;, &quot;kestrel&quot;]</code>, specifies that when we run this image (making it a container) we will execute <code>dnx</code> and in the current folder passing it the <code>kestrel</code> command.</li>
</ul>
<p>No when we have the <code>Dockerfile</code> ready all we need to do is to create the image:</p>
<pre><code>$ docker build -t onemanblog .
</code></pre>
<p>and then start a container with:</p>
<pre><code>$ docker run -i -t -p 5001:5001 onemanblog
</code></pre>
<p>The <code>-i</code> and <code>-t</code> flags make the container run in interactive mode, which means we see if it crashes and it also listens to <code>stdin</code>, that is, we can press enter to stop the application. The <code>-p 5001:5001</code> redirects the port 5001 from host to the container.</p>
<h2 id="summary">Summary</h2>
<p>If you have followed all the steps above you should now have a running container which you can go to <code>http://&lt;ip from &quot;docker-machine ip&quot;&gt;:5001/</code> and you should see the same application as we previously ran on Windows.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[ASP.NET 5: Self-hosting the application]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>A couple of weeks ago I had a presentation about ASP.NET 5 and MVC 6 at NNUG Oslo. The presentation wasn&apos;t recorded so I thought I just write some blog posts about it insted. This will be a serie of posts where I plan to go through</p>]]></description><link>https://blog.2mas.xyz/asp-net-5-self-hosting-the-application/</link><guid isPermaLink="false">5e382b29f81c630018abe067</guid><category><![CDATA[asp.net mvc]]></category><category><![CDATA[asp.net 5]]></category><category><![CDATA[dnx]]></category><category><![CDATA[.NET]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Thu, 14 May 2015 18:12:01 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>A couple of weeks ago I had a presentation about ASP.NET 5 and MVC 6 at NNUG Oslo. The presentation wasn&apos;t recorded so I thought I just write some blog posts about it insted. This will be a serie of posts where I plan to go through the features that I demonstrated during the presentation, plus some more features that I didn&apos;t have time to cover. I&apos;ll start with the basic and show one thing at a time and then add features as we go along. So let&apos;s get started.</p>
<p>Post in this serie:</p>
<ul>
<li><a href="http://blog.tomasjansson.com/asp-net-5-the-pipeline/?ref=blog.2mas.xyz">The pipeline</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-adding-mvc-to-an-application?ref=blog.2mas.xyz">Adding MVC to an application</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-setting-up-frontend-build-with-grunt/?ref=blog.2mas.xyz">Setting up frontend build (with grunt)</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-ioc-and-dependency-injection/?ref=blog.2mas.xyz">IoC and dependency injection</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-view-components/?ref=blog.2mas.xyz">View Components</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-self-hosting-the-application/?ref=blog.2mas.xyz">Self-hosting the application</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-hosting-your-application-in-docker/?ref=blog.2mas.xyz">Hosting your application in docker</a></li>
</ul>
<p>Source code: <a href="https://github.com/mastoj/OneManBlog?ref=blog.2mas.xyz">https://github.com/mastoj/OneManBlog</a></p>
<h2 id="settingupselfhosting">Setting up self-hosting</h2>
<p>In ASP.NET 5 you are more in charge of how you host the application. So far we&apos;ve been using IIS (or IIS Express), but I thought I would show how easy it is to add self-hosting to the application. Self-hosting is great if you want to run it as a service instead of in IIS.</p>
<h3 id="updatingprojectjson">Updating project.json</h3>
<p>The first step is to add two more packages we need to add:</p>
<ul>
<li><code>Microsoft.AspNet.Hosting</code> - the hosting infrastructure</li>
<li><code>Microsoft.AspNet.Server.WebListener</code> - the self-hosted web server implementation for Windows</li>
</ul>
<p>The <code>dependencies</code> node in the  <code>project.json</code> file should now look like:</p>
<pre><code>&quot;dependencies&quot;: {
    &quot;Microsoft.AspNet.Mvc&quot;: &quot;6.0.0-beta4&quot;,
    &quot;Microsoft.AspNet.Server.IIS&quot;: &quot;1.0.0-beta4&quot;,
    &quot;Microsoft.AspNet.StaticFiles&quot;: &quot;1.0.0-beta4&quot;,
    &quot;Microsoft.AspNet.Server.WebListener&quot;: &quot;1.0.0-beta4&quot;,
    &quot;Microsoft.AspNet.Hosting&quot;: &quot;1.0.0-beta4&quot;
},
</code></pre>
<p>The last thing we need to do is add a &quot;command&quot; to the <code>commands</code> node:</p>
<pre><code>&quot;commands&quot;: {
    &quot;web&quot;: &quot;Microsoft.AspNet.Hosting --server Microsoft.AspNet.Server.WebListener --server.urls http://localhost:5000&quot;
},
</code></pre>
<p>After you added that you will get a new menu item under the debug button called web:</p>
<p><img src="https://storage.ghost.io/c/7c/9f/7c9f0302-e2eb-4fec-95af-b7c64874855a/content/images/2015/05/Self-hosting.PNG" alt="Self-hosting menu item" loading="lazy"></p>
<p>Choosing that menu item and start the application will start the self-hosted version instead of IIS Express.</p>
<h3 id="dnvmdnxanddnu">DNVM, DNX and DNU</h3>
<p>If you want to run this from the command line you first install <code>DNVM</code>. To install it you can follow the instructions here: <a href="https://github.com/aspnet/home?ref=blog.2mas.xyz#powershell">https://github.com/aspnet/home#powershell</a>. You use <code>DNVM</code> to manage which version of <code>DNX</code> and <code>DNU</code> you want to use. After <code>DNVM</code> you can run a command like:</p>
<pre><code>dnvm use 1.0.0-beta4 -r coreclr -arch x64
</code></pre>
<p>This will select version 1.0.0-beta4 and the core runtime. When we have selected the version you can now use <code>DNX</code> to run the application from the command line with the following command:</p>
<pre><code>dnx . web
</code></pre>
<p>Note that the command above only works is you are in the same folder as the <code>project.json</code> file and that <code>web</code> must match the name of the command in the <code>project.json</code> file. If you need to restore the packages you can run <code>DNU</code> before <code>DNX</code>:</p>
<pre><code>dnu restore
</code></pre>
<!--kg-card-end: markdown-->]]></content:encoded></item><item><title><![CDATA[ASP.NET 5: View Components]]></title><description><![CDATA[<!--kg-card-begin: markdown--><p>A couple of weeks ago I had a presentation about ASP.NET 5 and MVC 6 at NNUG Oslo. The presentation wasn&apos;t recorded so I thought I just write some blog posts about it insted. This will be a serie of posts where I plan to go through</p>]]></description><link>https://blog.2mas.xyz/asp-net-5-view-components/</link><guid isPermaLink="false">5e382b29f81c630018abe066</guid><category><![CDATA[asp.net mvc]]></category><category><![CDATA[asp.net]]></category><category><![CDATA[asp.net 5]]></category><category><![CDATA[mvc]]></category><category><![CDATA[.NET]]></category><dc:creator><![CDATA[Tomas Jansson]]></dc:creator><pubDate>Sat, 09 May 2015 20:38:05 GMT</pubDate><content:encoded><![CDATA[<!--kg-card-begin: markdown--><p>A couple of weeks ago I had a presentation about ASP.NET 5 and MVC 6 at NNUG Oslo. The presentation wasn&apos;t recorded so I thought I just write some blog posts about it insted. This will be a serie of posts where I plan to go through the features that I demonstrated during the presentation, plus some more features that I didn&apos;t have time to cover. I&apos;ll start with the basic and show one thing at a time and then add features as we go along. So let&apos;s get started.</p>
<p>Post in this serie:</p>
<ul>
<li><a href="http://blog.tomasjansson.com/asp-net-5-the-pipeline/?ref=blog.2mas.xyz">The pipeline</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-adding-mvc-to-an-application?ref=blog.2mas.xyz">Adding MVC to an application</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-setting-up-frontend-build-with-grunt/?ref=blog.2mas.xyz">Setting up frontend build (with grunt)</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-ioc-and-dependency-injection/?ref=blog.2mas.xyz">IoC and dependency injection</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-view-components/?ref=blog.2mas.xyz">View Components</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-self-hosting-the-application/?ref=blog.2mas.xyz">Self-hosting the application</a></li>
<li><a href="http://blog.tomasjansson.com/asp-net-5-hosting-your-application-in-docker/?ref=blog.2mas.xyz">Hosting your application in docker</a></li>
</ul>
<p>Source code: <a href="https://github.com/mastoj/OneManBlog?ref=blog.2mas.xyz">https://github.com/mastoj/OneManBlog</a></p>
<h2 id="whatisviewcomponents">What is view components?</h2>
<p>Partial views in MVC has one limitation, which is that they doesn&apos;t have a controller for them. Not having controller makes it hard to have more complex logic associated with the view. View components changes that. Each view component consist of a view and a backing class, it&apos;s not a controller but almost. In this post we will take the post list which we created by injecting the &quot;repository&quot; into the index view in the <a href="http://blog.tomasjansson.com/asp-net-5-ioc-and-dependency-injection/?ref=blog.2mas.xyz">last post</a> and create a reuseable view component instead which we can use in multiple views.</p>
<h2 id="creatingtheviewcomponent">Creating the view component</h2>
<p>The purpose of this view component is to list all the posts for this simple blog, making it much easier to reuse in multiple views. An alternative would have been to use a partial view, but using a partial view would have forced us to get the data for the partial view in the controller for each of the views where we used the partial, but since a view component has a backing class that is not necessary.</p>
<h3 id="theviewcomponentclass">The ViewComponent class</h3>
<p>Create a folder called <code>ViewComponents</code> where you can have all your view components and add a <code>PostListViewComponent</code> class in the folder. The implementation of the class should look like this:</p>
<pre><code>public class PostListViewComponent : ViewComponent
{
    private readonly Data _data;

    public PostListViewComponent(Data data)
    {
        _data = data;
    }

    public IViewComponentResult Invoke(string title)
    {
        ViewBag.Title = title;
        return View(_data.GetPosts());
    }
}
</code></pre>
<p>We are inheriting from the class <code>ViewComponent</code> to get some extra help, like the <code>View</code> method in the base class. The <code>Invoke</code> method is what will be called from the views that adds this view component and it is returning a simple view that show the posts. We are also injecting the <code>Data</code> class in the constructor which makes it possible to get the data we need in this class instead of it being sent to it like you do with a partial view. The view we return has a <code>ViewBag</code> as a regular view which we take advantage of, and the <code>Invoke</code> method can also have arguments which you can pass to the view component when you use it.</p>
<h3 id="theview">The View</h3>
<p>The view is really straightforward:</p>
<pre><code>@model IEnumerable&lt;OneManBlog.Model.PostModel&gt;
&lt;div&gt;
    &lt;h3&gt;@ViewBag.Title&lt;/h3&gt;
    &lt;ul&gt;
        @foreach (var item in Model)
            {
            &lt;li&gt;@Html.ActionLink(item.Slug, &quot;Index&quot;, &quot;Post&quot;, new { slug = item.Slug })&lt;/li&gt;
        }
    &lt;/ul&gt;
&lt;/div&gt;
</code></pre>
<p>I want get into any detail what this does, but the hard part is where to put it. To get this to work it must be in the folder <code>Views\Shared\Components\PostList\</code> and the file must be called <code>Default.cshtml</code>. The important part is from <code>Components</code> and down, the first part just scope where it can be used. Since I want this to be used from all over the site I put it in <code>Shared</code>.</p>
<p>With these two files added my solution look like this:</p>
<p><img src="https://storage.ghost.io/c/7c/9f/7c9f0302-e2eb-4fec-95af-b7c64874855a/content/images/2015/05/ViewComponent.PNG" alt="View component solution structure" loading="lazy"></p>
<h3 id="usingtheviewcomponent">Using the view component</h3>
<p>To use this in any view all I have to do is add this line:</p>
<pre><code>@Component.Invoke(&quot;PostList&quot;, &quot;Blog posts&quot;)        
</code></pre>
<p>So my new <code>Home\Index.cshtml</code> container part now looks like this:</p>
<pre><code>&lt;div class=&quot;container&quot;&gt;
    &lt;h1&gt;This is my new blog&lt;/h1&gt;
    Hello from MVC NNUG! asdad sasdasdasd adasd asd sadsa

    @using (Html.BeginForm(&quot;Create&quot;, &quot;Post&quot;, FormMethod.Post))
    {
        &lt;div class=&quot;form-group&quot;&gt;
            &lt;label for=&quot;slug&quot;&gt;Slug&lt;/label&gt;
            &lt;input type=&quot;text&quot; name=&quot;slug&quot; id=&quot;name&quot; value=&quot;&quot; class=&quot;form-control&quot; /&gt;
        &lt;/div&gt;
        &lt;div class=&quot;form-group&quot;&gt;
            &lt;label for=&quot;content&quot;&gt;Content&lt;/label&gt;
            &lt;textarea id=&quot;content&quot; name=&quot;content&quot; class=&quot;form-control&quot;&gt;&lt;/textarea&gt;
        &lt;/div&gt;
        &lt;input type=&quot;submit&quot; value=&quot;Save&quot; class=&quot;btn btn-default&quot; /&gt;
    }
    @Component.Invoke(&quot;PostList&quot;, &quot;Blog posts&quot;)        
&lt;/div&gt;
</code></pre>
<p>and my new <code>Post\Index.cshtml</code> looks like this:</p>
<pre><code>&lt;div class=&quot;container&quot;&gt;
    &lt;h1&gt;@Model.Slug&lt;/h1&gt;
    &lt;div&gt;@Model.Content&lt;/div&gt;
    @Component.Invoke(&quot;PostList&quot;, &quot;Other blog posts&quot;)
&lt;/div&gt;
</code></pre>
<p>That&apos;s all there is to it.</p>
<h2 id="summary">Summary</h2>
<p>This is something I really missed in regular partial views and something that I think will be really useful creating more simple components that is reusable across a site. I look forward to try out this feature in a larger project and so how well it fits in, but so far I think it is really promising.</p>
<!--kg-card-end: markdown-->]]></content:encoded></item></channel></rss>