<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0"
  xmlns:atom="http://www.w3.org/2005/Atom"
  xmlns:content="http://purl.org/rss/1.0/modules/content/">
  <channel>
    <title>Rex Flex</title>
    <link>https://rexflex.net/</link>
    
    <atom:link href="/feed.xml" rel="self" type="application/rss+xml"/>
    
    <description></description>
    <pubDate>Sat, 29 Feb 2020 00:38:28 GMT</pubDate>
    <generator>http://hexo.io/</generator>
    
    <item>
      <title>Scaling Web Applications</title>
      <link>https://rexflex.net/articles/scaling-web-applications/</link>
      <guid>https://rexflex.net/articles/scaling-web-applications/</guid>
      <pubDate>Fri, 28 Feb 2020 00:00:00 GMT</pubDate>
      <description>
      
        &lt;p&gt;When trying to scale applications horizontally that weren’t built with that in mind, you’ll undoubtly be tasked with moving state around so that it can be available to each instance of the application.&lt;/p&gt;
      
      </description>
      
      
      <content:encoded><![CDATA[<p>When trying to scale applications horizontally that weren’t built with that in mind, you’ll undoubtly be tasked with moving state around so that it can be available to each instance of the application.</p><a id="more"></a><p>It doesn’t matter how you’re orchestrating each instance of your application. Whether each instance is hosted on its own virtual machine, inside a container, has its own physical server, or some combination of the above. You’ll still run into the issue of moving state to a centralized place where all instances can access it.</p><p>The application probably already does this for most of its state. For example, most of the application’s data probably lives in some sort of centralized database, like PostgreSQL or MySQL. If this isn’t the case, then that would be step one for scaling the application across multiple instances.</p><p>I believe that any running instance should be able to handle any request. When a client uses a web application, each request from the browser should be able to be handled by different backend servers, and the client application shouldn’t know or care.</p><h2 id="session-data">Session Data</h2><p>How about session data that’s being stored on the server that handled the request, unavailable to other instances? Many technology stacks are configured by default to work this way.</p><p>I prefer updating the session storage of the framework I’m using to store that data in something like redis. The redis server now becomes the central location which instances hit to load the data it needs for that user’s session.</p><h2 id="third-party-libraries">Third Party Libraries</h2><p>Scaling your application also requires knowledge about how the third party libraries your application uses. For example, does your .NET application use NHibernate second-level caching? For ease, it may have been setup to use one of the built in memory caches, such as <code>CoreMemoryCache</code>, <code>RtMemoryCache</code>, <code>SysCache</code>, or <code>SysCache2</code>. If you were previously hosting on a single instance, that’s not a problem. But now that you’re trying to spread the load across multiple instances, you may start seeing really odd caching patterns. The cache might be updated in one instance but not others. Maybe your application begins hitting your database more than expected because each instance starts with a cold cache.</p><p>This is a single example, but you’ll want to be knowledgable about the third party libraries your application uses, what features you’re using, and if that’s going to cause trouble when trying to scale your application.</p><h2 id="sticky-sessions">Sticky Sessions</h2><p>When load balancers say they can do sticky sessions, that means that the load balancer will do its best to ensure that all requests for that user’s session go to the same backend instance. This is often done by injecting a cookie in the first response for that user that the load balancer can then read back on subsequent requests to route the request to the same backend instance that serviced the first request.</p><p>At first glance, this solves the issue of user specific data being on a single instance. Users will be stuck to the instance that has their data, great! But in a way, it kicks the problem down the road and begs new questions.</p><p>What happens when you deploy new code and the instance comes down for updates? What happens if the instance crashes for any reason? You can’t garuntee that an instance will be available for the duration of a user’s session. Because of that, you still have to consider situations where requests for the same user’s session go to different instances.</p><p>I don’t think using sticky sessions is always a bad thing, however it would be a last resort option. There are some advanced situations where you might want to ensure a user gets pinned to a specific instance. You could do this to ensure the instance has a hot cache for user specific, often accessed, difficult to compute data. However, I would only go that route after having ruled out denormalizing that data in the main datastore or caching the data in something like redis where any instance would have access.</p>]]></content:encoded>
      
      <comments>https://rexflex.net/articles/scaling-web-applications/#disqus_thread</comments>
    </item>
    
    <item>
      <title>OpenBSD Machine Setup</title>
      <link>https://rexflex.net/articles/openbsd-machine-setup/</link>
      <guid>https://rexflex.net/articles/openbsd-machine-setup/</guid>
      <pubDate>Wed, 24 Oct 2018 00:00:00 GMT</pubDate>
      <description>
      
        &lt;p&gt;I recently decided to give OpenBSD a shot and wanted to document the process I used to get the system up and running for anyone else that might find this. These steps have been tested to work on OpenBSD 6.4.&lt;/p&gt;
      
      </description>
      
      
      <content:encoded><![CDATA[<p>I recently decided to give OpenBSD a shot and wanted to document the process I used to get the system up and running for anyone else that might find this. These steps have been tested to work on OpenBSD 6.4.</p><a id="more"></a><h3 id="installing-openbsd">Installing OpenBSD</h3><p>My laptop doesn’t have a supported wireless adapter, so I’m unable to download the file sets during the installation process. Because of that, I need to make sure I have the file sets included on the disk image. For my installation, I <a href="https://www.openbsd.org/faq/faq4.html#Download" target="_blank" rel="noopener">downloaded</a> the installXX.fs disk image which includes the file sets. If your wireless adapter is supported and you have internet access during the installation process, you could use minirootXX.fs and download the file sets during installation.</p><p>I created a bootable USB flash drive with <a href="https://rufus.ie/" target="_blank" rel="noopener">Rufus</a>. Then, I booted my laptop up with the flash drive in UEFI mode. When prompted, I opted for the <code>(S)hell</code> insetad of starting the installer so I could prepare the a special EFI system parittion where the UEFI bootloader would be copied after installation.</p><p>I installed to <code>sd0</code> so I ran the following command to initialize the partition table.</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fdisk -i -b 960 sd0</span><br></pre></td></tr></table></figure><p>After this, I ran <code>install</code> to start the installer. When I got to the portion about disk layout, I chose the <code>OpenBSD</code> option.</p><p>After installation, when it prompted to reboot, I went back into the <code>(S)hell</code> and ran the following commands to format the partition and copy the UEFI bootloader.</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;mnt&#x2F;sbin&#x2F;newfs_msdos sd0i</span><br><span class="line">mount &#x2F;dev&#x2F;sd0i &#x2F;mnt2</span><br><span class="line">mkdir -p &#x2F;mnt2&#x2F;efi&#x2F;boot</span><br><span class="line">cp &#x2F;mnt&#x2F;usr&#x2F;mdec&#x2F;BOOTX64.EFI &#x2F;mnt2&#x2F;efi&#x2F;boot</span><br></pre></td></tr></table></figure><p>I then rebooted the machine and everything came up without an issue.</p><h3 id="setting-up-doas">Setting up doas</h3><p>You’ll want to setup <code>doas</code> so you can run commands with root permissions without having to be logged in as root. This will also allow you to skip having to enter a password. <code>doas</code> is OpenBSD’s version of <code>sudo</code>.</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"># echo &#39;permit nopass username&#39; &gt; &#x2F;etc&#x2F;doas.conf</span><br></pre></td></tr></table></figure><h3 id="improving-disk-performance">Improving Disk Performance</h3><p>To increase disk performance, there are a couple of options we can enable in <code>/etc/fstab</code>.</p><p>The <code>noatime</code> option will stop updating the time that files are accessed. This means that reading a file won’t also include a write to update the access time, so it can <a href="https://man.openbsd.org/mount.8#noatime" target="_blank" rel="noopener">reduce disk activity</a>.</p><p>The <code>softdep</code> option makes metadata stop being written immediately and instead will write it “in an ordered fasion to keep the on-disk state of the file system consistent.” It can result in <a href="https://man.openbsd.org/mount.8#softdep" target="_blank" rel="noopener">significant speedups for file create/delete operations</a>. This can only be used with partitions formatted with the Fast File System (FFS).</p><p>To apply these changes, replace any <code>rw</code> in <code>/etc/fstab</code> with <code>rw,softdep,noatime</code>. Make a backup to <code>/etc/fstab.bak</code> incase anything goes wrong, you can go back to the old version without any trouble.</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"># sed -i.bak &#39;s&#x2F;rw&#x2F;rw,softdep,noatime&#x2F;&#39; &#x2F;etc&#x2F;fstab</span><br></pre></td></tr></table></figure><p>Reboot after this to apply the changes when the file systems are mounted again.</p><h3 id="installing-firmware-for-usb-wireless-adapter">Installing firmware for USB Wireless Adapter</h3><p>As I mentioned above, my laptop’s built in wireless adapter (Broadcom BCM4313) isn’t supported at all by OpenBSD. In order to get an internet connection, I bought an Edimax EW-7811Un for $10 off of Amazon which is supported by the <a href="https://man.openbsd.org/urtwn.4" target="_blank" rel="noopener">urtwn firmware</a>. The connection is a bit lackluster, I’m maxing out at around 7Mpbs down and 500Kbps up, however it’s very small and doesn’t have a huge antenna sticking out.</p><p>In order to get the firmware, I had to download it from the <a href="http://firmware.openbsd.org/firmware/" target="_blank" rel="noopener">OpenBSD firmware server</a> and save it to a flash drive on another computer. Once I got the firmware on a flash drive, I popped it in, figured out which parition I had written it to, mounted it, and installed it.</p><p>When you insert your flash drive, the name of the device will show up in xconsole. It will look similar to this:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sd1 at scsibus4 targ 1 lun 0: &lt;Samsung, Flash Drive, 1100&gt;</span><br><span class="line">sd1: 30594MB, 512 bytes&#x2F;sector, 62656641 sectors</span><br></pre></td></tr></table></figure><p>After seeing this, I could tell that my USB flash drive was labeled <code>sd1</code>.</p><p>I then needed to figure out which partition I had written it to. I’ve heard you can assume <code>i</code>, but I like to double check.</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"># disklabel sd1</span><br><span class="line">#        size       offset   fstype</span><br><span class="line">  c:   ######            0   unused</span><br><span class="line">  i:   ######         ####    MSDOS</span><br></pre></td></tr></table></figure><p>From this I could tell that my information was on the <code>i</code> partition, because it’s formatted using MSDOS.</p><p>I then mounted and installed the firmware.</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"># mkdir -p &#x2F;mnt&#x2F;usb</span><br><span class="line"># mount &#x2F;dev&#x2F;sd1i &#x2F;mnt&#x2F;usb</span><br><span class="line"># fw_update -p &#x2F;mnt&#x2F;usb urtwn</span><br></pre></td></tr></table></figure><h3 id="setting-up-the-wireless-connection">Setting up the Wireless Connection</h3><p>OpenBSD 6.4 introduced support to auto-join wireless networks. What this means is that OpenBSD can remember all of the networks you want to connect to along with all of their security settings. It will then decide which network to connect to and automatically switch when that network is no longer available and another is in range.</p><p><a href="https://undeadly.org/cgi?action=article;sid=20180712084645" target="_blank" rel="noopener">According to Peter Hessler</a>, the developer that worked on auto-join:</p><blockquote><p>It basically uses the Apple algorithm that is used on iPhones. As long the signal strength is good enough: Strongest security, then 5GHz, then 11n vs not-n, then pure signal strength.<br>You can also force it to choose a different one with “nwid foo”. The auto-join algorithm will take the saved security settings for “foo” and apply them when it attempts to connect.</p></blockquote><p>We want our network connection to automatically come up when we boot. In order to do this, we’ll need to create a <code>/etc/hostname.if</code> file. You’ll replace the extension <code>if</code> with your wireless interface name. For me, the file is <code>/etc/hostname.urtwn0</code>. When I was first setting up my wireless connection, I thought that <code>hostname</code> needed to be replaced with the actual hostname of my machine. That is NOT the case, my file is literally named <code>/etc/hostname.urtwn0</code>.</p><p>To use auto-join, we’ll use the <code>join</code> option followed by the network id and any necessary <code>wpakey</code> or <code>nwkey</code> arguments.</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">join NETWORKID wpakey PASSWORD</span><br><span class="line">join coffee-shop</span><br><span class="line">join &quot;wepnetwork&quot; nwkey &quot;12345&quot;</span><br><span class="line">dhcp</span><br><span class="line">inet6 autoconf</span><br><span class="line">up</span><br></pre></td></tr></table></figure><p>You can list as many <code>join</code> statements as you’d like and OpenBSD will switch between them as the networks disappear and become available.</p><h3 id="overriding-dns-servers">Overriding DNS Servers</h3><p>The wireless router provided by my ISP doesn’t allow me to set my DNS servers that are broadcast by its DHCP server. Since I don’t want to use my ISP’s DNS servers, I need to tell <code>dhclient</code> not to write the DNS servers it gets when establishing my network connection.</p><p>Create a <code>/etc/dhclient.conf</code> file and enter the following:</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">supersede domain-name-servers 1.1.1.1, 1.0.0.1;</span><br><span class="line">ignore domain-name;</span><br></pre></td></tr></table></figure><p>This will replace the DNS servers that <code>dhclient</code> gets from the network’s DHCP server with the servers you specify, <a href="https://1.1.1.1/" target="_blank" rel="noopener">Cloudflare’s DNS</a> in this case. My ISP also tries to set a search domain, which I’m telling <code>dhclient</code> to ignore.</p><p>You may want to use <code>prepend</code> insetad of <code>supersede</code> for the DNS servers. Doing this would make <code>dhclient</code> prefer the DNS servers you specify, but fall back to the DNS servers it got via DHCP.</p><h3 id="setting-up-the-install-url">Setting up the Install URL</h3><p>Now that we have our internet connection setup, we’re going to want to install system patches and add packages. Before we can do that, though, we’ll want to make sure we have a mirror set in <code>/etc/installurl</code>. This tells the OpenBSD tools where it should attempt to download packages and patches. This is setup by default in 6.4, but if yours is empty for some reason, set it.</p><p>I chose to use the CDN so I don’t have to worry about which mirror is closest. This is also the default in 6.4.</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"># echo &#39;https:&#x2F;&#x2F;cdn.openbsd.org&#x2F;pub&#x2F;OpenBSD&#39; &gt; &#x2F;etc&#x2F;installurl</span><br></pre></td></tr></table></figure><h3 id="installing-system-patches">Installing System Patches</h3><p>To update your system with the latest patches, run <code>syspatch</code>. This will install patches for issues that have been fixed since the release of the version you’re installing. If there are no patches to install, this will do nothing.</p><p>You can check which patches will be installed by looking over the <a href="https://www.openbsd.org/errata64.html" target="_blank" rel="noopener">errata</a>.</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"># syspatch</span><br></pre></td></tr></table></figure><h3 id="install-firmware">Install Firmware</h3><p>We manually downloaded and installed the firmware for our wireless adapter because we didn’t already have an internet connection. Now that we have a connection, we can download the rest of the firmware that our computer might need.</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"># fw_udpate</span><br></pre></td></tr></table></figure><h3 id="configuring-power-management">Configuring Power Management</h3><p>If you’re running on a laptop, you may want to enable the Advanced Power Management daemon or <code>apmd</code>. This will automatically tune your performance to help conserve battery and will also automatically hibernate or suspend your machine if your battery drops below the specified percentage.</p><p>With these commands we’re telling <code>rc</code> to start <code>apmd</code> when the system starts, setting the flags for <code>rc</code> to pass <code>apmd</code> when it starts, and starting it manually.</p><p>The flags we’re telling <code>rc</code> to pass to <code>apmd</code> are:</p><ul><li><code>-A</code> to start in automatic performance adjustment mode</li><li><code>-z 7</code> to automatically suspend the system if the battery is at or below 7% battery, and the system is currently not plugged in.</li></ul><p>Check <code>man apmd</code> for more options.</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"># rcctl enable apmd</span><br><span class="line"># rcctl set apmd flags -A -z 7</span><br><span class="line"># rcctl start apmd</span><br><span class="line">apmd(ok)</span><br></pre></td></tr></table></figure><h3 id="references">References</h3><p>While I was setting up my machine, I found and used several guides. I’ve decided to merge them into a single post for myself, and anyone else that might find this, to reference later.</p><ul><li><a href="https://sivers.org/openbsd" target="_blank" rel="noopener">Derek Sivers</a></li><li><a href="https://blog.jasper.la/openbsd-uefi-bootloader-howto.html" target="_blank" rel="noopener">Jasper Lievisse Adriaanse</a></li><li><a href="https://undeadly.org/cgi?action=article;sid=20180712084645" target="_blank" rel="noopener">OpenBSD Journal</a></li><li><a href="https://www.romanzolotarev.com/openbsd/install.html" target="_blank" rel="noopener">Roman Zolotarev</a></li></ul><p>Also, the OpenBSD man pages are very thorough and accessible. For more information on any of the steps in this post, check out the man pages.</p><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"># man fdisk</span><br><span class="line"># man doas</span><br><span class="line"># man doas.conf</span><br><span class="line"># man fstab</span><br><span class="line"># man mount</span><br><span class="line"># man disklabel</span><br><span class="line"># man fw_update</span><br><span class="line"># man ifconfig</span><br><span class="line"># man hostname.if</span><br><span class="line"># man dhclient.conf</span><br><span class="line"># man syspatch</span><br><span class="line"># man apmd</span><br><span class="line"># man rcctl</span><br></pre></td></tr></table></figure>]]></content:encoded>
      
      <comments>https://rexflex.net/articles/openbsd-machine-setup/#disqus_thread</comments>
    </item>
    
    <item>
      <title>Using ILMerge to hide Dependencies</title>
      <link>https://rexflex.net/articles/using-ilmerge-to-hide-dependencies/</link>
      <guid>https://rexflex.net/articles/using-ilmerge-to-hide-dependencies/</guid>
      <pubDate>Tue, 10 Nov 2015 00:00:00 GMT</pubDate>
      <description>
      
        &lt;p&gt;A few days ago I needed to install a nuget package to get some work done. Unfortunately, it depends on a higher version of Newtonsoft.Json than what we were currently using. I briefly looked into upgrading the version of Newtonsoft.Json across the application, but that ended up looking like more work than the original task I was working on.&lt;/p&gt;
      
      </description>
      
      
      <content:encoded><![CDATA[<p>A few days ago I needed to install a nuget package to get some work done. Unfortunately, it depends on a higher version of Newtonsoft.Json than what we were currently using. I briefly looked into upgrading the version of Newtonsoft.Json across the application, but that ended up looking like more work than the original task I was working on.</p><a id="more"></a><p>After thinking about it a little more, I was asking myself, why I should even have to care that a package I want to take a dependency on is relying on something else? Why should I need to setup assembly bindings to try to redirect dependent assemblies to higher or lower versions based on what the rest of my application is running?</p><p>Then the idea hit me to ditch the nuget package all together. I decided to grab the assembly I wanted to use, and the version of Newtonsoft.Json that it depends on and merge them into one. This allows me to have a single assembly without having to worry about whether or not it’s dependencies are going to play nice with the rest of the application.</p><p>To do this, I put the two assemblies I wanted to merge into a folder, renamed the original assembly to <code>&lt;assembly&gt;.old.dll</code> and ran the following command.</p><pre><code>ILMerge.exe /out:&lt;assembly&gt;.dll /internalize /target:library /targetplatform:v4,C:\Windows\Microsoft.net\Framework64\v4.0.30319 .\&lt;assembly&gt;.old.dll .\Newtonsoft.Json.dll</code></pre><p>Here’s a breakdown of what that command does:</p><ul><li><code>/out:&lt;assembly&gt;.dll</code> outputs the result to <code>&lt;assembly&gt;.dll</code>.</li><li><code>/internalize</code> marks all assemblies that are being merged into the first specified assembly as internal. This is important, as it makes sure we don’t have duplicate namespaces with our other reference to Newtonsoft.Json.</li><li><code>/target:library</code> tells ILMerge that we’re merging assemblies, you can also use <code>/target:exe</code> if you’re merging into an executable.</li><li><code>/targetplatform:v4,C:\Windows\Microsoft.net\Framework64\v4.0.30319</code> lets ILMerge know that the new assembly should target .NET 4.</li><li><code>.\&lt;assembly&gt;.old.dll</code> this is the first assembly that we specify, so it’s going to be the one that’s not marked as internal. This should always be the main dependency that you want access to from your application.</li><li><code>.\Newtonsoft.Json.dll</code> this is the assembly you want to merge in.</li><li><code>.\&lt;another_assembly&gt;.dll</code> You can tack on as many assemblies at the end as you want. It will merge them all into a single dll.</li></ul><p>After the merge was complete, I was able to add a reference to the produced dll. This worked just like the nuget package version, except I didn’t have to worry about the Newtonsoft.Json dependency, at all.</p><p>In the near future, I’m planning on submitting a pull request to the repository of the nuget package that I had issues with. Hopefully if it’s accepted the nuget package will no longer have any dependencies and will be a little easier to work with.</p><p>On the surface, this seems like a great way to deal with dependencies of nuget packages. However, I feel like since it’s not wide-spread and we’re all still dealing with these upgrade issues that there’s a catch I’m not seeing. Let me know on twitter or by email what I’m missing.</p>]]></content:encoded>
      
      <comments>https://rexflex.net/articles/using-ilmerge-to-hide-dependencies/#disqus_thread</comments>
    </item>
    
    <item>
      <title>Scratching the Itch</title>
      <link>https://rexflex.net/articles/scratching-the-itch/</link>
      <guid>https://rexflex.net/articles/scratching-the-itch/</guid>
      <pubDate>Fri, 02 Sep 2011 00:00:00 GMT</pubDate>
      <description>
      
        &lt;p&gt;A couple of weeks ago I found an article by Ryan Day about implementing the &lt;a href=&quot;http://www.ryanday.net/2011/08/21/nasdaq-itch/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Nasdaq ITCH&lt;/a&gt; &lt;a href=&quot;https://github.com/rday/ITCH41&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;protocol in python&lt;/a&gt;. I was really excited about this because I had always thought the barriers to entry for writing a program relating to the stock market would be very high. Turns out writing an application for stock markets is not the barrier, it’s getting the live data needed to be able to make money with it.&lt;/p&gt;
      
      </description>
      
      
      <content:encoded><![CDATA[<p>A couple of weeks ago I found an article by Ryan Day about implementing the <a href="http://www.ryanday.net/2011/08/21/nasdaq-itch/" target="_blank" rel="noopener">Nasdaq ITCH</a> <a href="https://github.com/rday/ITCH41" target="_blank" rel="noopener">protocol in python</a>. I was really excited about this because I had always thought the barriers to entry for writing a program relating to the stock market would be very high. Turns out writing an application for stock markets is not the barrier, it’s getting the live data needed to be able to make money with it.</p><a id="more"></a><p>I wanted to use <a href="http://www.rabbitmq.com/" target="_blank" rel="noopener">RabbitMQ</a> because I’ve been hearing a lot of great things about it. It has a really nice web interface you can use to check on the status of your queues and see how many messages are passing through. Also, since I had used <a href="http://masstransit-project.com/" target="_blank" rel="noopener">MassTransit</a> in the past with MSMQ, and MassTransit now supports RabbitMQ, I figured it’d be a breeze to setup.</p><p>RabbitMQ was very easy to get up and running, along with the plugin for the web interface. It turns out I don’t remember as much as I thought I did about MassTransit, but <a href="http://lostechies.com/josharnold/" target="_blank" rel="noopener">Joshua Arnold</a> was able to help me get setup pretty quick and I had messages flowing through RabbitMQ in what seemed like no time at all.</p><p>The message rate is very slow… I realized that I’m only able to publish about 3,000 messages per second to the message queue. After taking MassTransit out of the mix and publishing directly to RabbitMQ, that number raises to about 10,000 messages per second. If I don’t publish any messages at all and only parse the data from the file, I can parse about 450,000 messages per second. So, RabbitMQ and MassTransit are causing a bottleneck.</p><p>Consuming messages is even slower. I got MassTransit to pull messages off the queue at a top speed of about 1,200 messages per second. Way too slow to keep up with a trading day, where I think I would need to be able to handle at least 20,000 messages per second in order to keep up with bursts of traffic.</p><p>After doing a little digging, I found a <a href="http://mikehadlow.blogspot.com/2011/04/message-queue-shootout.html" target="_blank" rel="noopener">nice comparison</a> of some different queues. It sounds to me like <a href="http://www.zeromq.org/" target="_blank" rel="noopener">ZeroMQ</a> would be a perfect fit for this project. If I have some free time I’m going to give it a shot and see if it performs as well as they say.</p><p>Take a look at the code and let me know what you think: <a href="http://github.com/RexMorgan/Itch" target="_blank" rel="noopener">http://github.com/RexMorgan/Itch</a></p>]]></content:encoded>
      
      <comments>https://rexflex.net/articles/scratching-the-itch/#disqus_thread</comments>
    </item>
    
    <item>
      <title>FubuMVC: Redirect and Transfer</title>
      <link>https://rexflex.net/articles/fubumvc-redirect-and-transfer/</link>
      <guid>https://rexflex.net/articles/fubumvc-redirect-and-transfer/</guid>
      <pubDate>Tue, 19 Jul 2011 00:00:00 GMT</pubDate>
      <description>
      
        &lt;p&gt;Sometimes instead of simply rendering a view from your action, I need to redirect the user to another URL, or call another action.&lt;/p&gt;
&lt;p&gt;In this post I’m going to explain how FubuMVC allows you to perform these actions. In a multi-tenant application I’m working on, I handle all default requests to many domains with a single action in my FubuMVC application. I want to choose which behavior chain to run, depending on the URL that the user has browsed to.&lt;/p&gt;
      
      </description>
      
      
      <content:encoded><![CDATA[<p>Sometimes instead of simply rendering a view from your action, I need to redirect the user to another URL, or call another action.</p><p>In this post I’m going to explain how FubuMVC allows you to perform these actions. In a multi-tenant application I’m working on, I handle all default requests to many domains with a single action in my FubuMVC application. I want to choose which behavior chain to run, depending on the URL that the user has browsed to.</p><a id="more"></a><p>An example of this, just to make sure I’m explaining this properly, is Tumblr. Browsing to <a href="http://tumblr.com" target="_blank" rel="noopener">tumblr.com</a> should display the home page for Tumblr (sign up form, information about why Tumblr is great, etc). However, browsing to {username}.tumblr.com should display the posts by that particular user. <em>(I honestly don’t know if this is handled by a single piece of code on Tumblr, but I’d like to mimic this, with a single piece of code, in my project.)</em></p><p>To start, I’m going to create a FrontLoaderEnpoint that all default requests will go through.</p><p>In my FrontLoaderEndpoint, I need to check what URL the user is coming from. In order to do this, I have a property called <a href="http://groups.google.com/group/fubumvc-devel/msg/9c1091e92ed53b7c" target="_blank" rel="noopener">HTTP_HOST on my input model</a>. FubuMVC will automatically fill in the information from the <a href="http://msdn.microsoft.com/en-us/library/system.web.httprequest.servervariables.aspx" target="_blank" rel="noopener">ServerVariables collection</a>._ (I hate to just leave it as this “just works”, but model binding will be the topic of another blog post.)_</p><p>Now I’m taking the HTTP_HOST from the input model and attempting to look up the user that the domain belongs to.</p><p>If there is a user that is using the domain, then I’m going to go ahead and transfer the request to the endpoint that handles the user specific domains. I tell FubuMVC that I want to transfer the user by returning FubuContinuation.TransferTo. The TransferTo method takes in the input model of the action that you want to call.</p><p>If there’s not a user found for the domain, I’m going to redirect the user to the home page (which allows new users to sign up, etc). To redirect the user I return FubuContinuation.RedirectTo and, just like the TransferTo method, pass in the input model of the action I want to redirect the user to.</p><pre><code>public class FrontLoaderRequestModel{    public string HTTP_HOST { get; set; }}public class FrontLoaderEndpoint{    private readonly IUserRepository _userRepository;        public FrontLoaderEndpoint(IUserRepository userRepository)    {        _userRepository = userRepository;    }    public FubuContinuation Get(FrontLoaderRequestModel input)    {        var user = _userRepository.GetByDomain(input.HTTP_HOST);                if(user != null)        {            return FubuContinuation.TransferTo(new UserSpecificIndexRequestModel                                                    {                                                        User = user                                                    });        }        return FubuContinuation.RedirectTo(new HomeRequestModel());    }}</code></pre><h4 id="how-does-it-work-span-span">How does it work?<span> </span></h4><p>The way this works is RedirectTo and TransferTo are both static methods on the FubuContinuation class, which return a FubuContinuation object. In the constructor of the FubuContinuation object, it takes in the ContinuationType (Redirect, Transfer, or NextBehavior) and an action that should be called on the IContinuationDirector.</p><p>The IContinuationDirector is what actually does all of the work, by calling RedirectToUrl on the IOutputWriter if you’re doing a redirect <em>(just like I did in Step 2 of <a href="https://rexflex.net/articles/fubumvc-authentication/">FubuMVC: Authentication</a>.)</em>, or building a partial from the IPartialFactory and invoking it, if you’re doing a transfer. The action to call is resolved using the input model that you provided when you called FubuContinuation.RedirectTo / FubuContinuation.TransferTo. Since we’re using the <a href="https://rexflex.net/articles/fubumvc-one-model-in-one-model-out/">thunderdome pattern</a>, each of our actions are uniquely defined by the type of the input model.</p><p>Internally, FubuMVC has a built-in convention which gets run. This convention checks for any actions that have a FubuContinuation as an output type. If it finds one, it adds an internal behavior called ContinuationHandler directly after the action call.</p><p>When the ContinuationHandler gets called, it pulls the FubuContinuation that was set in my action call from the IFubuRequest and calls Process on it, passing into it, “this” <em>(the ContinuationHandler being called.)</em> The Process method calls the action that was passed into the FubuContinuation constructor and passes int he ContinuationHandler that’s being run. <em>(Note: ContinuationHandler implements IContinuationDirector.)</em></p><h4 id="bonus">Bonus!</h4><p>If you want to redirect the user to a URL of an outside site, just pass the URL directly into FubuContinuation.RedirectTo. The ContinuationHandler has a mechanism in place to redirect directly to a URL if it’s provided as a string.</p>]]></content:encoded>
      
      <comments>https://rexflex.net/articles/fubumvc-redirect-and-transfer/#disqus_thread</comments>
    </item>
    
    <item>
      <title>FubuMVC: One Model In, One Model Out</title>
      <link>https://rexflex.net/articles/fubumvc-one-model-in-one-model-out/</link>
      <guid>https://rexflex.net/articles/fubumvc-one-model-in-one-model-out/</guid>
      <pubDate>Thu, 14 Jul 2011 00:00:00 GMT</pubDate>
      <description>
      
        &lt;p&gt;A pattern that’s regularly used with FubuMVC is the one model in, one model out pattern. This is also known as OMIOMO and, my personal favorite, the &lt;a href=&quot;http://codebetter.com/jeremymiller/2008/10/23/our-opinions-on-the-asp-net-mvc-introducing-the-thunderdome-principle/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;“thunderdome”&lt;/a&gt; pattern. It took me a little while to understand why this pattern is in place and seems to be a gotcha when I come back to FubuMVC after an extended period of time. I’m going to write about why I use this pattern, to document it for both others, and my future self.&lt;/p&gt;
      
      </description>
      
      
      <content:encoded><![CDATA[<p>A pattern that’s regularly used with FubuMVC is the one model in, one model out pattern. This is also known as OMIOMO and, my personal favorite, the <a href="http://codebetter.com/jeremymiller/2008/10/23/our-opinions-on-the-asp-net-mvc-introducing-the-thunderdome-principle/" target="_blank" rel="noopener">“thunderdome”</a> pattern. It took me a little while to understand why this pattern is in place and seems to be a gotcha when I come back to FubuMVC after an extended period of time. I’m going to write about why I use this pattern, to document it for both others, and my future self.</p><a id="more"></a><h4 id="origins">Origins</h4><p>From the articles I can find online, the thunderdome pattern was created as a way to increase testability of your actions. By only allowing a single model in, it’s very easy to setup the context of the test. It also removes the need to rely on the <a href="http://msdn.microsoft.com/en-us/library/system.web.httpcontext.aspx" target="_blank" rel="noopener">HttpContext</a> inside the actions. In FubuMVC, if information is needed from the HttpContext, a property can be added to the input model and it’s the responsibility of model binding to set that property to the corresponding value in the HttpContext._ (Model Binding will be the topic of another post.)_</p><h4 id="benefits">Benefits</h4><p>Once you decide to use the thunderdome pattern, it’s not a big step to make each of the actions take a unique input model. If each behavior chain has a unique input model, then each behavior chain can be identified by its input type. This is a great way, in my opinion, to take advantage of static typing and make it work for you.</p><p>In FubuMVC, this is the most common way to identify behavior chains. Since each behavior chain is associated to a route, it’s the most common way to build URLs, also.</p><h4 id="other-patterns">Other Patterns</h4><p>It’s important to note that the thunderdome pattern is not the only way to use FubuMVC. All of the combinations of One/Zero model in One/Zero model out patterns are supported. I can see using a one model in, zero model out for use of services where you only care about the HTTP Response code. <em>(If you want to do this with the thunderdome pattern, you can just return an <a href="http://msdn.microsoft.com/en-us/library/system.net.httpstatuscode.aspx" target="_blank" rel="noopener">HttpStatusCode</a> from your action. There’s a <a href="https://github.com/DarthFubuMVC/fubumvc/blob/master/src/FubuMVC.Core/Behaviors/RenderStatusCodeBehavior.cs" target="_blank" rel="noopener">built</a> in <a href="https://github.com/DarthFubuMVC/fubumvc/blob/master/src/FubuMVC.Core/FubuRegistry.DefaultConventions.cs#L41" target="_blank" rel="noopener">convention</a> in FubuMVC to handle this return type.)</em></p><p>I don’t use either of the patterns which do not have an input model. If I have an action that doesn’t have any input, then I typically have it accept an empty “marker” input model, anyway. This gives me the ability to uniquely identify it if I ever need to create a link to it, or for any other reason.</p>]]></content:encoded>
      
      <comments>https://rexflex.net/articles/fubumvc-one-model-in-one-model-out/#disqus_thread</comments>
    </item>
    
    <item>
      <title>FubuMVC: Authorization</title>
      <link>https://rexflex.net/articles/fubumvc-authorization/</link>
      <guid>https://rexflex.net/articles/fubumvc-authorization/</guid>
      <pubDate>Sat, 09 Jul 2011 00:00:00 GMT</pubDate>
      <description>
      
        &lt;p&gt;When it comes to authorization, FubuMVC is very powerful in letting you setup extremely customizable rules for deciding who has access to what. Luckily, &lt;a href=&quot;http://lostechies.com/josharnold/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Joshua Arnold&lt;/a&gt; was able to help me get these rules setup and I’d like to document the process for everyone else.&lt;/p&gt;
&lt;p&gt;In this post, I’ll be going over how to write a custom authorization rule to keep users from being able to edit another user’s blog post in a simple blogging application. I’ll do this by plugging into the authorization facilities built into FubuMVC.&lt;/p&gt;
      
      </description>
      
      
      <content:encoded><![CDATA[<p>When it comes to authorization, FubuMVC is very powerful in letting you setup extremely customizable rules for deciding who has access to what. Luckily, <a href="http://lostechies.com/josharnold/" target="_blank" rel="noopener">Joshua Arnold</a> was able to help me get these rules setup and I’d like to document the process for everyone else.</p><p>In this post, I’ll be going over how to write a custom authorization rule to keep users from being able to edit another user’s blog post in a simple blogging application. I’ll do this by plugging into the authorization facilities built into FubuMVC.</p><a id="more"></a><h4 id="overview">Overview</h4><ol><li>Come up with a convention to identify which action calls need authorization, and how to access the information we need from the input models</li><li>Do the heavy lifting by writing an authorization policy to check and see if the user is authorized to do what they’re trying to do</li><li>Teach FubuMVC about the convention</li><li>Tell FubuMVC to use the convention</li></ol><h4 id="step-1-come-up-with-a-convention">Step 1: Come up with a convention</h4><p>In order to figure out which routes/action calls need authorization, I’m going to implement an interface on my input models. This will not only mark them so I can look them up later, but also provide me with a generic way of accessing the properties that I’m going to be running my authorization code against. In this case, all I need from the models are the post id, so that’s all that’s required on the interface. It’s also worth noting here that I have two input models. I use EditPostRequestModel for the http get action call (to get the post in order to display it for the user to edit), and the EditPostInputModel for the http post action call (which handles the saving of the post after it’s been edited by the user.)</p><pre><code>public interface IPostModel{    int PostId { get; }}public class EditPostInputModel : IPostModel{    public int PostId { get; set; }    public string Title { get; set; }    public string Body { get; set; }    public string Slug { get; set; }}public class EditPostRequestModel : IPostModel{    public int PostId { get; set; }    public string Title { get; set; }    public string Body { get; set; }    public string Slug { get; set; }}</code></pre><h4 id="step-2-do-the-heavy-lifting">Step 2: Do the heavy lifting</h4><p>Now that I’ve marked which actions need authorization, I’m going to write an authorization policy so I can specify how that authorization needs to be done. In this case I want to verify that the post being requested belongs to the user that is requesting it. This is a simple example, but you can do any sort of complex checking here that you wanted (e.g. If it were possible that your users could be editors and edit other user’s posts, that check would go here.)</p><p>For my simple case, we can just check that the user property on the requested post, is the same user as the user that’s currently logged in. The CurrentUser dependency is what I use to get the currently logged in user. Use whatever your convention is to do that here, instead.</p><pre><code>public class PostAuthorizationPolicy&lt;TModel&gt; : IAuthorizationPolicy    where TModel : class, IPostModel{    private readonly IPostRepository _postRepository;    private readonly CurrentUser _currentUser;    public PostAuthorizationPolicy(IPostRepository postRepository, CurrentUser currentUser)    {        _postRepository = postRepository;        _currentUser = currentUser;    }    public AuthorizationRight RightsFor(IFubuRequest request)    {        var model = request.Get&lt;TModel&gt;();        if (model == null)        {            return AuthorizationRight.Deny;        }        var post = _postRepository.GetById(model.PostId);        if (post == null)        {            return AuthorizationRight.Deny;        }        return post.User.Id == _currentUser.UserId                    ? AuthorizationRight.Allow                    : AuthorizationRight.Deny;    }}</code></pre><h4 id="step-3-teach-fubumvc-about-the-convention">Step 3: Teach FubuMVC about the convention</h4><p>So, I have my action calls setup that need authorization, and I’ve created a way to do that authorization, the next step is to tie the two together and tell FubuMVC how to apply my authorization policy.</p><p>FubuMVC has a DSL to do this, which can be accessed through the Authorization property on the behavior chain. The way this works is inside FubuMVC, <strong>after</strong> it has applied all of your conventions, it will check to see if there have been any policies added to the Authorization property on the behavior chain. If it finds that there has been, it will wrap the chain with an internal behavior called AuthorizationBehavior.</p><p>The way the AuthorizationBehavior works is by calling the authorization policies for the behavior and checking the return value of them. If <em>any</em> of the policies return AuthorizationRight.Deny, then the chain is stopped and IAuthorizationFailureHandler is called on to handle the erred request.</p><p>It’s very important that FubuMVC sets this convention up <strong>after</strong> it sets up all of the custom conventions. This ensures that the AuthenticationBehavior gets run before anything else in the behavior chain.</p><p>What I want to do is add a policy to the Authorization property for all action calls which have an input type that implements my IPostModel interface.</p><p>Since I made the policy an open generic, I’ll close that generic with the type that the action call is using. This is what allows the authorization policy to get the model out of the IFubuRequest (since things are keyed by type), which means I can check values specific to that particular request.</p><pre><code>public class PostAuthorizationConvention : IConfigurationAction{    public void Configure(BehaviorGraph graph)    {        graph            .Behaviors            .Where(c =&gt; typeof (IPostModel).IsAssignableFrom(c.InputType()))            .Each(chain =&gt; chain                                .Authorization                                .AddPolicy(typeof (PostAuthorizationPolicy&lt;&gt;).MakeGenericType(chain.InputType())));    }}</code></pre><h4 id="step-4-tell-fubumvc-to-use-the-convention">Step 4: Tell FubuMVC to use the convention</h4><p>Now that everything is all setup and I’ve defined how my convention works, I just have to tell FubuMVC to use the convention. To do this, in my FubuRegistry, I just add the following line.</p><pre><code>Policies.Add&lt;PostAuthorizationConvention&gt;();</code></pre><p>Now when I start up the application and browse to /post/edit/:id, I get a 403 forbidden message if the id is for a post that isn’t mine. If the post is mine, I’m allowed to pass right through to the rest of the chain.</p><h4 id="bonus">Bonus!</h4><p><em>What if I don’t want to return a 403 forbidden message? I want to do something unique and special!</em></p><p>Remember when I said that the AuthorizationBehavior will call on IAuthorizationFailureHandler if any of the policies go wrong in order to handle the authorization error? Well, all you have to do is implement your own IAuthorizationFailureHandler and tell FubuMVC to replace the default implementation with your custom one, in your FubuRegistry.</p><pre><code>public class CustomAuthorizationFailureHandler : IAuthorizationFailureHandler{    private readonly IOutputWriter _writer;    private readonly IUrlRegistry _urlRegistry;    public CustomAuthorizationFailureHandler(IOutputWriter writer, IUrlRegistry urlRegistry)    {        _writer = writer;        _urlRegistry = urlRegistry;    }    public void Handle()    {        // Get the url to the login page, and redirect the user there!        var url = _urlRegistry.UrlFor(new LoginRequestModel());        _writer.RedirectToUrl(url);    }}// In the registryServices(x =&gt; { x.ReplaceService&lt;IAuthorizationFailureHandler, CustomAuthorizationFailureHandler&gt;(); });</code></pre><p>Now when I attempt to browse to /post/edit/:id, if I don’t own the post, I get redirected to the login screen.</p>]]></content:encoded>
      
      <comments>https://rexflex.net/articles/fubumvc-authorization/#disqus_thread</comments>
    </item>
    
    <item>
      <title>FubuMVC: Authentication</title>
      <link>https://rexflex.net/articles/fubumvc-authentication/</link>
      <guid>https://rexflex.net/articles/fubumvc-authentication/</guid>
      <pubDate>Fri, 08 Jul 2011 00:00:00 GMT</pubDate>
      <description>
      
        &lt;p&gt;If you’re using FubuMVC and your site requires users to login, you’ll probably want to use the built in authentication facilities that FubuMVC provides. In this post, I’ll attempt to explain how this works.&lt;/p&gt;
&lt;p&gt;I’m going to write an authentication convention to block access to certain actions from unauthenticated users.&lt;/p&gt;
      
      </description>
      
      
      <content:encoded><![CDATA[<p>If you’re using FubuMVC and your site requires users to login, you’ll probably want to use the built in authentication facilities that FubuMVC provides. In this post, I’ll attempt to explain how this works.</p><p>I’m going to write an authentication convention to block access to certain actions from unauthenticated users.</p><a id="more"></a><h4 id="overview">Overview</h4><ol><li>Come up with a convention to determine which action calls require the user to be authenticated</li><li>Write a behavior to redirect a user if they’re not authenticated</li><li>Teach FubuMVC about the convention</li><li>Tell FubuMVC to use the convention</li><li>Let FubuMVC know when someone has logged in or out</li></ol><h4 id="step-1-come-up-with-a-convention">Step 1: Come up with a convention</h4><p>For this example, my convention is going to be any action call marked with a [Secured] attribute, will require an authenticated user in order to execute. As you’ll see, this can be adapted to match whatever convention you want to use.</p><p>To start, I’ll just create a simple marker attribute and throw it on the action calls that I want to be secured.</p><pre><code>public class SecuredAttribute : Attribute{}public class DashboardEndpoint{    [Secured]    public DashboardRequestModel Get(DashboardRequestModel input)    {        return new DashboardRequestModel();    }}</code></pre><p>Since we’ve marked the action calls that we want to secure, we’ll be able to pick them out later when we want to teach FubuMVC about our convention.</p><h4 id="step-2-write-a-behavior">Step 2: Write a behavior</h4><p>In order to do the actual work of checking to see if the user is logged in, and redirecting them if they’re not, I’ll need to create a behavior. If you’re unfamiliar with behaviors, I’d highly recommend reading <a href="http://lostechies.com/chadmyers/2011/06/23/cool-stuff-in-fubumvc-no-1-behaviors/" target="_blank" rel="noopener">these articles</a> <a href="http://guides.fubumvc.com/advanced_behaviors.html" target="_blank" rel="noopener">about</a> <a href="http://murrayon.net/2011/06/fubumvc-behavior-chains-bmvc-pattern.html" target="_blank" rel="noopener">them</a>.</p><p>The behavior will depend on the ISecurityContext provided by FubuMVC, so I can check if the user has been authenticated. If the user has not been authenticated, I’ll just redirect them to the login page.</p><p>It’s important to note that, by default, the ISecurityContext is a wrapper around the current HttpContext. This means that FubuMVC is really just using standard <a href="http://ASP.NET" target="_blank" rel="noopener">ASP.NET</a> forms authentication.</p><p>When FubuMVC calls the behavior, it will look at the result coming from the performInvoke() method. If the method returns DoNext.Continue, then the next behavior in the chain will be called. However, if it returns DoNext.Stop, then it will not call the next behavior in the chain and execution of the request stops. <em>(It actually doesn’t just stop, if you’ve been through any behaviors that wrap the authentication behavior, you will begin to start calling the afterInsideBehavior method on these.</em></p><pre><code>public class AuthenticationRequiredBehavior : BasicBehavior{    private readonly ISecurityContext _securityContext;    private readonly IUrlRegistry _urlRegistry;    private readonly IOutputWriter _outputWriter;    public AuthenticationRequiredBehavior(ISecurityContext securityContext, IUrlRegistry urlRegistry, IOutputWriter outputWriter)        : base(PartialBehavior.Ignored)    {        _securityContext = securityContext;        _urlRegistry = urlRegistry;        _outputWriter = outputWriter;    }    protected override DoNext performInvoke()    {        if(_securityContext.IsAuthenticated())        {            return DoNext.Continue;        }        var url = _urlRegistry.UrlFor(new LoginRequestModel());        _outputWriter.RedirectToUrl(url);        return DoNext.Stop;    }}</code></pre><h4 id="step-3-teach-fubumvc-about-the-convention">Step 3: Teach FubuMVC about the convention</h4><p>So I’ve setup our action calls to use the convention and the behavior to kick unauthorized people out. Now I just need to teach FubuMVC what that convention is, and how it should be implemented. In order to do that, I’ll need to create an implementation of the IConfigurationAction interface <em>(these are typically called conventions.)</em> My convention will modify the graph and wrap all action calls that have the Secured attribute with our behavior.</p><p>In the convention, I have access to all of the Actions that FubuMVC knows about. I’m able to filter those actions to only get those which implement the SecuredAttribute, and then wrap those with the behavior I just created.</p><pre><code>public class AuthenticationConvention : IConfigurationAction{    public void Configure(BehaviorGraph graph)    {        graph            .Actions()            .Where(c =&gt; c.HasAttribute&lt;SecuredAttribute&gt;())            .Each(c =&gt; c.WrapWith&lt;AuthenticationRequiredBehavior&gt;());    }}</code></pre><p>This is where I could change it up and use another convention if I wanted to. Instead of filtering the actions based on attributes, I can check for anything. If I wanted to filter for all actions with an input type that starts with “Add” or “Edit”, that’s possible by using this convention.</p><pre><code>graph    .Actions()    .Where(c =&gt; c.HasInput &amp;&amp; c.InputType().Name.StartsWith(&quot;Add&quot;) || c.InputType().Name.StartsWith(&quot;Edit&quot;))    .Each(c =&gt; c.WrapWith&lt;AuthenticationRequiredBehavior&gt;());</code></pre><h4 id="step-4-tell-fubumvc-to-use-the-convention">Step 4: Tell FubuMVC to use the convention</h4><p>In order to tell FubuMVC to apply the convention, I need to call this method from the FubuRegistry.</p><pre><code>ApplyConvention&lt;AuthenticationConvention&gt;();</code></pre><p>Now, if I run my project and attempt to browse to an action that has been locked down, I get redirected to the login page, which is exactly what I wanted it to do.</p><h4 id="step-5-let-fubumvc-know-when-someone-has-logged-in-or-out">Step 5: Let FubuMVC know when someone has logged in or out</h4><p>In order to tell FubuMVC that a user has been logged in, I need to depend on IAuthenticationContext in the action that logs users in. Once I’ve verified the user’s credentials are correct, I can call the ThisUserHasBeenAuthenticated method on IAuthenticationContext to let FubuMVC know.</p><p>When I want to log a user out, call SignOut on the IAuthenticationContext interface.</p><h4 id="gotcha">Gotcha!</h4><p>As I stated earlier, the default authentication in FubuMVC is really just a wrapper for forms authentication in <a href="http://ASP.NET" target="_blank" rel="noopener">ASP.NET</a>. So, in order to use the ISecurityContext, you’ll need to turn on forms authentication in your web.config, otherwise the ISecurityContext will always say that the user is authenticated.</p><pre><code>&lt;system.web&gt;    &lt;authentication mode=&quot;Forms&quot;&gt;        &lt;forms loginUrl=&quot;~/login&quot; timeout=&quot;25&quot; slidingExpiration=&quot;true&quot; /&gt;    &lt;/authentication&gt;&lt;/system.web&gt;</code></pre>]]></content:encoded>
      
      <comments>https://rexflex.net/articles/fubumvc-authentication/#disqus_thread</comments>
    </item>
    
    <item>
      <title>Possible Shortcomings of Groupon</title>
      <link>https://rexflex.net/articles/possible-shortcomings-of-groupon/</link>
      <guid>https://rexflex.net/articles/possible-shortcomings-of-groupon/</guid>
      <pubDate>Wed, 04 May 2011 00:00:00 GMT</pubDate>
      <description>
      
        &lt;p&gt;The other day I was reading an article titled &lt;a href=&quot;http://thecxrx.wordpress.com/2011/03/28/grouponed-to-death/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Grouponed to death?&lt;/a&gt; at The CX Rx. It hit a lot of points that I’ve always thought about these deal sites like Groupon, Living Social, and the 100’s of other clones that have been popping up.&lt;/p&gt;
      
      </description>
      
      
      <content:encoded><![CDATA[<p>The other day I was reading an article titled <a href="http://thecxrx.wordpress.com/2011/03/28/grouponed-to-death/" target="_blank" rel="noopener">Grouponed to death?</a> at The CX Rx. It hit a lot of points that I’ve always thought about these deal sites like Groupon, Living Social, and the 100’s of other clones that have been popping up.</p><a id="more"></a><p><em>To put the rest of the article into context, it’s important to know that Groupon works by selling coupons for a business’s service. The business agrees to give a discount of at least 50% and also agrees to give Groupon 50% of the revenue they take in from the coupons. This means that the business gets 25% of the list price for their product or service. At least, that’s how I understand it.</em></p><p>I’m not a business owner, but it’s hard for me to rationalize why any business would give up 50% of their, already cut in half revenue, providing their product or service for 25¢ on the dollar of their normal prices.</p><p>It’s hard to believe that you would actually turn over loyal customers and instead it seems like you’d get plenty of people coming to get a good deal, then never coming back. As <a href="http://themarketingspot.com/2010/12/email-coupons-way-kill-your-business.html" target="_blank" rel="noopener">Jay Ehret</a> puts it:</p><blockquote><p>The thought process goes like this: I get a new customer by giving them a discount: 50% off. They will appreciate the discount, see how great we are, and become a new customer. But that’s not how the customer thinks. They get their coupon, buy your stuff, and they like it. Then you ask them to buy again, but now you’ve doubled the price!<br>At the same time, you’re alienating your current customers by giving deep discounts to new customers, and offering nothing to the loyal customers that have been keeping you in business up until then.</p></blockquote><p>I’m sure this isn’t a new idea, but I would like to see tools that allow your current customers to tap into their own social network. Reward both the current customer and the new customers they’re able to bring to your business. Provide coupons to both. If you’re not giving a middle-man 50% of the reduced profits, you might even be able to offer discounts comparable to Groupon, without going out of business.</p>]]></content:encoded>
      
      <comments>https://rexflex.net/articles/possible-shortcomings-of-groupon/#disqus_thread</comments>
    </item>
    
    <item>
      <title>FubuMVC: Partial Views</title>
      <link>https://rexflex.net/articles/fubumvc-partial-views/</link>
      <guid>https://rexflex.net/articles/fubumvc-partial-views/</guid>
      <pubDate>Thu, 04 Nov 2010 00:00:00 GMT</pubDate>
      <description>
      
        &lt;p&gt;Today I was working on getting a partial view working properly in FubuMVC and started trying stumbling through it, very unsuccessfully. I ended up reaching out to &lt;a href=&quot;http://twitter.com/jmarnold&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Joshua Arnold&lt;/a&gt; for help with it. I’d like to share it with everyone that might be having trouble with them.&lt;/p&gt;
      
      </description>
      
      
      <content:encoded><![CDATA[<p>Today I was working on getting a partial view working properly in FubuMVC and started trying stumbling through it, very unsuccessfully. I ended up reaching out to <a href="http://twitter.com/jmarnold" target="_blank" rel="noopener">Joshua Arnold</a> for help with it. I’d like to share it with everyone that might be having trouble with them.</p><a id="more"></a><p>The way we’re going to be doing our partials is by having the concept of an action extension which can be called by our partial action. It’s a little difficult to explain, so let’s get right into the code. I’ll be <em>emphasizing</em> all of the gotchas that I ran into, to hopefully help explain things a little better.</p><p><em>With all of the generics, things can get a little confusing. The generic parameter in all of these classes is going to be the model that you’re working with. What we’re really building here is a very maintainable “model modifier”.</em></p><p>To start off, let’s create our partial action. We’ll be using a generic action that we’re calling PartialAction. <em>It is important to note that this is the action that’s going to get called when you call your partials. Since it’s generic, we’re going be calling it for <strong>all</strong> of our partial views.</em></p><pre><code>public class PartialAction&lt;T&gt;    where T : class{    private readonly IPartialActionExtensionGraph&lt;T&gt; _graph;    public PartialAction(IPartialActionExtensionGraph&lt;T&gt; graph)    {        _graph = graph;    }    public T Execute(T input)    {        return _graph.Modify(input);    }}</code></pre><p>As you can see, we have a dependency on and IPartialActionExtensionGraph. That’s a simple interface that has a single method, Modify. Since we’re going to be calling Modify on our Graph the same way as we call Modify on a single action extension, they share a common interface.</p><pre><code>public interface IPartialActionExtensionGraph&lt;T&gt; : IPartialActionExtension&lt;T&gt;     where T : class{}public interface IPartialActionExtension&lt;T&gt;    where T : class{    T Modify(T model);}</code></pre><p>Now we’re going to create a generic implementation for the action extension graph. We’ll want to call the Modify method on all of the action extensions that close the interface with the same type. We’re going to use our IoC container to keep track of all our implementations, in this case we’re using StructureMap, but you could probably use this with any dependency injection tool.</p><pre><code>public class PartialActionExtensionGraph&lt;T&gt; : IPartialActionExtensionGraph&lt;T&gt;    where T : class{    private readonly IContainer _container;    public PartialActionExtensionGraph(IContainer container)    {        _container = container;    }    public T Modify(T model)    {        _container.GetAllInstances&lt;IPartialActionExtension&lt;T&gt;&gt;()            .Each(extension =&gt; model = extension.Modify(model));        return model;    }}</code></pre><p>To load up StructureMap with all our action extensions, we’ll want to use this registry &amp; registry convention while we bootstrap StructureMap. This awesome piece of code is from Josh, so please go thank him. It will search through our entire assembly and find any types that close the interface IPartialActionExtension&lt;&gt;, that is not an interface, and is not abstract. <em>Please note that the Closes and FindInterfaceThatCloses extension methods are part of FubuCore.</em></p><pre><code>public class PartialActionExtensionsRegistry : Registry{    public PartialActionExtensionsRegistry()    {        Scan(x =&gt;        {            x.TheCallingAssembly();            x.Include(type =&gt; type.Closes(typeof(IPartialActionExtension&lt;&gt;)));            x.Exclude(type =&gt; type.IsInterface);            x.Exclude(type =&gt; type.IsAbstract);            x.With(new PartialActionExtensionsConvention());        });    }}public class PartialActionExtensionsConvention : IRegistrationConvention{    public void Process(Type type, Registry registry)    {        var extensionType = type.FindInterfaceThatCloses(typeof(IPartialActionExtension&lt;&gt;));        if(extensionType == null)        {            return;        }        registry            .For(extensionType)            .Add(type);    }}</code></pre><p>Now that our action is setup, we’ll build our model. Until this point, we’ve been dealing with the plumbing to get the partial views to work. So I’ll explain what we’re about to write. On our master page, we want to see either a “Login” link if the user has not logged in, yet or a “Logout” link if the user is already logged in. Pretty simple. <em>As you can see from the PartialAction class, our input and output model will be the same. So we just need to write the model that will be used by the view.</em></p><pre><code>[PartialModel]public class MasterLoginLogoutModel{    public bool IsAuthenticated { get; set; }}</code></pre><p>Note the PartialModel attribute. This is very important, because this is what we’ll use to tell FubuMVC to link it up to the PartialAction class.</p><p>In order for FubuMVC to know what to do, we’ll need to setup our behavior chains for the input model that we just built. This is where things get a little more complicated, but we’ll go through it step-by-step. We need to create action calls for each of our models, so let’s create an action source.</p><p>Our action source will be fairly simple. We’ll find all our classes that are marked with the PartialModel attribute, close the PartialAction&lt;&gt; action with this type, and create an action call for it. <em>Please note that the GetExecuteMethod method is a Type extension method which just returns a MethodInfo instance of the method to call. In this case it will be the Execute method.</em></p><pre><code>public class PartialActionsSource: IActionSource{    public IEnumerable&lt;ActionCall&gt; FindActions(TypePool types)    {        return types            .TypesMatching(t =&gt; t.HasAttribute&lt;PartialModelAttribute&gt;())            .Select(m =&gt;                        {                            var actionType = typeof(PartialAction&lt;&gt;).MakeGenericType(m);                            return new ActionCall(actionType, actionType.GetExecuteMethod());                        });    }}</code></pre><p>We’ll create the view real quick, nothing too fancy about it.</p><pre><code>&lt;%@ Page Language=&quot;C#&quot; CodeBehind=&quot;MasterLoginLogout.aspx.cs&quot; Inherits=&quot;Project.Web.Shared.Partials.Views.MasterLoginLogout&quot; %&gt;&lt;%@ Import Namespace=&quot;Project.Web.Models.Users&quot; %&gt;&lt;% if (Model.IsAuthenticated) {%>        <a href="<%=Urls.UrlFor(new UserLogoutGetModel())%>">Logout</a>    <% } else { %>        <a href="<%= Urls.UrlFor(new UserLoginGetModel()) %>">Login</a>    <%} %&gt;public class MasterLoginLogout : FubuPage&lt;MasterLoginLogoutModel&gt;{}</code></pre><p>Now, we can call the partial view from our master page very easily. It will look something like this.</p><pre><code>&lt;%@ Master Language=&quot;C#&quot; AutoEventWireup=&quot;true&quot; CodeBehind=&quot;Site.master.cs&quot; Inherits=&quot;Project.Web.Shared.Master.Site&quot; %&gt;&lt;%@ Import Namespace=&quot;FubuCore&quot; %&gt;&lt;%@ Import Namespace=&quot;Project.Web.Shared.Partials.Models&quot; %&gt;&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD XHTML 1.0 Transitional//EN&quot; &quot;http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd&quot;&gt;&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;    &lt;head&gt;        &lt;title&gt;Project Master Page&lt;/title&gt;    &lt;/head&gt;    &lt;body&gt;        &lt;% this.Partial&lt;MasterLoginLogoutModel&gt;(); %&gt;    &lt;/body&gt;&lt;/html&gt;public class Site : FubuMasterPage{}</code></pre><p>When we call our page, we’ll see that it almost works. It’s just that it will always say “Login” because we never set the IsAuthenticated property on our model. To do this, we just want to create an action extension (remember that base interface we made way up there?).</p><pre><code>public class MasterLoginLogoutPartialActionExtension : IPartialActionExtension&lt;MasterLoginLogoutModel&gt;{    private readonly IAuthenticationManager _authenticationManager;    public MasterLoginLogoutPartialActionExtension(IAuthenticationManager authenticationManager)    {        _authenticationManager = authenticationManager;    }    public MasterLoginLogoutModel Modify(MasterLoginLogoutModel model)    {        model.IsAuthenticated = _authenticationManager.LoggedIn;        return model;    }}</code></pre><p>Also, just for completeness, here are the parts of our FubuMVC Registry which pertains to these partials.</p><pre><code>public class ProjectFubuRegistry : FubuRegistry{    public ProjectFubuRegistry()    {        Applies.ToThisAssembly();        Actions.FindWith&lt;PartialActionsSource&gt;();        Views.TryToAttach(findViews =&gt;                                    {                                        findViews.by_ViewModel_and_Namespace_and_MethodName();                                        findViews.by_ViewModel_and_Namespace();                                        findViews.by_ViewModel();                                    }    }}</code></pre><p>Step-by-step, what happens when we call the partial from the master page?</p><ol><li>FubuMVC looks for the action call setup to accept that input type.2.  FubuMVC then calls the action call and passes a blank model to the PartialAction’s Execute method that was created while bootstrapping. In this case, it’s an instance of PartialAction, closed with MasterLoginLogoutModel.3.  When this instance of PartialAction is instantiated, it depends on an IPartialActionExtensionGraph<MasterLoginLogoutModel>. When we call Modify on this, StructureMap will have already found our MasterLoginLogoutPartialActionExtension class <em>(since it implements IPartialActionExtension and closes it with MasterLoginLogoutModel)</em>, and we will have a graph with this single action extension. If you had two classes that close this interface with MasterLoginLogoutModel, then they would both be in the graph.4.  The PartialAction, then calls modify on the graph, which loops through all of the action extensions and calls the Modify method, resetting the model to the return value for each call.5.  The model is then returned from the PartialAction, and is passed to the view.</li></ol><p>Now, whenever we want to create a new partial view, we can just follow these steps:</p><ol><li>Create the model for the view, <em>be sure to mark it with the PartialModel attribute</em>.2.  Create as many implementations of IPartialActionExtension as we need (normally only one). Be sure it closes the interface with the model we’ve just setup.3.  Create a view that uses the model. FubuMVC will be smart enough to figure out that’s the view we want to use, as long as we tell FubuMVC to match views by view models.</li></ol><p>It’s my understanding that most of this plumbing will be in a future release of FubuMVC. Until then, you can do this, instead. I’ll write another post when these features are native to Fubu.</p>]]></content:encoded>
      
      <comments>https://rexflex.net/articles/fubumvc-partial-views/#disqus_thread</comments>
    </item>
    
  </channel>
</rss>
