Web development with asp.net and React.js2016-06-12T22:22:12.839Zhttp://xabikostest.github.io/Babis KarypidisHexoTalking about isomorphic JavaScript applications in Progressive .NET 2016http://xabikostest.github.io/2016/06/12/Talking-about-isomorphic-JavaScript-applications-in-Progressive-NET-2016/2016-06-12T21:26:45.000Z2016-06-12T22:22:12.839Z<h4 id="Presenting-in-the-conference"><a href="#Presenting-in-the-conference" class="headerlink" title="Presenting in the conference"></a>Presenting in the conference</h4><p>During the past couple of years I was actively involved in several meetups and local events mostly as attendee but some times as speaker or organizer as well. In general I think this is one of the best ways to get to know really smart people and find out about the trends in the extremely fast moving software development world.<br><a id="more"></a><br>When I discover a really innovative subject I always want to know everything about it, and presenting this subject in front of other people is always a good reason to do it. As in the last couple of months I am working mostly as a <a href="http://facebook.github.io/react/" target="_blank" rel="external">Reactjs</a> developer and my interest for Microsoft’s new platform, <a href="https://www.microsoft.com/net" target="_blank" rel="external">.NET core</a> is high I am very interested on how we can combine these in order to get the best of the two worlds. This is going the subject of my presentation in the upcoming <a href="https://skillsmatter.com/conferences/7235-progressive-dot-net-tutorials-2016" target="_blank" rel="external">Progressive .NET 2016</a></p>
<h4 id="Presentation-details"><a href="#Presentation-details" class="headerlink" title="Presentation details"></a>Presentation details</h4><p>During the presentation I will try initially, to explain what is an <a href="http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/" target="_blank" rel="external">isomorphic JavaScrip application</a> and how we can achieve this in the .NET ecosystem. For that reason two corresponding libraries are going to be presented. Initially the mature and well known <a href="http://reactjs.net/" target="_blank" rel="external">Reactjs .NET</a>. This library offers some unique capabilities and allows us to render our <a href="http://facebook.github.io/react/" target="_blank" rel="external">React.js</a> components on the server and return a fully rendered page to the browser. The library is used in many project but it comes with some limitations like the lack of supporting server side routing or use it for another framework.</p>
<p>Microsoft on the other side, and most specifically the <a href="http://knockoutjs.com/" target="_blank" rel="external">Knockout</a> guy <a href="http://blog.stevensanderson.com/" target="_blank" rel="external">Steven Sanderson</a>, is developing an open source project in Github that is called <a href="https://github.com/aspnet/JavaScriptServices" target="_blank" rel="external">JavaScript services</a>. This library has as a goal to execute client side application of various frameworks and libraries on the server side. The project is quite promissing and currently you can use it with <a href="http://facebook.github.io/react/" target="_blank" rel="external">Reactjs</a>, <a href="https://angular.io/" target="_blank" rel="external">Angular2</a>, <a href="http://knockoutjs.com/" target="_blank" rel="external">Knockout</a> and more frameworkds will follow as the core project is framework agnostic.</p>
<h4 id="Where-this-will-happen"><a href="#Where-this-will-happen" class="headerlink" title="Where this will happen"></a>Where this will happen</h4><p>My presentation will be in the context of <a href="https://skillsmatter.com/conferences/7235-progressive-dot-net-tutorials-2016" target="_blank" rel="external">Progressive .NET 2016</a>. I have to say that I am very excited that I will be part of such a well known conference in the city of London. I will have the opportunity to share my thoughts and ideas on such a hot topic like the isomorphic JavaScript applications. I strongly believe that this kind of applications will become more and more popular as they provide tremendous flexibility and can improve initial performance quite a lot. I hope that my talk will be enjoyed by the .NET community as it touches a very innovative subject that opens new possibilities for web application development.</p>
<h2 id="Hope-to-meet-you-in-person-in-the-fantastic-Progressive-NET-2016"><a href="#Hope-to-meet-you-in-person-in-the-fantastic-Progressive-NET-2016" class="headerlink" title="Hope to meet you in person in the fantastic Progressive .NET 2016"></a>Hope to meet you in person in the fantastic <a href="https://skillsmatter.com/conferences/7235-progressive-dot-net-tutorials-2016" target="_blank" rel="external">Progressive .NET 2016</a></h2>
<h4 id="Presenting-in-the-conference"><a href="#Presenting-in-the-conference" class="headerlink" title="Presenting in the conference"></a>Presenting in the conference</h4><p>During the past couple of years I was actively involved in several meetups and local events mostly as attendee but some times as speaker or organizer as well. In general I think this is one of the best ways to get to know really smart people and find out about the trends in the extremely fast moving software development world.<br>
ASP.NET 5 and Webpack part 1http://xabikostest.github.io/2015/12/15/ASP-NET-5-and-Webpack-part-1/2015-12-15T17:40:00.000Z2016-05-08T18:40:11.361Z<h3 id="Introduction"><a href="#Introduction" class="headerlink" title="Introduction"></a>Introduction</h3><p>This is the first of the two parts about using <a href="http://webpack.github.io/" target="_blank" rel="external">webpack</a> and the corresponding <a href="https://www.nuget.org/packages/Webpack/" target="_blank" rel="external">nuget package</a> I created, in an asp.net 5 application.<br>This part acts as an introduction to the reasons behind the need for an alternative approach of static asset management and JavaScript module bundling in an asp.net 5 application.<br>Besides that includes a brief explanation of an example Reactjs application that uses the webpack nuget package. In the second part we will explore the internals of the nuget package itself and dig into webpack’s details.<br><a id="more"></a></p>
<h3 id="Connection-to-the-past"><a href="#Connection-to-the-past" class="headerlink" title="Connection to the past"></a>Connection to the past</h3><p>A long time ago I wrote a <a href="http://xabikos.com/javascript%20module%20bundler/javascript%20dependencies%20management/css%20module%20bundler/css%20dependencies%20management/2015/05/17/asp.net-vnext-with-webpack.html" target="_blank" rel="external">post</a> about using <a href="http://webpack.github.io/" target="_blank" rel="external">webpack</a><br>in an asp.net 5 (vnext at that point) application. I ended that post saying that another post would come with a full isomorphic JavaScript application in asp.net with <a href="http://facebook.github.io/react/" target="_blank" rel="external">React.js</a> and webpack.<br>Unfortunatelly I didn’t keep that promise but I am very optimistic this will happen in the future especially after we will be able to use the amazing <a href="http://tjanczuk.github.io/edge/#/" target="_blank" rel="external">Edge.js</a> library for server side rendering of React.js components.<br>In the meantime I was involved in several React projects and in all of them was using webpack so I had the change to really dig into the tool and learn it deeply.</p>
<h3 id="Why-to-use-webpack"><a href="#Why-to-use-webpack" class="headerlink" title="Why to use webpack"></a>Why to use webpack</h3><p>The last personal side project I am working on is a Reactjs application with asp.net 5 as server side platform this time. I really like the new approach from asp.net platform and the flexibility it provides.<br>In the tooling section though, there is still plenty of room for improvement. As mentioned above I was involved in several Reactjs projects and none of them was using asp.net as back end. I learned a lot during that time<br>but I was also a bit frustrated about the lack of tooling in .net ecosystem. As I highlighted in my <a href="http://xabikos.com/javascript%20module%20bundler/javascript%20dependencies%20management/css%20module%20bundler/css%20dependencies%20management/2015/05/17/asp.net-vnext-with-webpack.html" target="_blank" rel="external">related blog post</a> the new template provides a new and better way for client side dependencies maangement<br>through tools like <a href="http://bower.io" target="_blank" rel="external">bower</a>, <a href="http://gulpjs.com" target="_blank" rel="external">gulp</a> and <a href="http://gruntjs.com" target="_blank" rel="external">grunt</a>. My sense though is that community walks away from this approach and there is a tendency to use just npm modules even for client side packages and not <a href="http://bower.io" target="_blank" rel="external">bower</a>.<br>On top of that more and more projects use npm scripts and webpack for executing tasks instead of <a href="http://gulpjs.com" target="_blank" rel="external">gulp</a> or <a href="http://gruntjs.com" target="_blank" rel="external">grunt</a> something I really like as it removes a dependency and a corresponding configuration file from the project.<br>Finally I really suggest to watch <a href="https://twitter.com/jcreamer898" target="_blank" rel="external">Jonathan Creamer</a> <a href="https://www.youtube.com/watch?v=MzVFrIAwwS8" target="_blank" rel="external">talk</a> on some advanced features of webpack.</p>
<h3 id="Which-problem-the-library-solves"><a href="#Which-problem-the-library-solves" class="headerlink" title="Which problem the library solves"></a>Which problem the library solves</h3><p>One of the most valuable features of webpack is the accompanied <a href="https://webpack.github.io/docs/webpack-dev-server.html" target="_blank" rel="external">development server</a> and the live reload it provides when saving a file.<br>Of course this is not something new as there are tools that doing this already but where webpack-dev-server shines is that does this without reloading the page.<br>This happens by default for stylesheets. When using Reactjs we have exactly the same behaviour by using the appropriate configuration something that is extremelly powerfull as we dont’s loose the application’s state from a full page refresh.</p>
<p>What it was frustrated and lead me to create that library is the fact that I had first to start webpack-dev-server and then start my project through Visual Studio or command line in a different platform.<br>On top of that I had to do all the webpack configuration and add the correct script tags in my cshtml layout files. The webpack-dev-server could serve static html files as well and inject the approperiate scripts automatically<br>but then you end up to have your appication running in a diffrent location than the back end during development and have to solve all the <a href="https://en.wikipedia.org/wiki/Cross-origin_resource_sharing" target="_blank" rel="external">CORS</a> issues.<br>So during all these cycles I realised I should automate all these steps, from basic configuration to launch the right tool every time I am starting my asp.net project. The configuration the <a href="https://www.nuget.org/packages/Webpack/" target="_blank" rel="external">nuget package</a> provides looks like:</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Start asp.net core application</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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">app.UseWebpack(<span class="keyword">new</span> WebpackOptions() {</span><br><span class="line"> StylesTypes = <span class="keyword">new</span> List<StylesType>() {</span><br><span class="line"> StylesType.Css</span><br><span class="line"> },</span><br><span class="line"> EnableHotLoading = <span class="keyword">true</span>,</span><br><span class="line">});</span><br></pre></td></tr></tbody></table></figure></div></figure>
<h3 id="A-concrete-example"><a href="#A-concrete-example" class="headerlink" title="A concrete example"></a>A concrete example</h3><p>In order to demonstrate webpack in an asp.net 5 in a better way I have created a boilerplate application in <a href="https://github.com/xabikos/aspnet5-react-webpack-boilerplate" target="_blank" rel="external">Github</a>.<br>Once you copy the repository you need to execute dnu restore and dnu build as usual from the command line to download all the nuget packages and after this npm install to install the required node packages that are a few.<br>After finishing that, you are ready to start the application by executing dnx web. This will start the normal asp.net server but the webpack-dev-server too in the address that is provided in the configuration.<br>If no configuration is present will start on localhost:4000. The webpack-dev-server logs to the same console as asp.net does and you can get a nice indication on what is happening.<br>After the initial launch and when everything is fine you should have in the console an output like the following:</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Webpack console output</span><ul class="tabs"><li class="tab active">cmd</li></ul></figcaption><div class="tabs-content"><figure class="highlight cmd" style="display: block;"><table><tbody><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">[<span class="number">279</span>] ./~/react-deep-force-update/lib/index.js <span class="number">1</span>.<span class="number">29</span> kB {<span class="number">0</span>} [built]</span><br><span class="line">[<span class="number">280</span>] ./~/global/window.js <span class="number">243</span> bytes {<span class="number">0</span>} [built]</span><br><span class="line">[<span class="number">281</span>] ./app/components/counter.jsx <span class="number">3</span>.<span class="number">63</span> kB {<span class="number">0</span>} [built]</span><br><span class="line"><span class="function">webpack: <span class="title">bundle</span> <span class="title">is</span> <span class="title">now</span> <span class="title">VALID</span>.</span></span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>And if you browse to the project (<a href="http://localhost:5000" target="_blank" rel="external">http://localhost:5000</a> by default) you should get a screen like the one that follows:</p>
<div class="figure nocaption fig-100" style="width:;"><a class="fancybox" href="webpackBoilerplate.png" title="webpack" data-fancybox-group="webpack"><img class="fig-img" src="webpackBoilerplate.png" alt="webpack"></a></div><div style="clear:both;"></div>
<p>The output is quite simple but it demonstrates most of the features that will be used in a real application as well. It contains a statefull component that has some basic styling through sass.<br>The component actually has two counters. The first just counts the seconds since it was loaded in the page and the second the number of rerenders. Initially is maybe hard to understand the difference but once you will start<br>changing the component you can see that the rerender counter will be increased more than time elapsed as any chnage in the component will trigger an extra render.<br><strong>The amazing thing is that we can edit both the styles and the output of the component without loosing it’s state</strong></p>
<div class="figure nocaption fig-100" style="width:;"><a class="fancybox" href="hotloading.gif" title="webpack" data-fancybox-group="webpack"><img class="fig-img" src="hotloading.gif" alt="webpack"></a></div><div style="clear:both;"></div>
<h3 id="Additional-notes"><a href="#Additional-notes" class="headerlink" title="Additional notes"></a>Additional notes</h3><ul>
<li><p>Used only during development</p>
<p> This is a library that should be used only during development environment and should not be part of any production system.<br> To be sure you are staring in a development environment from the command line you need to execute <code>dnx web ASPNET_ENV=Development</code>.</p>
</li>
<li><p>Cross platform solution for live reload of static resources in asp.net 5 applications</p>
<p> As mentioned before there are some other tools that provide live reload functionality. This is a well tested solution for an asp.net 5 application that works cross platform.<br> Actually I developed the boilerplate project in OSX by using <a href="https://code.visualstudio.com" target="_blank" rel="external">Visual Studio Code</a></p>
</li>
<li><p>Production bundles</p>
<p> Webpack is a great tool for preparing the production bundles too as it can handle minification, create separate bundle for vendor scripts and support async loading of the bundles.<br> The tool has many more capabilities and would require a separate blog post to describe it.</p>
</li>
</ul>
<h3 id="Introduction"><a href="#Introduction" class="headerlink" title="Introduction"></a>Introduction</h3><p>This is the first of the two parts about using <a href="http://webpack.github.io/">webpack</a> and the corresponding <a href="https://www.nuget.org/packages/Webpack/">nuget package</a> I created, in an asp.net 5 application.<br>This part acts as an introduction to the reasons behind the need for an alternative approach of static asset management and JavaScript module bundling in an asp.net 5 application.<br>Besides that includes a brief explanation of an example Reactjs application that uses the webpack nuget package. In the second part we will explore the internals of the nuget package itself and dig into webpack’s details.<br>
Execute multiple npm scripts through VS Code task runnerhttp://xabikostest.github.io/2015/11/11/Execute-multiple-npm-scripts-through-VS-Code-task-runner/2015-11-11T19:40:00.000Z2016-05-08T18:40:11.353Z<h4 id="VS-Code"><a href="#VS-Code" class="headerlink" title="VS Code"></a>VS Code</h4><p><a href="https://code.visualstudio.com" target="_blank" rel="external">Vs code</a> is one of the new players in the area of editors and has done some really good progres so far on catching up with the competition. It is a lightweight editor which currently supports <a href="https://code.visualstudio.com/docs/languages/overview" target="_blank" rel="external">mulitple langueges</a> and on top of that it’s <a href="https://code.visualstudio.com/docs/editor/setup" target="_blank" rel="external">multiplatform</a>. It includes already some great features and more are coming in the near future. Personally I am using it more and more both for front and back end development.<br><a id="more"></a></p>
<h4 id="Webpack-Gulp-npm-scripts"><a href="#Webpack-Gulp-npm-scripts" class="headerlink" title="Webpack - Gulp - npm scripts"></a>Webpack - Gulp - npm scripts</h4><p>During the last months I am heavily involved in various Reactjs project so there is a need to execute scripts in order to transpile React components and ES6 code. In all projects we are doing heavy usage of <a href="http://webpack.github.io" target="_blank" rel="external">Webpack</a> in order to manage the transpilation and the dependencies management. Initially we were doing all the configuration through <a href="http://gulpjs.com" target="_blank" rel="external">Gulp</a> and it’s corresponding tasks. As Webpack evolved and I was more involved in nodejs ecosystem I found the npm scripts and how by using this feature we could avoid the dependency to Gulp or any other task runner.</p>
<h4 id="VS-Code-tasks-for-the-rescue"><a href="#VS-Code-tasks-for-the-rescue" class="headerlink" title="VS Code tasks for the rescue"></a>VS Code tasks for the rescue</h4><p>Code has integrated the ability to execute various tasks as you can see in the official <a href="https://code.visualstudio.com/docs/editor/tasks" target="_blank" rel="external">documentation</a>. As it mentioned clearly in the documentation there is already integrated support for Gulp, Grunt and some other tools. What is missing is that with a few lines of configuration we could execute all the scripts that exist in the corresponding section of our package.json file.</p>
<h4 id="Create-the-tasks-json-file"><a href="#Create-the-tasks-json-file" class="headerlink" title="Create the tasks.json file"></a>Create the tasks.json file</h4><p>Available tasks are declared in an external file called “tasks.json” and is placed inside the folder .vscode in the root of the project. You can either create it manual or let the editor create the folder and add a very detailed example file. In order to achieve the last you need to hit Ctrl + Shift + P or Cmd + Shift + P type “Tasks” and select Configure Task Runner as in the following image</p>
<div class="figure nocaption fig-100" style="width:;"><a class="fancybox" href="configureTasks.png" title="configure tasks" data-fancybox-group="tasks"><img class="fig-img" src="configureTasks.png" alt="configure tasks"></a></div><div style="clear:both;"></div>
<h4 id="Add-the-configuration-for-npm-scripts"><a href="#Add-the-configuration-for-npm-scripts" class="headerlink" title="Add the configuration for npm scripts"></a>Add the configuration for npm scripts</h4><p>In order to be able to execute the npm scripts we need to tweak the first task that is related to Typescript. As a first step lets see what are the available scripts inside the package.json file.</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>npm scripts</span><ul class="tabs"><li class="tab active">json</li></ul></figcaption><div class="tabs-content"><figure class="highlight" style="display: block;"><table><tbody><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">"scripts": {</span><br><span class="line"> "build-dev": "webpack --bail",</span><br><span class="line"> "start-dev": "webpack-dev-server"</span><br><span class="line">},</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>As I mentioned before we are doing a lot of react development so these two scripts are responsible for building the development version of the code the first and for starting the webpack’s development server and watching the files for changes the second. Now lets see how the tasks.json file looks like</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Add npm as comand</span><ul class="tabs"><li class="tab active">json</li></ul></figcaption><div class="tabs-content"><figure class="highlight json" style="display: block;"><table><tbody><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></pre></td><td class="code"><pre><span class="line">{</span><br><span class="line"> <span class="attr">"version"</span>: <span class="string">"0.1.0"</span>,</span><br><span class="line"> <span class="attr">"command"</span>: <span class="string">"npm"</span>,</span><br><span class="line"> <span class="attr">"isShellCommand"</span>: <span class="literal">true</span>,</span><br><span class="line"> <span class="attr">"showOutput"</span>: <span class="string">"always"</span>,</span><br><span class="line"> <span class="attr">"args"</span>: [<span class="string">"run"</span>],</span><br><span class="line"> <span class="attr">"isWatching"</span>: <span class="literal">false</span>,</span><br><span class="line"> <span class="attr">"tasks"</span>: [</span><br><span class="line"> { <span class="attr">"taskName"</span>: <span class="string">"build-dev"</span> },</span><br><span class="line"> { <span class="attr">"taskName"</span>: <span class="string">"start-dev"</span> }</span><br><span class="line"> ]</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>As you can see we have to declare “npm” as the required command and configure it as a shell command. The crucial part is the args option as all the scripts are executed by “npm run” as prefix so we need to provide this as an argument. The show output parameter is entirely up to you how to configure it. Then we need to declare the tasks for the command inside the corresponding array. Each task can have its own configuration and arguments but I would suggest not to use this option and instead putt all required arguments to the scripts section as some other members in the team could execute these from another tool. So in our case is enough to declare just the tasks name which of course should match with the one in scripts section.</p>
<h4 id="Task-execution"><a href="#Task-execution" class="headerlink" title="Task execution"></a>Task execution</h4><p>Now that everything is in place when hitting Ctrl + Shift + P or Cmd + Shift + P and select “Run Task” we should see a list with the available tasks that represent the scripts. We can choose either of the options and depending on the show output configuration we will be able to see the results in the output window.</p>
<div class="figure nocaption fig-100" style="width:;"><a class="fancybox" href="availabletasks.png" title="availalbe tasks" data-fancybox-group="tasks"><img class="fig-img" src="availabletasks.png" alt="availalbe tasks"></a></div><div style="clear:both;"></div>
<h4 id="Bonus-tasks-keyboard-shortcuts"><a href="#Bonus-tasks-keyboard-shortcuts" class="headerlink" title="Bonus - tasks keyboard shortcuts"></a>Bonus - tasks keyboard shortcuts</h4><p>Be default VS Code has assigned keyboard shortcuts for execute the build and test task. Luckily there are available the extension points for showing the panel with available tasks and also a command to stop the running task. First you need to find the preferences and then select Keyboard Shortcuts and then add the following entries. Feel free to change the key combinations according to your preferences. It was hard though to find some combination so I chose r for run a task and e for exit a task. After saving we can have an easier access to both select the command and also to terminate it.</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Keyboard shortcuts</span><ul class="tabs"><li class="tab active">json</li></ul></figcaption><div class="tabs-content"><figure class="highlight" style="display: block;"><table><tbody><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">{ "key": "shift+cmd+r", "command": "workbench.action.tasks.runTask" },</span><br><span class="line">{ "key": "shift+cmd+e", "command": "workbench.action.tasks.terminate"}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>Happy coding!</p>
<h4 id="VS-Code"><a href="#VS-Code" class="headerlink" title="VS Code"></a>VS Code</h4><p><a href="https://code.visualstudio.com">Vs code</a> is one of the new players in the area of editors and has done some really good progres so far on catching up with the competition. It is a lightweight editor which currently supports <a href="https://code.visualstudio.com/docs/languages/overview">mulitple langueges</a> and on top of that it’s <a href="https://code.visualstudio.com/docs/editor/setup">multiplatform</a>. It includes already some great features and more are coming in the near future. Personally I am using it more and more both for front and back end development.<br>
Webpack aliases and relative pathshttp://xabikostest.github.io/2015/10/03/Webpack-aliases-and-relative-paths/2015-10-03T10:10:00.000Z2016-05-08T18:40:11.341Z<h4 id="Why-Webpack"><a href="#Why-Webpack" class="headerlink" title="Why Webpack"></a>Why Webpack</h4><p><a href="http://webpack.github.io" target="_blank" rel="external">Webpack</a> is one of the solutions that are available out there and solves JavaScript reference modules problem. It’s also my favourite tool to use it in the Reactjs project I am involved lately. Webpack provides wider functionality except just referencing external JavaScript code but this is not the scope of this blog spot. In this post I will try to concentrate in a feature of the tool that most examples don’t use it and it’s very important according to my opinion. This is the <a href="https://webpack.github.io/docs/configuration.html#resolve" target="_blank" rel="external">resolve</a> section of Webpack configuration and how it can help us in day to day development.<br><a id="more"></a></p>
<h4 id="An-example-without-using-aliases"><a href="#An-example-without-using-aliases" class="headerlink" title="An example without using aliases"></a>An example without using aliases</h4><p>As mentioned earlier I am involved lately in multiple projects related to Reactjs so the example uses this library. What is described on the other hand could easily applied in frameworks like Angular or just pure JavaScript code which is bundled through Webpack.</p>
<p>Let’s say that we have a really simple components hierarchy that one uses the other. A view of this example could be this one:<br><figure class="codeblock codeblock--tabbed"><figcaption><span>Folder structure</span><ul class="tabs"><li class="tab active"></li></ul></figcaption><div class="tabs-content"><figure class="highlight plain" style="display: block;"><table><tbody><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></pre></td><td class="code"><pre><span class="line"><App></span><br><span class="line"> <Utility></span><br><span class="line"> <Home></span><br><span class="line"> <Utility></span><br><span class="line"> <Service></span><br></pre></td></tr></tbody></table></figure></div></figure><br>That means we have a Utility component (you could consider it a separate file) that is used by both App and Home component and on top of this Home component uses also an external service. This is reflected in the file system as:</p>
<div class="figure nocaption fig-33 center" style="width:;"><a class="fancybox" href="FolderStructure.png" title="folder structure" data-fancybox-group="webpack"><img class="fig-img" src="FolderStructure.png" alt="folder structure"></a></div><div style="clear:both;"></div>
<p>Even in new ES6 module system when we need a reference in a piece of code in our project that is not a node module, we need to reference it by relative path to the file we need it. So to make it more concrete the import code for App component looks like this:</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Import Utility module</span><ul class="tabs"><li class="tab active">js</li></ul></figcaption><div class="tabs-content"><figure class="highlight js" style="display: block;"><table><tbody><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"><span class="keyword">import</span> Home <span class="keyword">from</span> <span class="string">'./home.jsx'</span>;</span><br><span class="line"><span class="keyword">import</span> Utility <span class="keyword">from</span> <span class="string">'./common/utility.jsx'</span>;</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>And to make the issue with relative paths more obvious lets see the import statements of Home component:</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Import modules relative paths</span><ul class="tabs"><li class="tab active">js</li></ul></figcaption><div class="tabs-content"><figure class="highlight js" style="display: block;"><table><tbody><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"><span class="keyword">import</span> Utility <span class="keyword">from</span> <span class="string">'./common/utility.jsx'</span>;</span><br><span class="line"><span class="keyword">import</span> TextService <span class="keyword">from</span> <span class="string">'../services/textService.js'</span>;</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>From the example above we should realise that each time we need to use a piece of code in our application, we need to now in which exact folder we are and then start calculating the relative path to this file. This is something that really annoys me and is not only that. Just think the case that the project evolves and the utility file is referenced in multiple places. And then we need to either rename the file or more probably reorganise the folder structure and choose a different one. We have to find all the files that reference this file and make the appropriate changes.</p>
<h4 id="Webpack-Resolve-Alias-solution"><a href="#Webpack-Resolve-Alias-solution" class="headerlink" title="Webpack Resolve Alias solution"></a>Webpack Resolve Alias solution</h4><p>As mention before <a href="http://webpack.github.io" target="_blank" rel="external">Webpack</a> has a section in it’s configuration (<a href="https://webpack.github.io/docs/configuration.html#resolve" target="_blank" rel="external">resolve section</a>) that could solve this issue and it’s very powerful. We can declare aliases in many ways so we could not rely on relative paths but just reference our code as regular node modules.</p>
<p>First let’s see what we need to add to the webpack.config file:</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Webpack alias config</span><ul class="tabs"><li class="tab active">js</li></ul></figcaption><div class="tabs-content"><figure class="highlight js" style="display: block;"><table><tbody><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></pre></td><td class="code"><pre><span class="line">resolve: {</span><br><span class="line"> root: path.resolve(__dirname),</span><br><span class="line"> alias: {</span><br><span class="line"> app: <span class="string">'components/app'</span>,</span><br><span class="line"> home: <span class="string">'components/home'</span>,</span><br><span class="line"> utility: <span class="string">'components/common/utility'</span>,</span><br><span class="line"> textService: <span class="string">'services/textService'</span></span><br><span class="line"> },</span><br><span class="line"> extensions: [<span class="string">''</span>, <span class="string">'.js'</span>, <span class="string">'.jsx'</span>]</span><br><span class="line">},</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>It’s important to configure the root with an absolute path so the path in the alias section is becoming relative to where the webpack.config file resides. Of course in a real project where we have more files we should probably extract this object to a separate file and import it in webpack.config file. After that is our responsibility to have unique names in aliases something that probably was easier before, due to folder names.</p>
<p>But now is interesting to see how the import statements of components look like. Let’s begin with App component as before:</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Import module through alias</span><ul class="tabs"><li class="tab active">js</li></ul></figcaption><div class="tabs-content"><figure class="highlight js" style="display: block;"><table><tbody><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"><span class="keyword">import</span> Home <span class="keyword">from</span> <span class="string">'home'</span>;</span><br><span class="line"><span class="keyword">import</span> Utility <span class="keyword">from</span> <span class="string">'utility'</span>;</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>And let’s also see the Home component</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Import module through alias</span><ul class="tabs"><li class="tab active">js</li></ul></figcaption><div class="tabs-content"><figure class="highlight js" style="display: block;"><table><tbody><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"><span class="keyword">import</span> Utility <span class="keyword">from</span> <span class="string">'utility'</span>;</span><br><span class="line"><span class="keyword">import</span> TextService <span class="keyword">from</span> <span class="string">'textService'</span>;</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>By now should be obvious that it’s easier to reference any file in our project. On top of that, where every file resides exists only in one place so if there is a need to either rename a file or restructure the folders the only place we have to touch is the aliases. In the configuration I also added the extensions option as it’s a way not to include the extension of the file in the path.</p>
<p>You can find the code for this example in the corresponding <a href="https://github.com/xabikos/webpack-alias" target="_blank" rel="external">Github repository</a>.</p>
<h4 id="Why-Webpack"><a href="#Why-Webpack" class="headerlink" title="Why Webpack"></a>Why Webpack</h4><p><a href="http://webpack.github.io">Webpack</a> is one of the solutions that are available out there and solves JavaScript reference modules problem. It’s also my favourite tool to use it in the Reactjs project I am involved lately. Webpack provides wider functionality except just referencing external JavaScript code but this is not the scope of this blog spot. In this post I will try to concentrate in a feature of the tool that most examples don’t use it and it’s very important according to my opinion. This is the <a href="https://webpack.github.io/docs/configuration.html#resolve">resolve</a> section of Webpack configuration and how it can help us in day to day development.<br>
ASP.NET vNext with webpackhttp://xabikostest.github.io/2015/05/17/ASP-NET-vNext-with-webpack/2015-05-17T18:10:00.000Z2016-05-08T18:40:11.330Z<h4 id="Why-I-was-absent"><a href="#Why-I-was-absent" class="headerlink" title="Why I was absent"></a>Why I was absent</h4><p>It is a long time from my last post but so much have happened during this time period. Initially I was involved in the organization of local <a href="http://global.azurebootcamp.net/" target="_blank" rel="external">Global Azure Bootcamp</a> in <a href="http://www.skgazure.com/" target="_blank" rel="external">Thessaloniki</a>. It was our first attempt to organize an one day event and we are very satisfied by the result. It is an amazing feeling to be part of a global community for one day. Right after Azure Bootcamp, Microsoft’s biggest development conference took place in San Fransisco. At <a href="http://www.buildwindows.com/" target="_blank" rel="external">Build</a> tons of new features were announced and I am still straggling to watch all the interesting videos on <a href="http://channel9.msdn.com/events/build/2015/" target="_blank" rel="external">Channel 9</a>. Lastly I attended the first international development conference that was organized in the city I am living, in Thessaloniki. <a href="http://devitconf.org/" target="_blank" rel="external">Devit</a> took place on Friday 15th of May and it was very successful and amazingly well organized conference.</p>
<h4 id="ASP-NET-vNext"><a href="#ASP-NET-vNext" class="headerlink" title="ASP.NET vNext"></a>ASP.NET vNext</h4><p><a href="http://www.asp.net/vnext" target="_blank" rel="external">asp.net vNext</a> is the next version of the well know web stack framework and I won’t describe it at all as it’s quite easy to find details about it. It’s not yet production ready but that point comes really close. I am very interested on this new web stack and the direction it gets so I am playing with it when the time permits. Among the other changes the core team has done, they also changed the way the client side package management is done. The framework adopts well known practices on the field and adds to the core system tools like <a href="https://www.npmjs.com/" target="_blank" rel="external">npm</a> and <a href="http://bower.io/" target="_blank" rel="external">bower</a> package managers and <a href="http://gulpjs.com/" target="_blank" rel="external">gulp</a> and <a href="http://gruntjs.com/" target="_blank" rel="external">grunt</a> tasks runners. For the people that are not familiar with basic <a href="https://nodejs.org/" target="_blank" rel="external">nodejs</a> development and client side package management they should spend some time and study those as it’s part of the next version of asp.net. An excellent place to start the reading is the newly added official <a href="http://docs.asp.net/en/latest/index.html" target="_blank" rel="external">documentation site</a> of asp.net vNext.<br><a id="more"></a></p>
<h4 id="Client-side-package-management-and-webpack"><a href="#Client-side-package-management-and-webpack" class="headerlink" title="Client side package management and webpack"></a>Client side package management and webpack</h4><p>During the last months in my work I am heavily involved on developing a large <a href="http://facebook.github.io/react/" target="_blank" rel="external">Reactjs</a> application. For this reason we need to use a lot of node and bower packages something that makes the usage of a module bundler an absolute requirement. After some investigation we chose to use <a href="http://webpack.github.io/" target="_blank" rel="external">webpack</a> as it is very popular, it has an active community behind it and it fits perfect with react development. One of the greatest features of webpack is that it allows to use node packages directly inside the browser.</p>
<h4 id="Combine-ASP-NET-vNext-with-webpack"><a href="#Combine-ASP-NET-vNext-with-webpack" class="headerlink" title="Combine ASP.NET vNext with webpack"></a>Combine ASP.NET vNext with webpack</h4><p> The current project templates for asp.net vNext that are part of Visual Studio 2015 RC offer a completely different way of managing the client side packages dependencies which is in the right direction. I will try to make a step further and show how we can use webpack to organize our JavaScript and css code in a more modular way. To demonstrate this I have created <a href="https://github.com/xabikos/aspvnextwebpack" target="_blank" rel="external">a repository in Github</a> which would be a good starting point. After cloning the repository locally there are a sequence of commands you should execute in order to launch the application. Before executing these commands you have to make sure that <a href="https://nodejs.org/" target="_blank" rel="external">nodejs</a> is properly install on your machine and also the latest asp.net vNext is also present. You can get more info on how to install the asp.net vNext again in the <a href="http://docs.asp.net/en/latest/index.html" target="_blank" rel="external">official documentation site</a>. Once the environment is ready you need to execute form a command line that points to the same folder you cloned the repository the command:</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Install node modules</span><ul class="tabs"><li class="tab active">cmd</li></ul></figcaption><div class="tabs-content"><figure class="highlight cmd" style="display: block;"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p> in order to install all the node packages. Then we need to install all the referenced bower components by executing first</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Install bower globally</span><ul class="tabs"><li class="tab active">cmd</li></ul></figcaption><div class="tabs-content"><figure class="highlight cmd" style="display: block;"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install bower -g</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p> to install Bower globally and then</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Install bower modules</span><ul class="tabs"><li class="tab active">cmd</li></ul></figcaption><div class="tabs-content"><figure class="highlight cmd" style="display: block;"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">bower install</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p> to install the bower components. After doing this you need to generate the bundles through the preconfigured gulp task. So you need to execute</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Install gulp globally</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install gulp -g</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p> to install Gulp as a global package and then</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Start gulp development task</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">gulp development</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>in order to create the JavaScript and css bundles. The final step is to launch the development server by executing</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Start asp.net core application</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">dnx . web</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>After a while you should see Started on the command line and if you navigate to <a href="http://localhost:5000/" target="_blank" rel="external">http://localhost:5000/</a> you should get a page like the one following</p>
<div class="figure nocaption fig-100" style="width:;"><a class="fancybox" href="webpack.png" title="webpack" data-fancybox-group="webpack"><img class="fig-img" src="webpack.png" alt="webpack"></a></div><div style="clear:both;"></div>
<h4 id="JavaScript-dependencies-management"><a href="#JavaScript-dependencies-management" class="headerlink" title="JavaScript dependencies management"></a>JavaScript dependencies management</h4><p>The application is really basic and what it does is after entering a number in the textbox and pressing submit renders some Lorem ipsum text on the screen. The code for this exists in the index.cshtml file is pretty basic and easy to understand. But the interesting is how the Lorem global variable is available. This is done because in the _Layout.cshtml we include the app.bunle.js file which was generated by webpack when we executed the gulp development command. If you try to explore this file you would probably feel a bit confused as it contains many lines of code. But let’s take one step back and see where this file came from.</p>
<p>Let’s start by looking at the file lorem.js which the content is following</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>A simple javascript module</span><ul class="tabs"><li class="tab active">js</li></ul></figcaption><div class="tabs-content"><figure class="highlight js" style="display: block;"><table><tbody><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><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> loremHipsum <span class="keyword">from</span> <span class="string">'lorem-hipsum'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> Lorem = {</span><br><span class="line"> addText(count, loremTextElement, loremValidationElement) {</span><br><span class="line"> <span class="keyword">if</span> (<span class="built_in">isNaN</span>(count) || count < <span class="number">1</span> || count > <span class="number">100</span>) {</span><br><span class="line"> loremValidationElement.html(<span class="string">'Invalid input'</span>);</span><br><span class="line"> } <span class="keyword">else</span> {</span><br><span class="line"> loremTextElement.html(loremHipsum({</span><br><span class="line"> count: count,</span><br><span class="line"> units: <span class="string">'sentences'</span></span><br><span class="line"> }));</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">};</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> Lorem;</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>As you can see we can use the new ES6 module system thanks to webpack and the <a href="https://github.com/babel/babel-loader/" target="_blank" rel="external">babel loader</a>. The lorem-hipsum is just on ordinal node package that we can consume directly inside our browser scripts. Also we export the object Lorem we created in the file. The object just contains a simple method that uses the node package to add some random text to the provided element. You should also notice that we can use the new way of declaring functions.</p>
<p>The next important piece in the procedure is the app.js file which contains only two lines of code.</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Client side app entry point</span><ul class="tabs"><li class="tab active">js</li></ul></figcaption><div class="tabs-content"><figure class="highlight js" style="display: block;"><table><tbody><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"><span class="keyword">var</span> Lorem = <span class="built_in">require</span>(<span class="string">'expose?Lorem!./lorem'</span>)</span><br><span class="line"><span class="built_in">require</span>(<span class="string">'../styles/site.scss'</span>);</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>This is the entry point in our application and the first line is the one that makes the Lorem variable available in the global scope through the <a href="https://github.com/webpack/expose-loader/" target="_blank" rel="external">expose-loader</a> webpack loader. The second line is related to css and we will explain it afterwards. So during the creation of the bundle webpack solves all the dependencies starting from app.js file and produces the final app.bundle.js file which can be referenced directly from an html page.</p>
<h4 id="css-dependencies-management"><a href="#css-dependencies-management" class="headerlink" title="css dependencies management"></a>css dependencies management</h4><p>Let’s move on how webpack can assist us on stylesheets dependencies management. If everything is fine so far when you load the page you will notice that the top header animates and fades in to the page. This is done by the <a href="https://github.com/jdsimcoe/animated.sass/" target="_blank" rel="external">animated.sass</a> bower component which is referenced and applying certain classes. The most interesting piece of this exists in the file main.scss which looks like this:</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Application's style file</span><ul class="tabs"><li class="tab active">css</li></ul></figcaption><div class="tabs-content"><figure class="highlight" style="display: block;"><table><tbody><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">@import "../bower_components/animated.sass/_animated.scss";</span><br><span class="line">@include animation(fade-in-down);</span><br><span class="line"></span><br><span class="line">.app-title{</span><br><span class="line"> @include animate(fade-in-down, 2s);</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>Here you can see that this is a regular scss file but we have imported a module from the bower components folder and then we can use it in a simple way. The entry point for the generated css bundle is the site.scss file which contains only one line that imports the main.scss file. This file could be used as a global repository that loads all the other scss files required by the application.</p>
<h4 id="Additional-points"><a href="#Additional-points" class="headerlink" title="Additional points"></a>Additional points</h4><p>The current default template manages the predefined libraries in a way that could potentially implemented in a different way. For example the current implementation copies into the lib folder the packages that are hard copied inside the gulpfile and most specifically in copy command. This is not very flexible as it requires every time that a new dependency is added the modification of this file as well. A possible solution to this would be to require all this dependencies in the app.js file and let webpack to create the final bundle.</p>
<p>I have also include a gulp task that creates the minified versions of all the bundles that should always been used in production environment.</p>
<h4 id="The-next-blog-post"><a href="#The-next-blog-post" class="headerlink" title="The next blog post"></a>The next blog post</h4><p>The next post which will come soon will expand this one and will describe how we can build a full isomorphic JavaScript application with asp.net vNext, <a href="http://facebook.github.io/react/" target="_blank" rel="external">React.js</a>, <a href="http://reactjs.net/" target="_blank" rel="external">Reactjs.net</a> and <a href="http://webpack.github.io/" target="_blank" rel="external">webpack</a>.</p>
<h4 id="Why-I-was-absent"><a href="#Why-I-was-absent" class="headerlink" title="Why I was absent"></a>Why I was absent</h4><p>It is a long time from my last post but so much have happened during this time period. Initially I was involved in the organization of local <a href="http://global.azurebootcamp.net/">Global Azure Bootcamp</a> in <a href="http://www.skgazure.com/">Thessaloniki</a>. It was our first attempt to organize an one day event and we are very satisfied by the result. It is an amazing feeling to be part of a global community for one day. Right after Azure Bootcamp, Microsoft’s biggest development conference took place in San Fransisco. At <a href="http://www.buildwindows.com/">Build</a> tons of new features were announced and I am still straggling to watch all the interesting videos on <a href="http://channel9.msdn.com/events/build/2015/">Channel 9</a>. Lastly I attended the first international development conference that was organized in the city I am living, in Thessaloniki. <a href="http://devitconf.org/">Devit</a> took place on Friday 15th of May and it was very successful and amazingly well organized conference.</p>
<h4 id="ASP-NET-vNext"><a href="#ASP-NET-vNext" class="headerlink" title="ASP.NET vNext"></a>ASP.NET vNext</h4><p><a href="http://www.asp.net/vnext">asp.net vNext</a> is the next version of the well know web stack framework and I won’t describe it at all as it’s quite easy to find details about it. It’s not yet production ready but that point comes really close. I am very interested on this new web stack and the direction it gets so I am playing with it when the time permits. Among the other changes the core team has done, they also changed the way the client side package management is done. The framework adopts well known practices on the field and adds to the core system tools like <a href="https://www.npmjs.com/">npm</a> and <a href="http://bower.io/">bower</a> package managers and <a href="http://gulpjs.com/">gulp</a> and <a href="http://gruntjs.com/">grunt</a> tasks runners. For the people that are not familiar with basic <a href="https://nodejs.org/">nodejs</a> development and client side package management they should spend some time and study those as it’s part of the next version of asp.net. An excellent place to start the reading is the newly added official <a href="http://docs.asp.net/en/latest/index.html">documentation site</a> of asp.net vNext.<br>
Using Reactjs.net in Web Formshttp://xabikostest.github.io/2015/03/18/Using-Reactjs-net-in-Web-Forms/2015-03-18T19:00:00.000Z2016-05-08T18:40:11.320Z<h4 id="About-React"><a href="#About-React" class="headerlink" title="About React"></a>About React</h4><p><a href="http://facebook.github.io/react/" target="_blank" rel="external">React</a> is a JavaScript library that allows us to build modern and complex web interfaces. It’s becoming more and more popular and there is a huge <a href="https://twitter.com/hashtag/reactjs" target="_blank" rel="external">buzz</a> around it. The last is absolutely normal as <a href="https://www.facebook.com/" target="_blank" rel="external">Facebook</a> is the creator of the library and they have heavily invested on it. They even have developed some architecture guidelines on how to build a React application which is called <a href="http://facebook.github.io/flux/docs/overview.html" target="_blank" rel="external">Flux</a>. Lately I am involved in a project that we are using these tools and I have to say it is really fun as it is a fresh technology and certainly changes the way I was used to develop web applications. Lastly React is one of the best libraries out there to develop what is called an <a href="http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/" target="_blank" rel="external">Isomorphic JavaScript</a> application. I won’t explain more why isomorphic looks like a safe choice for the future of the web as this is not the goal of the post.<br><a id="more"></a><br>One of the strongest points of React library is that you can produce the same HTML mark up in an easy way both client and server side. As a JavaScript library it is easy to understand how this happens because it doesn’t differs from other client side templating engines like <a href="http://handlebarsjs.com/" target="_blank" rel="external">Handlebars</a> or <a href="http://linkedin.github.io/dustjs/" target="_blank" rel="external">Dust.js</a>. Now on the server side it’s really easy to create the same HTML mark up once you are using <a href="https://nodejs.org/" target="_blank" rel="external">node.js</a> something that is quite powerful as you could potentially render one part of the application server side and the rest client side. This approach has the obvious advantage that the user experience is excellent as it gets the most important part of the information immediately and the rest of the page can be loaded client side.</p>
<h4 id="ReactJS-NET-and-ASP-NET-MVC"><a href="#ReactJS-NET-and-ASP-NET-MVC" class="headerlink" title="ReactJS.NET and ASP.NET MVC"></a>ReactJS.NET and ASP.NET MVC</h4><p>Some of the core React team members, have been created a library that consists of several <a href="https://www.nuget.org/packages?q=reactjs" target="_blank" rel="external">nuget packages</a> that allows server side rendering of a react application. I would like to explain a bit more on this as the approach the team adopted is brilliant. I was playing with the source code, which is available on <a href="https://github.com/xabikos/ReactjsWebForms" target="_blank" rel="external">GitHub repository</a>, and trying to understand how they accomplish to execute JavaScript code inside a .NET application. The library uses either the <a href="https://code.google.com/p/v8/" target="_blank" rel="external">V8 JavaScript engine</a> or Internet Explorer’s JavaScript engine and creates a context where regular JavaScript code is executed and evaluated which offers tremendous flexibility. </p>
<p>There is an official page for <a href="http://reactjs.net/" target="_blank" rel="external">ReactJS.NET</a> that offers a very good documentation and examples of how to use it. All the examples describing how to use <a href="http://reactjs.net/" target="_blank" rel="external">ReactJS.NET</a> inside an ASP.NET MVC application and there are the corresponding nuget packages which we can install to achieve this. Once we have installed the nuget package we can add the code below inside any Razor view and we will get back the HTML from the React components. Of course there are more steps involved and you can find detailed instructions <a href="http://reactjs.net/guides/server-side-rendering.html" target="_blank" rel="external">here</a>. </p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Add react content to Razor view</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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">@Html.React(<span class="string">"HelloWorld"</span>, <span class="keyword">new</span> {</span><br><span class="line"> name = <span class="string">"Daniel"</span></span><br><span class="line">})</span><br></pre></td></tr></tbody></table></figure></div></figure>
<h4 id="ReactJS-NET-in-Web-Forms"><a href="#ReactJS-NET-in-Web-Forms" class="headerlink" title="ReactJS.NET in Web Forms"></a>ReactJS.NET in Web Forms</h4><p>Now I will try to demonstrate how to use ReactJS.NET inside a Web Form. The first step is to create a Web Forms project from the well known Visual Studio wizard as in the following image<br><div class="figure nocaption fig-100" style="width:;"><a class="fancybox" href="createwebforms.jpg" title="new web forms project" data-fancybox-group="react"><img class="fig-img" src="createwebforms.jpg" alt="new web forms project"></a></div><div style="clear:both;"></div></p>
<p>The following step is to install the Reactjs.Net nuget package by typing the command below in the Package Manager console.</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Install Reactjs.net nuge package</span><ul class="tabs"><li class="tab active">ps</li></ul></figcaption><div class="tabs-content"><figure class="highlight ps" style="display: block;"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Install-Package React.Web.Mvc4 -verbose</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>This will install all the required dependencies for server side rendering to work. It will also install some dependencies that are only MVC specific but this is not a problem as the structure of two projects are very similar.<br>Now it’s time to create the first simple React component. Inside the Scripts folder we create a components sub folder where we can add the helloWorld.jsx file. The file contains a mix of JavaScript and HTML mark up syntax.</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Create a simple react component</span><ul class="tabs"><li class="tab active">js</li></ul></figcaption><div class="tabs-content"><figure class="highlight js" style="display: block;"><table><tbody><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> PageContent = React.createClass({</span><br><span class="line"> render: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>{ </span><br><span class="line"> <span class="keyword">return</span> (</span><br><span class="line"> <div></span><br><span class="line"> Hello world from {this.props.user}</span><br><span class="line"> </div></span><br><span class="line"> );</span><br><span class="line"> } </span><br><span class="line">});</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>I am not going to explain this piece of code as this is pure React and you can get all the required details in the <a href="http://facebook.github.io/react/" target="_blank" rel="external">official site</a>. After doing this we need to change the ReactConfig file inside App_Start folder which added when we installed the nuget package. More specifically we need to add to the configuration the jsx file we just created. This is pretty straightforward and we can achieve it by adding the following statement.</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Reactjs.net configuration</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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">ReactSiteConfiguration.Configuration</span><br><span class="line"> .AddScript(<span class="string">"~/Scripts/components/helloWorld.jsx"</span>);</span><br></pre></td></tr></tbody></table></figure></div></figure>
<h4 id="Render-the-content-inside-a-Web-Form"><a href="#Render-the-content-inside-a-Web-Form" class="headerlink" title="Render the content inside a Web Form"></a>Render the content inside a Web Form</h4><p>In order to render the produced HTML inside a Web Form we need to add a literal asp control to the page and then assign the value of it in the code behind file and more specifically in the page load method. So the Default.aspx file should look like this:</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Add placeholder div into web form</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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"><asp:Content ID=<span class="string">"BodyContent"</span> ContentPlaceHolderID=<span class="string">"MainContent"</span> runat=<span class="string">"server"</span>></span><br><span class="line"> <asp:Literal ID=<span class="string">"PageContent"</span> runat=<span class="string">"server"</span>></asp:Literal></span><br><span class="line"></asp:Content></span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>and the the Default.aspx.cs file like this:</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Fill the div</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">void</span> <span class="title">Page_Load</span>(<span class="params"><span class="keyword">object</span> sender, EventArgs e</span>)</span><br><span class="line"></span>{</span><br><span class="line"> <span class="keyword">var</span> env = AssemblyRegistration.Container.Resolve<IReactEnvironment>();</span><br><span class="line"> <span class="keyword">var</span> objectModel = <span class="keyword">new</span> { user = <span class="string">"React User"</span> };</span><br><span class="line"> <span class="keyword">var</span> reactComponent = env.CreateComponent(<span class="string">"PageContent"</span>, objectModel);</span><br><span class="line"></span><br><span class="line"> PageContent.Text = reactComponent.RenderHtml();</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>The code here is pretty simple and self explanatory. One point I would like to highlight is that the first parameter in CreateComponent method it should be the same as the name of the variable in the first line of jsx file. On top of this the second argument can be any object that holds the application data. In the picture below you can see the final result.</p>
<div class="figure nocaption fig-100" style="width:;"><a class="fancybox" href="reactresult.jpg" title="react result" data-fancybox-group="react"><img class="fig-img" src="reactresult.jpg" alt="react result"></a></div><div style="clear:both;"></div>
<p>I have created a corresponding <a href="https://github.com/xabikos/ReactjsWebForms" target="_blank" rel="external">GitHub repository</a> that contains a working example</p>
<h4 id="About-React"><a href="#About-React" class="headerlink" title="About React"></a>About React</h4><p><a href="http://facebook.github.io/react/">React</a> is a JavaScript library that allows us to build modern and complex web interfaces. It’s becoming more and more popular and there is a huge <a href="https://twitter.com/hashtag/reactjs">buzz</a> around it. The last is absolutely normal as <a href="https://www.facebook.com/">Facebook</a> is the creator of the library and they have heavily invested on it. They even have developed some architecture guidelines on how to build a React application which is called <a href="http://facebook.github.io/flux/docs/overview.html">Flux</a>. Lately I am involved in a project that we are using these tools and I have to say it is really fun as it is a fresh technology and certainly changes the way I was used to develop web applications. Lastly React is one of the best libraries out there to develop what is called an <a href="http://nerds.airbnb.com/isomorphic-javascript-future-web-apps/">Isomorphic JavaScript</a> application. I won’t explain more why isomorphic looks like a safe choice for the future of the web as this is not the goal of the post.<br>
Open a default Express node.js application from Visual Studio 2013http://xabikostest.github.io/2015/02/14/Open-a-default-Express-node-js-application-from-Visual-Studio-2013/2015-02-14T12:30:00.000Z2016-05-08T18:40:11.307Z<h3 id="node-js-and-Visual-Studio"><a href="#node-js-and-Visual-Studio" class="headerlink" title="node.js and Visual Studio"></a>node.js and Visual Studio</h3><p><a href="http://nodejs.org/" target="_blank" rel="external">node.js</a> is a very popular platform which allows having Javacript executed on the server. This is what everybody reads when navigating on the <a href="http://nodejs.org/" target="_blank" rel="external">official site</a>:<br><em>Node.js® is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.</em><br><a id="more"></a><br>During the last couple of years Microsoft has put a lot of effort to provide a nice experience when we want to develop a node.js application by using Visual Studio. This comes of course in conjunction of supporting node.js hosting on the company’s cloud platform <a href="http://azure.microsoft.com/en-us/develop/nodejs/" target="_blank" rel="external">Microsoft Azure</a>. We are able to develop any node.js application in Visual Studio because of the <a href="https://nodejstools.codeplex.com/" target="_blank" rel="external">Node.js Tools for Visual Studio</a> awesome open source project. This is an extension that is completely free and anyone who is interested could install it on Visual Studio. After installing the extension we can create various node.js applications as we can see in the following picture.</p>
<div class="figure nocaption fig-100" style="width:;"><a class="fancybox" href="newNodeProject.jpg" title="new node project" data-fancybox-group="vsnode"><img class="fig-img" src="newNodeProject.jpg" alt="new node project"></a></div><div style="clear:both;"></div>
<h4 id="Open-an-existing-node-application"><a href="#Open-an-existing-node-application" class="headerlink" title="Open an existing node application"></a>Open an existing node application</h4><p>The most interesting part according to my opinion is the first one, <strong>From existing Node.js code,</strong> as it gives us the opportunity to open an existing node application that was created from a different IDE and maybe on a different platform (Linux, OSX). This option gives us tremendous freedom to start contributing in a node.js project that some members of the team use different IDE and are on different platforms and we can still use Visual Studio without problem. Let me demonstrate how this works and also mention a fix to a minor problem.</p>
<h4 id="Create-a-default-Express-application"><a href="#Create-a-default-Express-application" class="headerlink" title="Create a default Express application"></a>Create a default Express application</h4><p>The first step is to create the default Express application. I am not going to explain the prerequisites of doing this as <a href="http://expressjs.com/starter/generator.html" target="_blank" rel="external">here</a> you can find very detailed instructions. After we have installed all the required dependencies and we have created a folder somewhere in our system, we should open a command window to the newly created folder and just hit:<br><figure class="codeblock codeblock--tabbed"><figcaption><span>Create express application</span><ul class="tabs"><li class="tab active">cmd</li></ul></figcaption><div class="tabs-content"><figure class="highlight cmd" style="display: block;"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">express firstExpressApplication</span><br></pre></td></tr></tbody></table></figure></div></figure><br>and after this is finished we have to move to the newly created folder and install the referenced node packages. This can be done my hitting:<br><figure class="codeblock codeblock--tabbed"><figcaption><span>Move to the correct directory</span><ul class="tabs"><li class="tab active">cmd</li></ul></figcaption><div class="tabs-content"><figure class="highlight cmd" style="display: block;"><table><tbody><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"><span class="built_in">cd</span> firstExpressApplication</span><br><span class="line">npm install</span><br></pre></td></tr></tbody></table></figure></div></figure><br>At this point we have a very simple Express application which we can launch by typing in the command window<br><figure class="codeblock codeblock--tabbed"><figcaption><span>Start express application</span><ul class="tabs"><li class="tab active">cmd</li></ul></figcaption><div class="tabs-content"><figure class="highlight cmd" style="display: block;"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">set</span> DEBUG=firstExpressApplication & node .\bin\www</span><br></pre></td></tr></tbody></table></figure></div></figure><br>After doing this just open a browser tab and navigate to the url: <a href="http://localhost:3000" target="_blank" rel="external">http://localhost:3000</a> and you should see the default express application running.</p>
<h4 id="Open-the-Express-application-from-Visual-Studio"><a href="#Open-the-Express-application-from-Visual-Studio" class="headerlink" title="Open the Express application from Visual Studio"></a>Open the Express application from Visual Studio</h4><p>Now is the most interesting part where we can open this application from visual studio further change it. After giving a name in the window that is shown in the picture above we press next and we are presented with a window like the one following where we should choose the folder that contains the application’s code.</p>
<div class="figure nocaption fig-100" style="width:;"><a class="fancybox" href="selectforlder.jpg" title="select folder" data-fancybox-group="vsnode"><img class="fig-img" src="selectforlder.jpg" alt="select folder"></a></div><div style="clear:both;"></div>
<p>After clicking next a window like the following is shown to us where we can choose which file should be executed when F5 is pressed.</p>
<div class="figure nocaption fig-100" style="width:;"><a class="fancybox" href="selectstartfile.jpg" title="select start file" data-fancybox-group="vsnode"><img class="fig-img" src="selectstartfile.jpg" alt="select start file"></a></div><div style="clear:both;"></div>
<p>Here is the small problem as it doesn’t give us the option to choose the bin\www file which contains the initialization logic. We have to manually change this after the Visual Studio project creation is finished. We are leaving the app.js file as selected and click next. The coming window is a great thought as it gives the flexibility of storing the Visual Studio project file in a different place than the original Express application. This means that we could even not add this file to source control and definitely it is not going to bother other people in the team that they don’t use Visual Studio.</p>
<div class="figure nocaption fig-100" style="width:;"><a class="fancybox" href="selectprojectlocation.jpg" title="select project location" data-fancybox-group="vsnode"><img class="fig-img" src="selectprojectlocation.jpg" alt="select project location"></a></div><div style="clear:both;"></div>
<h4 id="Fixing-the-problem-of-initial-file"><a href="#Fixing-the-problem-of-initial-file" class="headerlink" title="Fixing the problem of initial file"></a>Fixing the problem of initial file</h4><p>When the importing of the project is finished we can press F5 in order to achieve the same result as previously where we start the project from command line. But if we do this we will experience an error. A normal debugging session is starting and a command window with debugger details is shown but after a couple of seconds the window is disappeared and no application is present. This is due the starting file selection we made earlier. In order to fix this issue we need to edit the project and change the corresponding setting manually. We have to spot the <strong>StartupFile</strong> setting that is set in <strong>app.js</strong> and change it to <strong>bin\www</strong>. After saving the changes, reload the project and pressing F5 everything should work as expected.</p>
<p>You can find more details for node.js tools for visual studio in the <a href="https://nodejstools.codeplex.com/" target="_blank" rel="external">codeplex project</a></p>
<h3 id="node-js-and-Visual-Studio"><a href="#node-js-and-Visual-Studio" class="headerlink" title="node.js and Visual Studio"></a>node.js and Visual Studio</h3><p><a href="http://nodejs.org/">node.js</a> is a very popular platform which allows having Javacript executed on the server. This is what everybody reads when navigating on the <a href="http://nodejs.org/">official site</a>:<br><em>Node.js® is a platform built on Chrome’s JavaScript runtime for easily building fast, scalable network applications. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient, perfect for data-intensive real-time applications that run across distributed devices.</em><br>
ASP.NET - Create an OWIN middleware to trigger a permanent redirecthttp://xabikostest.github.io/2015/01/26/Create-an-OWIN-middleware-to-trigger-a-permanent-redirect/2015-01-26T22:15:00.000Z2016-05-08T18:40:11.291Z<h4 id="OWIN-and-project-Katana"><a href="#OWIN-and-project-Katana" class="headerlink" title="OWIN and project Katana"></a>OWIN and project Katana</h4><p><a href="http://owin.org/" target="_blank" rel="external">OWIN</a> (Open Web Iterface for .NET) is the new way of developing web applications in the .NET ecosystem. It is a great approach as it offers the flexibility of decoupling the application from the hosting environment itself. This means that as long as we develop a Web application on top of OWIN then we can easily host it outside the standard hosting environment so far which is IIS. A quick example is that by using a specific <a href="https://www.nuget.org/packages/Microsoft.Owin.SelfHost/" target="_blank" rel="external">nuget package</a>. As OWIN is just a specification then we need an implementation of this in each platform we want to support. The implementation for Microsoft’s platform is called <a href="http://www.asp.net/aspnet/overview/owin-and-katana/an-overview-of-project-katana" target="_blank" rel="external">Katana</a>.<br><a id="more"></a> </p>
<h4 id="OWIN-core-components"><a href="#OWIN-core-components" class="headerlink" title="OWIN core components"></a>OWIN core components</h4><p>OWIN has a very nice and easy to understand architecture as it is closer to HTTP protocol and doesn’t assume any functionality is there because of the hosting layer. All the manipulation has to do with the two main objects that is an HttpRequestMessage and HttpResponseMessage. This is a really good choice of abstracting the actual HTTP layer and it’s an architecture that is very familiar to developers from other platforms like <a href="http://nodejs.org/" target="_blank" rel="external">node.js</a>. On top of this another very interesting and well known pattern that exists also in <a href="http://expressjs.com/" target="_blank" rel="external">Express</a> framework is the middlewares. A middleware is a really simple piece of code that gets a request object as a parameter and can either transform this request and pass it to the next middleware if present or create a response and don’t allow the request to further execute on the server. So a web application could potentially consist of several middlewares that are executed one after the other.</p>
<h4 id="OWIN-middleware-details"><a href="#OWIN-middleware-details" class="headerlink" title="OWIN middleware details"></a>OWIN middleware details</h4><p>The bare minimum OWIN middleware could look like the code below which the only thing it does is to write some statements as diagnostic and lets the request to proceed by calling the next middleware in the pipeline. </p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Simple middleware example</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">MinimumMiddleware</span></span><br><span class="line">{</span><br><span class="line"> <span class="keyword">private</span> AppFunc _next;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Initialize</span>(<span class="params">AppFunc next</span>)</span><br><span class="line"> </span>{</span><br><span class="line"> _next = next;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">async</span> Task <span class="title">Invoke</span>(<span class="params">IDictionary<<span class="keyword">string</span>, <span class="keyword">object</span>> environment</span>)</span><br><span class="line"> </span>{</span><br><span class="line"> Debug.WriteLine(<span class="string">"Begin executing request in custom middleware"</span>);</span><br><span class="line"> <span class="keyword">await</span> next.Invoke(environment);</span><br><span class="line"> Debug.WriteLine(<span class="string">"End executing request in custom middleware"</span>);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>In order to use this middleware we have to register it in the StartUp class as below.</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Register middleware for usage</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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"><span class="keyword">public</span> <span class="keyword">partial</span> <span class="keyword">class</span> <span class="title">Startup</span> {</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Configuration</span>(<span class="params">IAppBuilder app</span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> customMiddleware = <span class="keyword">new</span> MinimumMiddleware();</span><br><span class="line"> app.Use(customMiddleware);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<h4 id="Trigger-a-redirect-from-a-middleware"><a href="#Trigger-a-redirect-from-a-middleware" class="headerlink" title="Trigger a redirect from a middleware"></a>Trigger a redirect from a middleware</h4><p>The implementation above gives us just a dictionary of string and object and into this dictionary exists all the useful info like the request itself. A better option is to derive from OwinMiddleware class that gives us access to all the request specific data in a strongly type manner through IOwinContext interface. In the code that follows we can see an example of triggering a permanent redirect from an OWIN middleware and don’t let the request to further processed by the application.</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Check url middleware</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">CheckUrlMiddleware</span> : <span class="title">OwinMiddleware</span></span><br><span class="line">{</span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">readonly</span> IUrlChecker _checker;</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="title">CheckLegacyUrlMiddleware</span>(<span class="params">OwinMiddleware next, IUrlChecker checker</span>) : <span class="title">base</span>(<span class="params">next</span>)</span><br><span class="line"> </span>{</span><br><span class="line"> _checker = checker;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">async</span> <span class="keyword">override</span> Task <span class="title">Invoke</span>(<span class="params">IOwinContext context</span>)</span><br><span class="line"> </span>{</span><br><span class="line"> </span><br><span class="line"> <span class="keyword">var</span> url = context.Request.Uri;</span><br><span class="line"> <span class="keyword">string</span> urlToRedirect = <span class="string">""</span>; </span><br><span class="line"> <span class="keyword">if</span> (_checker.NeedsPermanentRedirect(url.AbsoluteUri, <span class="keyword">out</span> urlToRedirect) )</span><br><span class="line"> {</span><br><span class="line"> <span class="comment">// 301 is the status code of permanent redirect</span></span><br><span class="line"> context.Response.StatusCode = <span class="number">301</span>;</span><br><span class="line"> context.Response.Headers.Set(<span class="string">"Location"</span>, urlToRedirect);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">else</span></span><br><span class="line"> {</span><br><span class="line"> <span class="keyword">await</span> Next.Invoke(context);</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>The IUrlChecker is just an Interface that the implementation of it contains all the business logic if a redirect should take place or not. I use it here also to demonstrate how we can inject dependencies in our middleware in the correct way. The piece of code below shows what we have to do in order this middleware to executed for every request.</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Register middleware for usage</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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"><span class="keyword">public</span> <span class="keyword">partial</span> <span class="keyword">class</span> <span class="title">Startup</span> {</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">Configuration</span>(<span class="params">IAppBuilder app</span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> urlChecker = DependencyResolver.Current.GetService<IUrlChecker>();</span><br><span class="line"> app.Use<CheckUrlMiddleware>(urlChecker); </span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<h4 id="OWIN-and-project-Katana"><a href="#OWIN-and-project-Katana" class="headerlink" title="OWIN and project Katana"></a>OWIN and project Katana</h4><p><a href="http://owin.org/">OWIN</a> (Open Web Iterface for .NET) is the new way of developing web applications in the .NET ecosystem. It is a great approach as it offers the flexibility of decoupling the application from the hosting environment itself. This means that as long as we develop a Web application on top of OWIN then we can easily host it outside the standard hosting environment so far which is IIS. A quick example is that by using a specific <a href="https://www.nuget.org/packages/Microsoft.Owin.SelfHost/">nuget package</a>. As OWIN is just a specification then we need an implementation of this in each platform we want to support. The implementation for Microsoft’s platform is called <a href="http://www.asp.net/aspnet/overview/owin-and-katana/an-overview-of-project-katana">Katana</a>.<br>
My participation in ItProDevConnections 2014http://xabikostest.github.io/2014/12/02/My-participation-in-ItProDevConnections-2014/2014-12-02T21:15:00.000Z2016-05-08T18:40:11.274Z<p>During last weekend I had the opportunity to attend <a href="http://www.itprodevconnections.gr/" target="_blank" rel="external">ItProDevConnection</a> for third time and second time in a row as public speaker. I have to say it was an amazing experience, I so enjoyed myself being part of a huge tech community. I met so many interesting people among else and heard about latest trends in development.<br><a id="more"></a> </p>
<h4 id="The-conference"><a href="#The-conference" class="headerlink" title="The conference"></a>The conference</h4><p><a href="http://www.itprodevconnections.gr/" target="_blank" rel="external">ItProDevConnection</a> is an annual conference that is organized by <a href="http://www.dotnetzone.gr/" target="_blank" rel="external">dotNETZone.gr</a>, <a href="http://autoexec.gr/" target="_blank" rel="external">autoexec.gr</a> and <a href="http://sqlschool.gr/" target="_blank" rel="external">SQLSchool.gr</a> which are some of the biggest technical communities in Greece. The main goal of the conference is to bring together software developers and IT professionals in one event, in order to share knowledge, expertise and of course to give an opportunity to meet some really smart and interesting people. During the event there are parallel sessions regarding IT, software development and some sessions related to both fields. In general is a high quality conference and for sure one of the biggest happening every year in Greece.</p>
<h4 id="Beginning-and-keynote"><a href="#Beginning-and-keynote" class="headerlink" title="Beginning and keynote"></a>Beginning and keynote</h4><p>The event begun on Saturday 29th of November early in the morning by registration of the attendees and an excellent keynote from <a href="https://twitter.com/@htsavdaris" target="_blank" rel="external">Harry Tsavdaris</a> which is a former member of technical communities and now is responsible for the Information Systems of the Ministry of Economics. He gave us a really nice insight about the problems a huge organization faces and especially the absolute need to be on-line and available under all circumstances. During the keynote the room was full as you can see in the following photo.</p>
<div class="figure nocaption fig-100" style="width:;"><a class="fancybox" href="keynote.jpg" title="Keynote" data-fancybox-group="itprodev"><img class="fig-img" src="keynote.jpg" alt="Keynote"></a></div><div style="clear:both;"></div>
<h4 id="My-session"><a href="#My-session" class="headerlink" title="My session"></a>My session</h4><p>This year I had the change to give a presentation for second time in a row and I was quite excited for this. Last year I spoke about <a href="http://www.visualstudio.com/en-us/products/what-is-visual-studio-online-vs.aspx" target="_blank" rel="external">Visual Studio Online</a> and Application Lifecycle Management by using <a href="http://git-scm.com/" target="_blank" rel="external">Git</a>. At that time the subject was really hot as Microsoft had just renamed Team Foundation Service to Visual Studio Online and the Git support was relatively new inside Visual Studio. </p>
<p>This time I chose to change subject completely and talk about <a href="http://msdn.microsoft.com/en-us/data/ef.aspx" target="_blank" rel="external">Entity Framework</a> and how we can use some of its advance features, like interceptors, to create a multitenant application. You can find more details about the subject in the series of my blog post I wrote recently <a href="http://xabikos.com/multitenant/application%20design/software%20as%20a%20service/2014/11/17/create-a-multitenant-application-with-entity-framework-code-first---part-1.html" target="_blank" rel="external">Part 1</a> <a href="http://xabikos.com/multitenant/application%20design/software%20as%20a%20service/2014/11/18/create-a-multitenant-application-with-entity-framework-code-first---part-2.html" target="_blank" rel="external">Part 2</a> <a href="http://xabikos.com/multitenant/application%20design/software%20as%20a%20service/2014/11/19/create-a-multitenant-application-with-entity-framework-code-first---part-3.html" target="_blank" rel="external">Part 3.</a> It took me a fair amount of time to prepare for the session but at the end I am very satisfied with the result as a lot of people were there to attend and got some good comments at the end. On top of this I think I gave some ideas on how we can use some not well known features of the framework in order to solve some not straightforward problems. At this point I would also like to say a huge THANKS to all the people were present during my session. You can see me in action during my presentation in the two pictures below.</p>
<div class="figure nocaption fig-50" style="width:;"><a class="fancybox" href="speaker1.jpg" title="My session" data-fancybox-group="itprodev"><img class="fig-img" src="speaker1.jpg" alt="My session"></a></div>
<div class="figure nocaption fig-50" style="width:;"><a class="fancybox" href="speaker2.jpg" title="my session" data-fancybox-group="itprodev"><img class="fig-img" src="speaker2.jpg" alt="my session"></a></div><div style="clear:both;"></div>
<iframe src="//www.slideshare.net/slideshow/embed_code/42890889" width="476" height="400" frameborder="0" allowfullscreen></iframe>
<h4 id="Networking-Socializing"><a href="#Networking-Socializing" class="headerlink" title="Networking - Socializing"></a>Networking - Socializing</h4><p>As last year I managed to meet some new really nice and smart people when not attending the technical sessions. I would like to highlight here that maybe this part of events is even more important than the technical knowledge you get there. We have the change to be among other people who share the same passion about development and technology in general. This year I was quite happy as I met many of the <a href="http://www.meetup.com/Thessaloniki-NET-Meetup/" target="_blank" rel="external">Thessaloniki .NET meetup</a> fellowship and we made the decision to further proceed with our meetings in the near future. You can get a sense of who we are in the following picture.</p>
<div class="figure nocaption fig-100" style="width:;"><a class="fancybox" href="netMeetup.jpg" title="net meetup" data-fancybox-group="itprodev"><img class="fig-img" src="netMeetup.jpg" alt="net meetup"></a></div><div style="clear:both;"></div>
<h4 id="End-of-the-event"><a href="#End-of-the-event" class="headerlink" title="End of the event"></a>End of the event</h4><p>On Sunday evening, after two very exciting days and tons of useful info we had to close the event and reschedule it for the next year. During the closing session many presents were given to the attendees and we took some beautiful pictures. In the most left one there are all the attendees with the speakers and organizers and in the right one just the speakers with the awesome stuff that helped with the organization. I am really looking forward for the next event. </p>
<div class="figure nocaption fig-50" style="width:;"><a class="fancybox" href="AllTogether1.jpg" title="all together" data-fancybox-group="itprodev"><img class="fig-img" src="AllTogether1.jpg" alt="all together"></a></div>
<div class="figure nocaption fig-50" style="width:;"><a class="fancybox" href="speakers1.jpg" title="speakers" data-fancybox-group="itprodev"><img class="fig-img" src="speakers1.jpg" alt="speakers"></a></div><div style="clear:both;"></div>
<p>During last weekend I had the opportunity to attend <a href="http://www.itprodevconnections.gr/">ItProDevConnection</a> for third time and second time in a row as public speaker. I have to say it was an amazing experience, I so enjoyed myself being part of a huge tech community. I met so many interesting people among else and heard about latest trends in development.<br>
Create a multitenant application with Entity Framework Code First - Part 3http://xabikostest.github.io/2014/11/19/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-3/2014-11-19T19:15:00.000Z2016-05-08T18:40:11.263Z<h4 id="Connection-with-previous-posts"><a href="#Connection-with-previous-posts" class="headerlink" title="Connection with previous posts"></a>Connection with previous posts</h4><p>This is the last post of the series of how we can use Entity Framework Code First to create a multitenant application. You are requested first to read <a href="/2014/11/17/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-1/">Part 1</a> where there is an introduction in the problem we are trying to solve and some infrastructure code required to continue. <a href="/2014/11/18/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-2/">Part 2</a> describes the query filtering that is happening automatically in the entire application. In this post I am going to show how we can use the CommandTree interceptor in order to modify the insert, update and delete commands. The idea of implement something like this came to my mind after watching <a href="http://romiller.com/" target="_blank" rel="external">Rowan Miller’s</a> excellent <a href="http://channel9.msdn.com/Events/TechEd/NorthAmerica/2014/DEV-B417#fbid=" target="_blank" rel="external">session</a> in North America TechEd, which I highly recommend you to watch.<br><a id="more"></a></p>
<hr>
<h4 id="Modification-of-insert-command"><a href="#Modification-of-insert-command" class="headerlink" title="Modification of insert command"></a>Modification of insert command</h4><p>Let’s start by presenting the code of insert command which is probably the simplest case. What we want to achieve is to always assign the correct TenantId when saving an entity that has this property. I have to remind here that Message class has a private set in TenantId property so there is no way to assign it from the code base.<br><figure class="codeblock codeblock--tabbed"><figcaption><span>Insert command interceptor</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">TenantCommandTreeInterceptor</span> : <span class="title">IDbCommandTreeInterceptor</span> {</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">TreeCreated</span>(<span class="params">DbCommandTreeInterceptionContext interceptionContext</span>) </span>{</span><br><span class="line"> <span class="keyword">if</span> (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace) {</span><br><span class="line"> <span class="comment">// Check that there is an authenticated user in this context</span></span><br><span class="line"> <span class="keyword">var</span> identity = Thread.CurrentPrincipal.Identity <span class="keyword">as</span> ClaimsIdentity;</span><br><span class="line"> <span class="keyword">if</span> (identity == <span class="keyword">null</span>){</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">var</span> userIdclaim = identity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);</span><br><span class="line"> <span class="keyword">if</span> (userIdclaim == <span class="keyword">null</span>) {</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">var</span> userId = userIdclaim.Value;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> insertCommand = interceptionContext.Result <span class="keyword">as</span> DbInsertCommandTree;</span><br><span class="line"> <span class="keyword">if</span> (insertCommand != <span class="keyword">null</span>) {</span><br><span class="line"> <span class="keyword">var</span> column = TenantAwareAttribute.GetTenantColumnName(insertCommand.Target.VariableType.EdmType);</span><br><span class="line"> <span class="keyword">if</span> (!<span class="keyword">string</span>.IsNullOrEmpty(column)) {</span><br><span class="line"> <span class="comment">// Create the variable reference in order to create the property</span></span><br><span class="line"> <span class="keyword">var</span> variableReference = DbExpressionBuilder.Variable(insertCommand.Target.VariableType,</span><br><span class="line"> insertCommand.Target.VariableName);</span><br><span class="line"> <span class="comment">// Create the property to which will assign the correct value</span></span><br><span class="line"> <span class="keyword">var</span> tenantProperty = DbExpressionBuilder.Property(variableReference, column);</span><br><span class="line"> <span class="comment">// Create the set clause, object representation of sql insert command</span></span><br><span class="line"> <span class="keyword">var</span> tenantSetClause =</span><br><span class="line"> DbExpressionBuilder.SetClause(tenantProperty, DbExpression.FromString(userId));</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Remove potential assignment of tenantId for extra safety</span></span><br><span class="line"> <span class="keyword">var</span> filteredSetClauses =</span><br><span class="line"> insertCommand.SetClauses.Cast<DbSetClause>()</span><br><span class="line"> .Where(sc => ((DbPropertyExpression)sc.Property).Property.Name != column);</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Construct the final clauses, object representation of sql insert command values</span></span><br><span class="line"> <span class="keyword">var</span> finalSetClauses =</span><br><span class="line"> <span class="keyword">new</span> ReadOnlyCollection<DbModificationClause></span><br><span class="line"> (<span class="keyword">new</span> List<DbModificationClause>(filteredSetClauses) {</span><br><span class="line"> tenantSetClause</span><br><span class="line"> });</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> newInsertCommand = <span class="keyword">new</span> DbInsertCommandTree(</span><br><span class="line"> insertCommand.MetadataWorkspace,</span><br><span class="line"> insertCommand.DataSpace,</span><br><span class="line"> insertCommand.Target,</span><br><span class="line"> finalSetClauses,</span><br><span class="line"> insertCommand.Returning);</span><br><span class="line"></span><br><span class="line"> interceptionContext.Result = newInsertCommand;</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure></p>
<p>The most important piece of code is where we create the set clause. To further explain this is an object representation of a SQL pair values like INSERT INTO TABLE (TenantId) VALUE (the value of tenantId). After doing this we filter the original collection of set clause and remove any possible existence of the same set clause. As a final step we create a new insert command by assigning the original values and replacing only the set clause. The interception ends by setting the result explicitly.</p>
<hr>
<h4 id="Modification-of-update-command"><a href="#Modification-of-update-command" class="headerlink" title="Modification of update command"></a>Modification of update command</h4><p>Now we have to modify any update command that is sent to the database and remove any change in the value of tenantId and add an extra where statement based on the tenantId. So after the interception any SQL update command is going to have an extra and statement like AND TenantId = ‘value of tenantId’.<br><figure class="codeblock codeblock--tabbed"><figcaption><span>Update command interceptor</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">TenantCommandTreeInterceptor</span> : <span class="title">IDbCommandTreeInterceptor</span> {</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">TreeCreated</span>(<span class="params">DbCommandTreeInterceptionContext interceptionContext</span>) </span>{</span><br><span class="line"> <span class="keyword">if</span> (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace) {</span><br><span class="line"> <span class="comment">// Check that there is an authenticated user in this context</span></span><br><span class="line"> <span class="keyword">var</span> identity = Thread.CurrentPrincipal.Identity <span class="keyword">as</span> ClaimsIdentity;</span><br><span class="line"> <span class="keyword">if</span> (identity == <span class="keyword">null</span>){</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">var</span> userIdclaim = identity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);</span><br><span class="line"> <span class="keyword">if</span> (userIdclaim == <span class="keyword">null</span>) {</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">var</span> userId = userIdclaim.Value;</span><br><span class="line"> <span class="keyword">var</span> updateCommand = interceptionContext.Result <span class="keyword">as</span> DbUpdateCommandTree;</span><br><span class="line"> <span class="keyword">if</span> (updateCommand != <span class="keyword">null</span>) {</span><br><span class="line"> <span class="keyword">var</span> column = TenantAwareAttribute.GetTenantColumnName(updateCommand.Target.VariableType.EdmType);</span><br><span class="line"> <span class="keyword">if</span> (!<span class="keyword">string</span>.IsNullOrEmpty(column)){</span><br><span class="line"> <span class="comment">// Create the variable reference in order to create the property</span></span><br><span class="line"> <span class="keyword">var</span> variableReference = DbExpressionBuilder.Variable(updateCommand.Target.VariableType,</span><br><span class="line"> updateCommand.Target.VariableName);</span><br><span class="line"> <span class="comment">// Create the property to which will assign the correct value</span></span><br><span class="line"> <span class="keyword">var</span> tenantProperty = DbExpressionBuilder.Property(variableReference, column);</span><br><span class="line"> <span class="comment">// Create the tenantId where predicate, object representation of sql where tenantId = value statement</span></span><br><span class="line"> <span class="keyword">var</span> tenantIdWherePredicate = DbExpressionBuilder.Equal(tenantProperty, DbExpression.FromString(userId));</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Remove potential assignment of tenantId for extra safety</span></span><br><span class="line"> <span class="keyword">var</span> filteredSetClauses =</span><br><span class="line"> updateCommand.SetClauses.Cast<DbSetClause>()</span><br><span class="line"> .Where(sc => ((DbPropertyExpression)sc.Property).Property.Name != column);</span><br><span class="line"></span><br><span class="line"> <span class="comment">// Construct the final clauses, object representation of sql insert command values</span></span><br><span class="line"> <span class="keyword">var</span> finalSetClauses =</span><br><span class="line"> <span class="keyword">new</span> ReadOnlyCollection<DbModificationClause>(<span class="keyword">new</span> List<DbModificationClause>(filteredSetClauses));</span><br><span class="line"></span><br><span class="line"> <span class="comment">// The initial predicate is the sql where statement</span></span><br><span class="line"> <span class="keyword">var</span> initialPredicate = updateCommand.Predicate;</span><br><span class="line"> <span class="comment">// Add to the initial statement the tenantId statement which translates in sql AND TenantId = 'value'</span></span><br><span class="line"> <span class="keyword">var</span> finalPredicate = initialPredicate.And(tenantIdWherePredicate);</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> newUpdateCommand = <span class="keyword">new</span> DbUpdateCommandTree(</span><br><span class="line"> updateCommand.MetadataWorkspace,</span><br><span class="line"> updateCommand.DataSpace,</span><br><span class="line"> updateCommand.Target,</span><br><span class="line"> finalPredicate,</span><br><span class="line"> finalSetClauses,</span><br><span class="line"> updateCommand.Returning);</span><br><span class="line"></span><br><span class="line"> interceptionContext.Result = newUpdateCommand;</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure></p>
<p>The first part of the code is exactly the same as the interception in insert command. The only difference here is that we don’t create another set clause but a predicate which is the object representation of the SQL And statement. We explicitly do a logical AND with the original predicate and assign the final predicate in the new update command we construct.</p>
<hr>
<h4 id="Modification-of-delete-command"><a href="#Modification-of-delete-command" class="headerlink" title="Modification of delete command"></a>Modification of delete command</h4><p>The last piece to finish the puzzle is to modify the delete command before travelling to the database. The goal is exactly the same with update command. We want to append an extra where SQL statement in all delete commands. The code is also the same as in update command.</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Delete command interceptor</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">TenantCommandTreeInterceptor</span> : <span class="title">IDbCommandTreeInterceptor</span> {</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">TreeCreated</span>(<span class="params">DbCommandTreeInterceptionContext interceptionContext</span>) </span>{</span><br><span class="line"> <span class="keyword">if</span> (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace) {</span><br><span class="line"> <span class="comment">// Check that there is an authenticated user in this context</span></span><br><span class="line"> <span class="keyword">var</span> identity = Thread.CurrentPrincipal.Identity <span class="keyword">as</span> ClaimsIdentity;</span><br><span class="line"> <span class="keyword">if</span> (identity == <span class="keyword">null</span>){</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">var</span> userIdclaim = identity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);</span><br><span class="line"> <span class="keyword">if</span> (userIdclaim == <span class="keyword">null</span>) {</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">var</span> userId = userIdclaim.Value;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> deleteCommand = interceptionContext.Result <span class="keyword">as</span> DbDeleteCommandTree;</span><br><span class="line"> <span class="keyword">if</span> (deleteCommand != <span class="keyword">null</span>){</span><br><span class="line"> <span class="keyword">var</span> column = TenantAwareAttribute.GetTenantColumnName(deleteCommand.Target.VariableType.EdmType);</span><br><span class="line"> <span class="keyword">if</span> (!<span class="keyword">string</span>.IsNullOrEmpty(column)){</span><br><span class="line"> <span class="comment">// Create the variable reference in order to create the property</span></span><br><span class="line"> <span class="keyword">var</span> variableReference = DbExpressionBuilder.Variable(deleteCommand.Target.VariableType,</span><br><span class="line"> deleteCommand.Target.VariableName);</span><br><span class="line"> <span class="comment">// Create the property to which will assign the correct value</span></span><br><span class="line"> <span class="keyword">var</span> tenantProperty = DbExpressionBuilder.Property(variableReference, column);</span><br><span class="line"> <span class="keyword">var</span> tenantIdWherePredicate = DbExpressionBuilder.Equal(tenantProperty, DbExpression.FromString(userId));</span><br><span class="line"></span><br><span class="line"> <span class="comment">// The initial predicate is the sql where statement</span></span><br><span class="line"> <span class="keyword">var</span> initialPredicate = deleteCommand.Predicate;</span><br><span class="line"> <span class="comment">// Add to the initial statement the tenantId statement which translates in sql AND TenantId = 'value'</span></span><br><span class="line"> <span class="keyword">var</span> finalPredicate = initialPredicate.And(tenantIdWherePredicate);</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> newDeleteCommand = <span class="keyword">new</span> DbDeleteCommandTree(</span><br><span class="line"> deleteCommand.MetadataWorkspace,</span><br><span class="line"> deleteCommand.DataSpace,</span><br><span class="line"> deleteCommand.Target,</span><br><span class="line"> finalPredicate);</span><br><span class="line"></span><br><span class="line"> interceptionContext.Result = newDeleteCommand;</span><br><span class="line"> <span class="keyword">return</span> ;</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>We create manually again a predicate and do a logical AND with the original predicate of the command. After this we creating a new delete command and assign it as the interception result. There is no need to create different interceptors class per command of course. We can combine all of them in just one class as you can see in <a href="https://github.com/xabikos/EfMultitenant/blob/master/Multitenant.Interception/Infrastructure/TenantCommandTreeInterceptor.cs" target="_blank" rel="external">this example</a>.</p>
<hr>
<h4 id="Final-thoughts"><a href="#Final-thoughts" class="headerlink" title="Final thoughts"></a>Final thoughts</h4><p>This was the last part of a series of posts. You can find the first part <a href="/2014/11/17/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-1/">here</a> and the second <a href="/2014/11/18/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-2/">here</a>. I hope that these posts will become useful to other developers as this is the way we solved the multi tenancy data access problem in the project I am currently working on. Any comments or thoughts to improve the code are more than welcome. As I mentioned in the previous posts I have a public <a href="https://github.com/xabikos/EfMultitenant/" target="_blank" rel="external">Github repository</a> that contains a full project with the demonstrated code.</p>
<h3 id="Part-1"><a href="#Part-1" class="headerlink" title="Part 1"></a><a href="/2014/11/17/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-1/">Part 1</a></h3><h3 id="Part-2"><a href="#Part-2" class="headerlink" title="Part 2"></a><a href="/2014/11/18/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-2/">Part 2</a></h3>
<h4 id="Connection-with-previous-posts"><a href="#Connection-with-previous-posts" class="headerlink" title="Connection with previous posts"></a>Connection with previous posts</h4><p>This is the last post of the series of how we can use Entity Framework Code First to create a multitenant application. You are requested first to read <a href="/2014/11/17/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-1/">Part 1</a> where there is an introduction in the problem we are trying to solve and some infrastructure code required to continue. <a href="/2014/11/18/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-2/">Part 2</a> describes the query filtering that is happening automatically in the entire application. In this post I am going to show how we can use the CommandTree interceptor in order to modify the insert, update and delete commands. The idea of implement something like this came to my mind after watching <a href="http://romiller.com/">Rowan Miller’s</a> excellent <a href="http://channel9.msdn.com/Events/TechEd/NorthAmerica/2014/DEV-B417#fbid=">session</a> in North America TechEd, which I highly recommend you to watch.<br>
Create a multitenant application with Entity Framework Code First - Part 2http://xabikostest.github.io/2014/11/18/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-2/2014-11-18T19:15:00.000Z2016-05-08T18:40:11.254Z<h4 id="A-short-introduction"><a href="#A-short-introduction" class="headerlink" title="A short introduction"></a>A short introduction</h4><p>In continuation of <a href="/2014/11/17/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-1/">Part 1</a> about creating a multitenant application with Entity Framework Code First we are going to see how we can use Interceptors to apply filtering when querying the data in a transparent way for our application. It is highly recommended to read the <a href="/2014/11/17/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-1/">first part</a> as this post assumes you are already familiar with the problem.<br><a id="more"></a><br>The idea behind this implementation came up based on two very nice projects in Github which try to give a generic solution to the filtering problem. The first project is called <a href="https://github.com/jbogard/EntityFramework.Filters/" target="_blank" rel="external">EntityFramework.Filters</a> and it was the first one from <a href="http://lostechies.com/jimmybogard/" target="_blank" rel="external">Jimmy Bogard</a> which has a NuGet <a href="https://www.nuget.org/packages/EntityFramework.Filters/" target="_blank" rel="external">package</a> as well. The second very similar project which solved a couple of issues is <a href="https://github.com/jcachat/EntityFramework.DynamicFilters/" target="_blank" rel="external">EntityFramework.DynamicFilters</a> from <a href="https://github.com/jcachat/" target="_blank" rel="external">jcachat</a> which also comes with a NuGet <a href="https://www.nuget.org/packages/EntityFramework.DynamicFilters/" target="_blank" rel="external">package</a>. I have to highlight here that both of the projects give a wider solution to query filtering with Entity Framework and for our solution we are going to use just the general idea of filtering.</p>
<hr>
<h4 id="Entity-Framework-interceptors"><a href="#Entity-Framework-interceptors" class="headerlink" title="Entity Framework interceptors"></a>Entity Framework interceptors</h4><p><a href="http://msdn.microsoft.com/en-us/data/dn469464.aspx#BuildingBlocks/" target="_blank" rel="external">Interceptors</a> is a very powerful mechanism that Entity Framework added in version 6 and allows us to write custom code and then injecting in the framework’s execution pipeline. We can use interceptors to extend or modify the functionality of Entity Framework. A very common scenario in to use interceptors for database activity logging as you can see in <a href="http://msdn.microsoft.com/en-us/data/dn469464.aspx#BuildingBlocks/" target="_blank" rel="external">this example</a>. For our purposes we will use interceptors to modify first all the query commands to the database and in the next part the insert, update and delete commands.</p>
<hr>
<h4 id="The-command-tree-interceptor"><a href="#The-command-tree-interceptor" class="headerlink" title="The command tree interceptor"></a>The command tree interceptor</h4><p>The first step is to implement the IDbCommandTreeInterceptor and the TreeCreated method it declares, in order to take control of the query send to the database. The TenantCommandTreeInterceptor class is available below:<br><figure class="codeblock codeblock--tabbed"><figcaption><span>Query command Interceptor</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">TenantCommandTreeInterceptor</span> : <span class="title">IDbCommandTreeInterceptor</span> {</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">TreeCreated</span>(<span class="params">DbCommandTreeInterceptionContext interceptionContext</span>) </span>{</span><br><span class="line"> <span class="keyword">if</span> (interceptionContext.OriginalResult.DataSpace == DataSpace.SSpace) {</span><br><span class="line"> <span class="comment">// Check that there is an authenticated user in this context</span></span><br><span class="line"> <span class="keyword">var</span> identity = Thread.CurrentPrincipal.Identity <span class="keyword">as</span> ClaimsIdentity;</span><br><span class="line"> <span class="keyword">if</span> (identity == <span class="keyword">null</span>){</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">var</span> userIdclaim = identity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);</span><br><span class="line"> <span class="keyword">if</span> (userIdclaim == <span class="keyword">null</span>) {</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="comment">// In case of query command change the query by adding a filtering based on tenantId</span></span><br><span class="line"> <span class="keyword">var</span> queryCommand = interceptionContext.Result <span class="keyword">as</span> DbQueryCommandTree;</span><br><span class="line"> <span class="keyword">if</span> (queryCommand != <span class="keyword">null</span>) {</span><br><span class="line"> <span class="keyword">var</span> newQuery = queryCommand.Query.Accept(<span class="keyword">new</span> TenantQueryVisitor());</span><br><span class="line"> interceptionContext.Result = <span class="keyword">new</span> DbQueryCommandTree(</span><br><span class="line"> queryCommand.MetadataWorkspace,</span><br><span class="line"> queryCommand.DataSpace,</span><br><span class="line"> newQuery);</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure></p>
<p>I will try to explain the piece of code even though is not one of easiest concept in .net framework. A <a href="http://msdn.microsoft.com/en-us/library/vstudio/ee789837(v=vs.100).aspx/" target="_blank" rel="external">command tree</a> in most cases is the equivalent of an <a href="http://msdn.microsoft.com/en-us/library/bb397951.aspx/" target="_blank" rel="external">expression tree</a> that was created by a LINQ statement and Entity Framework can understand. In our case the query command tree is an object model representation of a query as is explained in the <a href="http://msdn.microsoft.com/en-us/library/vstudio/ee789837(v=vs.100).aspx/" target="_blank" rel="external">msdn</a> documentation. If we would like to make it more clear a query command tree is an object representation of a SQL select statement with all required parameters.</p>
<p>Initially we try to get the the identity of the user and verify that is logged in by getting the ClaimTypes.NameIdentifier. If the user is not logged we shouldn’t proceed with the interception as our requirement is to filter the data per user. The next few lines of code are relatively simple as we first examine if the command is a query command and if this is the case we continue with the interception. We create the new query which contains the filtering by applying the <a href="http://en.wikipedia.org/wiki/Visitor_pattern/" target="_blank" rel="external">Visitor design pattern</a> and the next step is to explicitly set the Result property of the interceptionContext by creating a new DbQueryCommandTree and return as the interception has done.</p>
<hr>
<h4 id="The-TenantQueryVisitor-class"><a href="#The-TenantQueryVisitor-class" class="headerlink" title="The TenantQueryVisitor class"></a>The TenantQueryVisitor class</h4><p>Now it’s time to see how the Query visitor class looks like.</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Query expression visitor</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">TenantQueryVisitor</span>: <span class="title">DefaultExpressionVisitor</span> {</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> DbExpression <span class="title">Visit</span>(<span class="params">DbScanExpression expression</span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> column = TenantAwareAttribute.GetTenantColumnName(expression.Target.ElementType);</span><br><span class="line"></span><br><span class="line"> <span class="keyword">if</span> (!<span class="keyword">string</span>.IsNullOrEmpty(column)) {</span><br><span class="line"> <span class="comment">// Get the current expression</span></span><br><span class="line"> <span class="keyword">var</span> dbExpression = <span class="keyword">base</span>.Visit(expression);</span><br><span class="line"> <span class="comment">// Get the current expression binding</span></span><br><span class="line"> <span class="keyword">var</span> currentExpressionBinding = DbExpressionBuilder.Bind(dbExpression);</span><br><span class="line"> <span class="comment">// Create the variable reference in order to create the property</span></span><br><span class="line"> <span class="keyword">var</span> variableReference = DbExpressionBuilder.Variable(currentExpressionBinding.VariableType,</span><br><span class="line"> currentExpressionBinding.VariableName);</span><br><span class="line"> <span class="comment">// Create the property based on the variable in order to apply the equality</span></span><br><span class="line"> <span class="keyword">var</span> tenantProperty = DbExpressionBuilder.Property(variableReference, column);</span><br><span class="line"> <span class="comment">// Create the parameter which is an object representation of a sql parameter.</span></span><br><span class="line"> <span class="comment">// We have to create a parameter and not perform a direct comparison with Equal function for example</span></span><br><span class="line"> <span class="comment">// as this logic is cached per query and called only once</span></span><br><span class="line"> <span class="keyword">var</span> tenantParameter = DbExpressionBuilder.Parameter(tenantProperty.Property.TypeUsage,</span><br><span class="line"> TenantAwareAttribute.TenantIdFilterParameterName);</span><br><span class="line"> <span class="comment">// Apply the equality between property and parameter.</span></span><br><span class="line"> <span class="keyword">var</span> filterExpression = DbExpressionBuilder.Equal(tenantProperty, tenantParameter);</span><br><span class="line"> <span class="comment">// Apply the filtering to the initial query</span></span><br><span class="line"> <span class="keyword">return</span> DbExpressionBuilder.Filter(currentExpressionBinding, filterExpression);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">base</span>.Visit(expression);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>The code here requires some knowledge of entity framework internals but I will try to explain it a bit more even though there are multiple comments in the code. What we are doing here is that we get the initial query and storing it in currentExpressionBinding variable. After doing this we create another expression which the SQL equivalent is “originalQuery AND TenantId = @TenantIdParameter”. We could assign the value at this point and don’t use a SQL Parameter but this has a major problem as it’s highlighted in the comments. Internally Entity Framework caches the command tree by model as explained <a href="https://entityframework.codeplex.com/SourceControl/latest#src/EntityFramework/Infrastructure/Interception/IDbCommandTreeInterceptor.cs" target="_blank" rel="external">here</a> so if we apply the filtering at this point we will get back always the data for the first user accessed the application something that obvious wrong. This implementation detail adds the need of implementing another interceptor, that is in a lower level, and assign the SQL parameter value we created inside visitor class.</p>
<hr>
<h4 id="The-command-interceptor-class"><a href="#The-command-interceptor-class" class="headerlink" title="The command interceptor class"></a>The command interceptor class</h4><p>The command interceptor class is shown below:<br><figure class="codeblock codeblock--tabbed"><figcaption><span>Command Interceptor</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">internal</span> <span class="keyword">class</span> <span class="title">TenantCommandInterceptor</span> : <span class="title">IDbCommandInterceptor</span> {</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">NonQueryExecuting</span>(<span class="params">DbCommand command, DbCommandInterceptionContext<<span class="keyword">int</span>> interceptionContext</span>)</span>{</span><br><span class="line"> SetTenantParameterValue(command);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">NonQueryExecuted</span>(<span class="params">DbCommand command, DbCommandInterceptionContext<<span class="keyword">int</span>> interceptionContext</span>)</span>{}</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">ReaderExecuting</span>(<span class="params">DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext</span>)</span>{</span><br><span class="line"> SetTenantParameterValue(command);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">ReaderExecuted</span>(<span class="params">DbCommand command, DbCommandInterceptionContext<DbDataReader> interceptionContext</span>)</span>{}</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">ScalarExecuting</span>(<span class="params">DbCommand command, DbCommandInterceptionContext<<span class="keyword">object</span>> interceptionContext</span>)</span>{</span><br><span class="line"> SetTenantParameterValue(command);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">ScalarExecuted</span>(<span class="params">DbCommand command, DbCommandInterceptionContext<<span class="keyword">object</span>> interceptionContext</span>)</span>{}</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">SetTenantParameterValue</span>(<span class="params">DbCommand command</span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> identity = Thread.CurrentPrincipal.Identity <span class="keyword">as</span> ClaimsIdentity;</span><br><span class="line"> <span class="keyword">if</span> ((command == <span class="keyword">null</span>) || (command.Parameters.Count == <span class="number">0</span>) || identity == <span class="keyword">null</span>) {</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">var</span> userClaim = identity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);</span><br><span class="line"> <span class="keyword">if</span> (userClaim != <span class="keyword">null</span>) {</span><br><span class="line"> <span class="keyword">var</span> userId = userClaim.Value;</span><br><span class="line"> <span class="comment">// Enumerate all command parameters and assign the correct value in the one we added inside query visitor</span></span><br><span class="line"> <span class="keyword">foreach</span> (DbParameter param <span class="keyword">in</span> command.Parameters) {</span><br><span class="line"> <span class="keyword">if</span> (param.ParameterName != TenantAwareAttribute.TenantIdFilterParameterName)</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> param.Value = userId;</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure></p>
<p>Here the logic is simpler as we just have to find the SQL Parameter if present and assign the correct value based on the user identity. The IDbCommandInterceptor contains six methods but in our use case we have to intercept only the ones executing before the command is sent to the database. I want to highlight here that is important how we access the required tenantId which in our case is the userId and we can find it from user’s identity. Now that async operations are very common this code could potentially executed by a thread that didn’t start the entire procedure so we have to make sure we can still access the required info.</p>
<hr>
<h4 id="Add-interceptors-in-Entity-Framework-pipeline"><a href="#Add-interceptors-in-Entity-Framework-pipeline" class="headerlink" title="Add interceptors in Entity Framework pipeline"></a>Add interceptors in Entity Framework pipeline</h4><p>The last step is to make Entity Framework aware of the interceptors we added before. To accomplish this we must use one of the latest addition in Framework the <a href="http://msdn.microsoft.com/en-us/data/jj680699.aspx/" target="_blank" rel="external">DbConfiguration</a> class. We have to derive from this class and add the two interceptors as the code snippet below shows:<br><figure class="codeblock codeblock--tabbed"><figcaption><span>Entity Framework Configuration</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">EntityFrameworkConfiguration</span> : <span class="title">DbConfiguration</span> {</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="title">EntityFrameworkConfiguration</span>(<span class="params"></span>) </span>{</span><br><span class="line"> AddInterceptor(<span class="keyword">new</span> TenantCommandInterceptor());</span><br><span class="line"> AddInterceptor(<span class="keyword">new</span> TenantCommandTreeInterceptor());</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure></p>
<p>This class is very handy and powerful as we can do several configurations and is discovered automatically by Entity Framework. I want to note here that only one instance of a class deriving from DbConfiguration must exist per AppDomain.</p>
<hr>
<p>This was the second part of a series of three posts. You can find the first part <a href="/2014/11/17/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-1/">here</a>. I have created a <a href="https://github.com/xabikos/EfMultitenant/" target="_blank" rel="external">project in Github</a> that contains the full code in a relatively change model. In the next post I will describe how we can use interceptors to modify the insert, update and delete command.</p>
<h3 id="Part-1"><a href="#Part-1" class="headerlink" title="Part 1"></a><a href="/2014/11/17/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-1/">Part 1</a></h3><h3 id="Part-3"><a href="#Part-3" class="headerlink" title="Part 3"></a><a href="/2014/11/19/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-3/">Part 3</a></h3>
<h4 id="A-short-introduction"><a href="#A-short-introduction" class="headerlink" title="A short introduction"></a>A short introduction</h4><p>In continuation of <a href="/2014/11/17/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-1/">Part 1</a> about creating a multitenant application with Entity Framework Code First we are going to see how we can use Interceptors to apply filtering when querying the data in a transparent way for our application. It is highly recommended to read the <a href="/2014/11/17/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-1/">first part</a> as this post assumes you are already familiar with the problem.<br>
Create a multitenant application with Entity Framework Code First - Part 1http://xabikostest.github.io/2014/11/17/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-1/2014-11-17T22:15:00.000Z2016-05-08T18:40:11.240Z<p>A highly increasing request we have to serve as developers, especially after Software as a Service revolution, is to provide software that is able to handle individual users in one application by separate each user’s data. This feature is called <a href="http://en.wikipedia.org/wiki/Multitenancy" target="_blank" rel="external">Multitenancy</a> and there are several ways to achieve it. In this series of posts I will try to demonstrate how we can achieve the data isolation by using some advance features of Entity Framework.<br><a id="more"></a></p>
<hr>
<h4 id="The-really-simple-model"><a href="#The-really-simple-model" class="headerlink" title="The really simple model"></a>The really simple model</h4><p>The first part includes the description of the model used across the application. Lets assume we want to manage some Messages for our application and each logged in user should be able to access and modify only his personal messages. The Message is a classic <a href="http://en.wikipedia.org/wiki/Plain_Old_CLR_Object" target="_blank" rel="external">POCO</a> class that doesn’t have any Entity Framework specific code as you can see in the snippet below.<br><figure class="codeblock codeblock--tabbed"><figcaption><span>Message POCO</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Message</span> {</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">long</span> Id { <span class="keyword">get</span>; <span class="keyword">set</span>; }</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">string</span> TenantId { <span class="keyword">get</span>; <span class="keyword">set</span>; }</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">virtual</span> ApplicationUser User { <span class="keyword">get</span>; <span class="keyword">set</span>; }</span><br><span class="line"> [Required]</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">string</span> Description { <span class="keyword">get</span>; <span class="keyword">set</span>; }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure></p>
<p>We follow mainly the convention over configuration approach Entity Framework provides and the only explicit configuration we have to apply in our Message class is to declare TenantId as foreign key for User property by adding the code that follows in the DbContext class we are going to use for data access.<br><figure class="codeblock codeblock--tabbed"><figcaption><span>Entity configuration</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">OnModelCreating</span>(<span class="params">DbModelBuilder modelBuilder</span>) </span>{</span><br><span class="line"> <span class="keyword">base</span>.OnModelCreating(modelBuilder);</span><br><span class="line"></span><br><span class="line"> modelBuilder.Entity<Message>()</span><br><span class="line"> .HasRequired(m => m.User)</span><br><span class="line"> .WithMany()</span><br><span class="line"> .HasForeignKey(m => m.TenantId)</span><br><span class="line"> .WillCascadeOnDelete(<span class="keyword">true</span>);</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure></p>
<hr>
<h4 id="The-“manual”-approach"><a href="#The-“manual”-approach" class="headerlink" title="The “manual” approach"></a>The “manual” approach</h4><p>I will first implement an MVC Controller that includes the logic of filtering based on TenantId and assign the correct TenantId when creating a new message. The code we have to write is more or less like the snippet below:<br><figure class="codeblock codeblock--tabbed"><figcaption><span>Controller</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line">[Authorize]</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">MessagesController</span> : <span class="title">Controller</span> {</span><br><span class="line"> <span class="keyword">private</span> ApplicationDbContext db = <span class="keyword">new</span> ApplicationDbContext();</span><br><span class="line"></span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">string</span> UserId { <span class="keyword">get</span> { <span class="keyword">return</span> User.Identity.IsAuthenticated ? User.Identity.GetUserId() : <span class="keyword">string</span>.Empty; }}</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> ActionResult <span class="title">Index</span>(<span class="params"></span>) </span>{</span><br><span class="line"> <span class="comment">// Tenant specific query logic</span></span><br><span class="line"> <span class="keyword">var</span> messages = db.Messages.Include(m => m.User).Where(m => m.TenantId == UserId);</span><br><span class="line"> <span class="keyword">return</span> View(messages.ToList());</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> ActionResult <span class="title">Details</span>(<span class="params"><span class="keyword">long</span>? id</span>) </span>{</span><br><span class="line"> <span class="comment">// Tenant specific query logic</span></span><br><span class="line"> Message message = db.Messages.SingleOrDefault(m => m.Id == id && m.TenantId == UserId);</span><br><span class="line"> <span class="keyword">if</span> (message == <span class="keyword">null</span>) {</span><br><span class="line"> <span class="keyword">return</span> HttpNotFound();</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> View(message);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> ActionResult <span class="title">Create</span>(<span class="params">[Bind(Include = <span class="string">"Id,Description"</span></span>)] Message message) </span>{</span><br><span class="line"> <span class="keyword">if</span> (ModelState.IsValid) {</span><br><span class="line"> <span class="comment">// Assign tenant Id explicitly</span></span><br><span class="line"> message.TenantId = UserId;</span><br><span class="line"> db.Messages.Add(message);</span><br><span class="line"> db.SaveChanges();</span><br><span class="line"> <span class="keyword">return</span> RedirectToAction(<span class="string">"Index"</span>);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> View(message);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> ActionResult <span class="title">Edit</span>(<span class="params"><span class="keyword">long</span>? id</span>) </span>{</span><br><span class="line"> <span class="comment">// Tenant specific query logic</span></span><br><span class="line"> Message message = db.Messages.SingleOrDefault(m => m.Id == id && m.TenantId == UserId);</span><br><span class="line"> <span class="keyword">if</span> (message == <span class="keyword">null</span>) {</span><br><span class="line"> <span class="keyword">return</span> HttpNotFound();</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> View(message);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> ActionResult <span class="title">Edit</span>(<span class="params">[Bind(Include = <span class="string">"Id,Description"</span></span>)] Message message) </span>{</span><br><span class="line"> <span class="keyword">if</span> (ModelState.IsValid) {</span><br><span class="line"> <span class="comment">// Assign tenant Id explicitly</span></span><br><span class="line"> message.TenantId = UserId;</span><br><span class="line"> db.Entry(message).State = EntityState.Modified;</span><br><span class="line"> db.SaveChanges();</span><br><span class="line"> <span class="keyword">return</span> RedirectToAction(<span class="string">"Index"</span>);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> View(message);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure></p>
<p>I didn’t include all required logic and also removed the delete functionality but the problem of always remember to filter the correct data is obvious. On top of this we must assign the TenantId property explicitly as the user should not be able to do something like this. This approach is of course a valid solution but requires a lot of repetition of the same logic throughout our application something that is always error prone. On top of this the entire application has knowledge of the TenantId concept. We could solve this problem by creating a base class, something like base Repository or similar approach, and hide this detail there. This would definitely improve the design but still when the base class is not enough we have to remember to apply the filtering.</p>
<hr>
<h4 id="Entity-Framework-Interceptors"><a href="#Entity-Framework-Interceptors" class="headerlink" title="Entity Framework Interceptors"></a>Entity Framework Interceptors</h4><p><a href="http://msdn.microsoft.com/en-us/data/dn469464.aspx#BuildingBlocks" target="_blank" rel="external">Entity Framework Interceptors</a> is a very powerful feature added in version 6 of the framework and we can use them in order to hide the filtering and assign the correct TenantId in only one place. To be able to do that we must first write some infrastructure code.</p>
<hr>
<h4 id="TenantAwareAttribute-and-custom-convention"><a href="#TenantAwareAttribute-and-custom-convention" class="headerlink" title="TenantAwareAttribute and custom convention"></a>TenantAwareAttribute and custom convention</h4><p>The first step is to create an ordinary attribute class with which we can annotate our classes in order to get the Tenant functionality automatically. The code for the attribute class is shown below:</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Custom Attribute</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">[AttributeUsage(AttributeTargets.Class, AllowMultiple = <span class="keyword">false</span>)]</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">TenantAwareAttribute</span> : <span class="title">Attribute</span> {</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">const</span> <span class="keyword">string</span> TenantAnnotation = <span class="string">"TenantAnnotation"</span>;</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">const</span> <span class="keyword">string</span> TenantIdFilterParameterName = <span class="string">"TenantIdParameter"</span>;</span><br><span class="line"></span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">string</span> ColumnName { <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="title">TenantAwareAttribute</span>(<span class="params"><span class="keyword">string</span> columnName</span>) </span>{</span><br><span class="line"> ColumnName = columnName;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">string</span> <span class="title">GetTenantColumnName</span>(<span class="params">EdmType type</span>) </span>{</span><br><span class="line"> MetadataProperty annotation = type.MetadataProperties.SingleOrDefault(</span><br><span class="line"> p => p.Name.EndsWith(<span class="keyword">string</span>.Format(<span class="string">"customannotation:{0}"</span>, TenantAnnotation)));</span><br><span class="line"></span><br><span class="line"> <span class="keyword">return</span> annotation == <span class="keyword">null</span> ? <span class="keyword">null</span> : (<span class="keyword">string</span>)annotation.Value;</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>When using this attribute we have to declare which property of the class is the one responsible for TenantId. Moreover exposes a static helper method to get the the tenant column name based on the EdmType.</p>
<p>The next step is to use this attribute by adding a custom <a href="http://msdn.microsoft.com/en-us/data/jj819164.aspx" target="_blank" rel="external">Entity Framework convention</a> to the DbContext class we are going to use for data access in our application. To do this we have to add the code snippet below on the DbContext class.</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Add attribute to configuration</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">protected</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">OnModelCreating</span>(<span class="params">DbModelBuilder modelBuilder</span>) </span>{</span><br><span class="line"> <span class="keyword">base</span>.OnModelCreating(modelBuilder);</span><br><span class="line"></span><br><span class="line"> modelBuilder.Entity<Message>()</span><br><span class="line"> .HasRequired(m => m.User)</span><br><span class="line"> .WithMany()</span><br><span class="line"> .HasForeignKey(m => m.TenantId)</span><br><span class="line"> .WillCascadeOnDelete(<span class="keyword">true</span>);</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> conv = <span class="keyword">new</span> AttributeToTableAnnotationConvention<TenantAwareAttribute, <span class="keyword">string</span>>(</span><br><span class="line"> TenantAwareAttribute.TenantAnnotation, (type, attributes) => attributes.Single().ColumnName);</span><br><span class="line"></span><br><span class="line"> modelBuilder.Conventions.Add(conv);</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<hr>
<h4 id="Changes-in-Message-class"><a href="#Changes-in-Message-class" class="headerlink" title="Changes in Message class"></a>Changes in Message class</h4><p>After creating this infrastructure code the Message class can change and decorate it with the TenantAwareAttribute attribute as below:</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>Changed Message POCO</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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></pre></td><td class="code"><pre><span class="line">[TenantAware(<span class="string">"TenantId"</span>)]</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">Message</span> {</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">long</span> Id { <span class="keyword">get</span>; <span class="keyword">set</span>; }</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">string</span> TenantId { <span class="keyword">get</span>; <span class="keyword">private</span> <span class="keyword">set</span>; }</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">virtual</span> ApplicationUser User { <span class="keyword">get</span>; <span class="keyword">set</span>; }</span><br><span class="line"> [Required]</span><br><span class="line"> <span class="keyword">public</span> <span class="keyword">string</span> Description { <span class="keyword">get</span>; <span class="keyword">set</span>; }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>As we can see here there is another important change in the class. The TenantId property now is private set which means we can’t explicitly assign it from our code base. The last issue is quite important as we are not able to assign an invalid TenantId by mistake. Furthermore we don’t have to take care of assign a TenantId at all.</p>
<hr>
<p>This was the first part of a series of three posts. It includes the problem and the infrastructure code for what is coming on the next posts. For those that can’t wait I have created a <a href="https://github.com/xabikos/EfMultitenant" target="_blank" rel="external">project in Github</a> that contains the full code in a relatively change model. In the next post I will describe how we can use the code we already created to apply filtering based on TenantId always in a transparent way for our application.</p>
<h3 id="Part-2"><a href="#Part-2" class="headerlink" title="Part 2"></a><a href="/2014/11/18/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-2/">Part 2</a></h3><h3 id="Part-3"><a href="#Part-3" class="headerlink" title="Part 3"></a><a href="/2014/11/19/Create-a-multitenant-application-with-Entity-Framework-Code-First-Part-3/">Part 3</a></h3>
<p>A highly increasing request we have to serve as developers, especially after Software as a Service revolution, is to provide software that is able to handle individual users in one application by separate each user’s data. This feature is called <a href="http://en.wikipedia.org/wiki/Multitenancy">Multitenancy</a> and there are several ways to achieve it. In this series of posts I will try to demonstrate how we can achieve the data isolation by using some advance features of Entity Framework.<br>
ASP.NET User confirmed email filter attributehttp://xabikostest.github.io/2014/11/05/user-confirmed-filter-attribute/2014-11-05T19:00:00.000Z2016-05-08T18:40:11.216Z<p><a href="https://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs/" target="_blank" rel="external">Action filters</a> is a very powerful mechanism in an ASP.NET MVC application that gives us the capability of injecting functionality in our application in a centralized and structure way.<br>In this post I am showing how we can create an action filter attribute in order to decorate our controllers to check if the current user has verified his email address<br>after registering in our system through new ASP.NET <a href="http://www.asp.net/identity" target="_blank" rel="external">Identity system</a>. I am going to create two filters as we want to have this functionality in regular MVC controllers and in Web Api controllers as well.</p>
<p>First lets see the code for the regular MVC controllers. What we have to do is just derive from ActionFilterAttribute class that lives in System.Web.Mvc namespace and override the OnActionExecuting method.<br><figure class="codeblock codeblock--tabbed"><figcaption><span>UserConfirmedFilterAttribute</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = <span class="keyword">true</span>, Inherited = <span class="keyword">true</span>)]</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">UserConfirmedFilterAttribute</span> : <span class="title">ActionFilterAttribute</span> {</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> <span class="keyword">void</span> <span class="title">OnActionExecuting</span>(<span class="params">ActionExecutingContext filterContext</span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> userId = filterContext.HttpContext.User.Identity.GetUserId();</span><br><span class="line"> <span class="comment">// User is not logged in so redirect him to log in controller action</span></span><br><span class="line"> <span class="keyword">if</span> (<span class="keyword">string</span>.IsNullOrEmpty(userId)) {</span><br><span class="line"> filterContext.Result = <span class="keyword">new</span> RedirectToRouteResult(<span class="keyword">new</span> RouteValueDictionary(</span><br><span class="line"> <span class="keyword">new</span> { controller = <span class="string">"Account"</span>, action = <span class="string">"Login"</span>, </span><br><span class="line"> returnUrl = filterContext.HttpContext.Request.RawUrl }));</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> userManager = filterContext.HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();</span><br><span class="line"> <span class="keyword">if</span> (!userManager.IsEmailConfirmed(userId)) {</span><br><span class="line"> filterContext.Result =</span><br><span class="line"> <span class="keyword">new</span> RedirectToRouteResult(</span><br><span class="line"> <span class="keyword">new</span> RouteValueDictionary(<span class="keyword">new</span> { controller = <span class="string">"ConstrollerNameToRedirect"</span>, </span><br><span class="line"> action = <span class="string">"ActionMethodToRedirect"</span> }));</span><br><span class="line"> <span class="keyword">return</span>;</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">base</span>.OnActionExecuting(filterContext);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure></p>
<p>The code is very simple as in the case the user has confirmed the email the execution flow continues normally. In the opposite case we are able to redirect the user<br>in a specific action of a controller by replacing the corresponding values.</p>
<p>The code is very similar for Web Api controllers as we can see right below.</p>
<figure class="codeblock codeblock--tabbed"><figcaption><span>UserConfirmedFilterAttribute</span><ul class="tabs"><li class="tab active">cs</li></ul></figcaption><div class="tabs-content"><figure class="highlight cs" style="display: block;"><table><tbody><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><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = <span class="keyword">true</span>, Inherited = <span class="keyword">true</span>)]</span><br><span class="line"><span class="keyword">public</span> <span class="keyword">class</span> <span class="title">UserConfirmedWebApiFilterAttribute</span> : <span class="title">ActionFilterAttribute</span> {</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">override</span> Task <span class="title">OnActionExecutingAsync</span>(<span class="params">HttpActionContext actionContext, CancellationToken cancellationToken</span>) </span>{</span><br><span class="line"> <span class="keyword">var</span> userId = actionContext.RequestContext.Principal.Identity.GetUserId();</span><br><span class="line"> <span class="comment">// User is not logged in so redirect him to log in controller action</span></span><br><span class="line"> <span class="keyword">if</span> (<span class="keyword">string</span>.IsNullOrEmpty(userId)) {</span><br><span class="line"> actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized,</span><br><span class="line"> <span class="string">"You must be logged in to access this resource"</span>);</span><br><span class="line"> <span class="keyword">return</span> Task.FromResult(<span class="number">0</span>);</span><br><span class="line"> }</span><br><span class="line"></span><br><span class="line"> <span class="keyword">var</span> userManager = actionContext.Request.GetOwinContext().GetUserManager<ApplicationUserManager>();</span><br><span class="line"> <span class="keyword">if</span> (!userManager.IsEmailConfirmed(userId)) {</span><br><span class="line"> actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest,</span><br><span class="line"> <span class="string">"You must be verify your email address in order to access this resource"</span>);</span><br><span class="line"> <span class="keyword">return</span> Task.FromResult(<span class="number">0</span>);</span><br><span class="line"> }</span><br><span class="line"> <span class="keyword">return</span> <span class="keyword">base</span>.OnActionExecutingAsync(actionContext, cancellationToken);</span><br><span class="line"> }</span><br><span class="line">}</span><br></pre></td></tr></tbody></table></figure></div></figure>
<p>Here I choose to implement the async version of OnActionExecuting method. If the user has confirmed the email address then the request is served normally.<br>If the user is not logged in or has not confirmed the email a bad request response is returned containing the additional message.</p>
<p>You can find a complete <a href="https://github.com/xabikos/ActionFilters" target="_blank" rel="external">project</a> containing both of the attributes on Github.</p>
<p><a href="https://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/understanding-action-filters-cs/" target="_blank" rel=