{"@attributes":{"version":"2.0"},"channel":{"title":"Adam Tibi","description":"My blog where I share my software experience and what I encounter in different projects","link":"https:\/\/adamtibi.net\/","pubDate":"Mon, 03 Oct 2022 10:37:19 +0000","lastBuildDate":"Mon, 03 Oct 2022 10:37:19 +0000","generator":"Jekyll v3.9.2","item":[{"title":"Pragmatic Deep Learning Model for Forex Forecasting with Multi-Step Prediction","description":"<figure>\n<img src=\"\/assets\/artefacts\/2020\/10\/multi-step-prediction.png\" srcset=\"\/assets\/artefacts\/2020\/10\/multi-step-prediction@4x.png 4x, \/assets\/artefacts\/2020\/10\/multi-step-prediction@3x.png 3x, \/assets\/artefacts\/2020\/10\/multi-step-prediction@2x.png 2x, \/assets\/artefacts\/2020\/10\/multi-step-prediction.png\" alt=\"A graph showing GBPUSD with a multi-step prediction on the price movement\" \/>\n<\/figure>\n\n<p>This is my post on Towards AI on building an LSTM Deep Learning model that can predict the market:<\/p>\n\n<p><a href=\"https:\/\/medium.com\/towards-artificial-intelligence\/pragmatic-deep-learning-model-for-forex-forecasting-569aae6d4a1a\" target=\"_blank\">Pragmatic Deep Learning Model for Forex Forecasting: Using LSTM and TensorFlow on the GBPUSD Time Series for multi-step prediction<\/a><\/p>\n\n<!--more-->\n","pubDate":"Thu, 08 Oct 2020 17:44:00 +0000","link":"https:\/\/adamtibi.net\/10-2020\/pragmatic-deep-learning-model-for-forex-forecasting-multi-step-prediction","guid":"https:\/\/adamtibi.net\/10-2020\/pragmatic-deep-learning-model-for-forex-forecasting-multi-step-prediction","category":["Machine Learning","LSTM","Forex","Deep Learning","Uncategorized"]},{"title":"The day when the software industry makes its mind","description":"<figure>\n<img src=\"\/assets\/artefacts\/2019\/07\/confused.png\" srcset=\"\/assets\/artefacts\/2019\/07\/confused@4x.png 4x, \/assets\/artefacts\/2019\/07\/confused@3x.png 3x, \/assets\/artefacts\/2019\/07\/confused@2x.png 2x, \/assets\/artefacts\/2019\/07\/confused.png\" alt=\"A confused man with multiple directions in front of him\" \/>\n<\/figure>\n\n<p>In year 2000 I started writing code professionally while at uni, before that I was writing code as a hobby. I\u00a0was\u00a0fascinated\u00a0by all the best practices I should follow: I shouldn\u2019t use HTML tables for design; they are horrible, I shouldn\u2019t write JavaScript inside my HTML I should do it obtrusively, I should not do database business logic in my code, I would violate the separation layers and I will mix business logic with database logic etc\u2026 Fast forward two decades later, I learned to take everything I hear with a pinch of salt!<\/p>\n\n<h2 id=\"the-do-it-dont-do-it-dont-approach\">The Do it, Don\u2019t, Do it, Don\u2019t Approach<\/h2>\n<p>They tell you do it; it is good; they tell you not; it isn\u2019t then they change their mind a few years later, then again and again.<\/p>\n\n<h3 id=\"writing-server-side-code-in-your-html\">Writing server-side code in your HTML<\/h3>\n\n<!--more-->\n\n<p>When I was a hobbyist, I liked ASP and how you can write some code that is then transformed magically into HTML. You write a bit of HTML tangled with a bit of code and life was cool.<\/p>\n\n<p>ASP.NET Webforms came along and the major advice, <strong>DO NOT<\/strong> write code in your HTML, write it in the <em>code-behind<\/em> otherwise you would be violating the separation of concerns!<\/p>\n\n<p>ASP.NET MVC came with Razor pages and the advice was \u201cwrite a bit of C# code,\u201d it is ok, sorry for the previous advice, but don\u2019t overdo it and be a good boy.<\/p>\n\n<p>Single Page Applications (SPA), <strong>DO NOT<\/strong> write any code in your HTML, better not even dealing with that, let the client deal with it, what were you thinking?!<\/p>\n\n<h3 id=\"mixing-database-queries-with-business-logic\">Mixing database queries with business logic<\/h3>\n\n<p>Writing database logic inside your code would violate the separation of concerns. One of the reason of failures of applications such as MS FoxPro and MS Access was this. Writing stored procedures for your business logic are even worse (please don\u2019t shoot the messenger) because you are scattering your business logic on multiple layers (and million other reasons).<\/p>\n\n<p>Later on, the Object Relational Frameworks (ORMs) such as Hibernate (Java), Active Record (Ruby on Rails) and Entity Framework (.NET) came along! Now writing database logic inside your code is fine again! But you don\u2019t call it \u201cdatabase operations\u201d anymore, otherwise you become uncool.<\/p>\n\n<h3 id=\"designing-with-tables\">Designing with tables<\/h3>\n\n<p>Prior to 2003, if you were to write a web page, you probably would use HTML tables to control your layout. Then the CSS started becoming more supported and the advice changed; <strong>DO NOT<\/strong> use tables for layout and you could find blogs of over 10 reasons of why you shouldn\u2019t do it.<\/p>\n\n<p>Bootstrap and later on CSS Flexbox came along, you know what, they have <strong>Grid<\/strong>, not <strong>Table<\/strong>, Grids are fine, even though the used CSS classes are called <code class=\"language-plaintext highlighter-rouge\">row<\/code> and <code class=\"language-plaintext highlighter-rouge\">col<\/code> and now grids are fine!<\/p>\n\n<h3 id=\"unobtrusive\">Unobtrusive<\/h3>\n\n<p>When Netscape introduced JavaScript, developers used to write JavaScript events mixed with HTML, the button will have an <code class=\"language-plaintext highlighter-rouge\">onclick<\/code> and then the JavaScript code. Then jQuery came along with the <strong>unobtrusive<\/strong> concept (I like this keyword and I learned to pronounce it quickly without stuttering) and now dare you say to a front-end developer to write JS code inside HTML.<\/p>\n\n<p>Years went by, jQuery became uncool and now the Single Page Application frameworks (React, Angular, Vue, etc\u2026) came to the rescue. And guess what, you are better using JavaScript or framework-specific keywords inside HTML and now it is ok, think <code class=\"language-plaintext highlighter-rouge\">(click)=\"onClickMe()\"<\/code> in Angular, we were kidding when we\u2019ve said obtrusive JS is bad!<\/p>\n\n<h3 id=\"you-should-not-be-using-flash-or-silverlight-or-else\">You should not be using Flash or Silverlight, or else!<\/h3>\n\n<p>Flash and Silverlight suddenly became bad practice, as they require a plugin to work in the browser and the advice became not to use them because you should be using HTML5. Ok, I got it, plugins are bad, I would not encourage using them. Years later <a href=\"https:\/\/webassembly.org\" target=\"_blank\">Web Assembly<\/a> came along.<\/p>\n\n<p>Did you know, you are allowed to write code that executes as a web assembly, all the stuff we said about plugins are no longer relevant. Writing non-JS code in the browser is fine again, such a wonderful world :)<\/p>\n\n<h3 id=\"conclusion\">Conclusion<\/h3>\n\n<p>The irony is that I agree with the logic change and why things went in the other direction, it all make sense to me. Today, what I\u2019ve learned is to always have an open mind for change where it makes sense and to have more flexible opinion in my technical discussions, as every thing will change later on.<\/p>\n\n","pubDate":"Mon, 29 Jul 2019 07:44:00 +0000","link":"https:\/\/adamtibi.net\/07-2019\/the-day-when-the-software-industry-makes-its-mind","guid":"https:\/\/adamtibi.net\/07-2019\/the-day-when-the-software-industry-makes-its-mind","category":["CodeProject","Software","Best Practices","Uncategorized"]},{"title":"Ten software keywords that make you look smarter","description":"<figure>\n<img src=\"\/assets\/artefacts\/2014\/09\/look-smarter.jpg\" alt=\"A guy with a thick eye glasses and nerd look\" \/>\n<\/figure>\n\n<p>They say the coat doesn\u2019t make the man, I say the right quote can make a developer punch above the waistline. In this post, I selected a group of my favourite keywords which make me smile and think \u201cnerd\u201d every time I hear one.<br \/>\n<!--more--><\/p>\n\n<h2 id=\"1--the-god-function\">1 \u2013 The God Function<\/h2>\n\n<p>This is the all-in-one function (method). It is one function that does everything, is it like 100 lines or more. Obviously, writing a God Function contradicts with clean and readable code principles and usually the people guilty of using it are beginners and pros coming from other domains (like mathematicians).<\/p>\n\n<p>This term is usually used in a sarcastic way to mock a function that is long and needs refactoring.<\/p>\n\n<h2 id=\"2--vertical-concerns\">2 \u2013 Vertical Concerns<\/h2>\n\n<p>It is a concern not directly related to the piece of code that you write. So, when you are writing some code to save a user info in the database, logging the event and notifying other systems that a record has been added are mostly vertical concerns.<\/p>\n\n<p>Vertical concerns are usually dealt with in C# with attributes, Membership Provider attributes are a good example.<\/p>\n\n<h2 id=\"3--cross-cutting-concerns\">3 \u2013 Cross-Cutting Concerns<\/h2>\n\n<p>Quoting from Wikipedia:<\/p>\n\n<blockquote>\n  <p>Cross-cutting concerns are aspects of a program that affect other concerns. These concerns often cannot be cleanly decomposed from the rest of the system in both the design and implementation, and can result in either scattering (code duplication), tangling (significant dependencies between systems), or both.<\/p>\n\n  <p>For instance, if writing an application for handling medical records, the indexing of such records is a core concern, while logging a history of changes to the record database or user database, or an authentication system, would be cross-cutting concerns since they touch more parts of the program.<\/p>\n<\/blockquote>\n\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Cross-cutting_concern\" target=\"_blank\">https:\/\/en.wikipedia.org\/wiki\/Cross-cutting_concern<\/a><\/p>\n\n<h2 id=\"4--hateoas\">4 \u2013 HATEOAS<\/h2>\n\n<p>Quoting from Wikipedia:<\/p>\n\n<blockquote>\n  <p>HATEOAS, an abbreviation for Hypermedia as the Engine of Application State, is a constraint of the REST application architecture that distinguishes it from most other network application architectures. The principle is that a client interacts with a network application entirely through hypermedia provided dynamically by application servers. A REST client needs no prior knowledge about how to interact with any particular application or server beyond a generic understanding of hypermedia. By contrast, in a service-oriented architecture (SOA), clients and servers interact through a fixed interface shared through documentation or an interface description language (IDL).<\/p>\n\n  <p>The HATEOAS constraint decouples client and server in a way that allows the server functionality to evolve independently.<\/p>\n<\/blockquote>\n\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/HATEOAS\" target=\"_blank\">https:\/\/en.wikipedia.org\/wiki\/HATEOAS<\/a><\/p>\n\n<p>I first heard this term long time ago (2009?) from <a href=\"https:\/\/jimwebber.org\/\" target=\"_blank\">Jim Webber<\/a> when I was attending an event on REST.<\/p>\n\n<h2 id=\"5--ubiquitous-language\">5 \u2013 Ubiquitous Language<\/h2>\n\n<p>Quoting from Martin Fowler:<\/p>\n\n<blockquote>\n  <p>Ubiquitous Language is the term Eric Evans uses in Domain Driven Design for the practice of building up a common, rigorous language between developers and users. This language should be based on the Domain Model used in the software \u2013 hence the need for it to be rigorous, since software doesn\u2019t cope well with ambiguity.<\/p>\n<\/blockquote>\n\n<p><a href=\"https:\/\/martinfowler.com\/bliki\/UbiquitousLanguage.html\" target=\"_blank\">https:\/\/martinfowler.com\/bliki\/UbiquitousLanguage.html<\/a><\/p>\n\n<h2 id=\"6--fluent-interface\">6 \u2013 Fluent Interface<\/h2>\n\n<p>Quoting from Wikipedia:<\/p>\n\n<blockquote>\n  <p>A fluent interface (as first coined by Eric Evans and Martin Fowler) is an implementation of an object oriented API that aims to provide for more readable code.<\/p>\n\n  <p>A fluent interface is normally implemented by using method cascading (concretely method chaining) to relay the instruction context of a subsequent call (but a fluent interface entails more than just method chaining). Generally, the context is defined through the return value of a called method self-referential, where the new context is equivalent to the last context terminated through the return of a void context.<\/p>\n<\/blockquote>\n\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Fluent_interface\" target=\"_blank\">https:\/\/en.wikipedia.org\/wiki\/Fluent_interface<\/a><\/p>\n\n<p>A theoretical example of a fluent interface usage would be something like:<br \/>\n<code class=\"language-plaintext highlighter-rouge\">member.Name(\"Adam\").Country(\"England\").City(\"London\");<\/code><\/p>\n\n<h2 id=\"7--optimistic-concurrency-control\">7 \u2013 Optimistic Concurrency Control<\/h2>\n\n<p>Quoting from Wikipedia:<\/p>\n\n<blockquote>\n  <p>Optimistic concurrency control (OCC) is a concurrency control method applied to transactional systems such as relational database management systems and software transactional memory. OCC assumes that multiple transactions can frequently complete without interfering with each other. While running, transactions use data resources without acquiring locks on those resources. Before committing, each transaction verifies that no other transaction has modified the data it has read. If the check reveals conflicting modifications, the committing transaction rolls back and can be restarted. Optimistic concurrency control was first proposed by H.T. Kung.<\/p>\n\n  <p>OCC is generally used in environments with low data contention. When conflicts are rare, transactions can complete without the expense of managing locks and without having transactions wait for other transactions\u2019 locks to clear, leading to higher throughput than other concurrency control methods. However, if contention for data resources is frequent, the cost of repeatedly restarting transactions hurts performance significantly; it is commonly thought that other concurrency control methods have better performance under these conditions. However, locking-based (\u201cpessimistic\u201d) methods also can deliver poor performance because locking can drastically limit effective concurrency even when deadlocks are avoided.<\/p>\n<\/blockquote>\n\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Optimistic_concurrency_control\" target=\"_blank\">https:\/\/en.wikipedia.org\/wiki\/Optimistic_concurrency_control<\/a><\/p>\n\n<h2 id=\"8--cyclomatic-complexity\">8 \u2013 Cyclomatic Complexity<\/h2>\n\n<p>Quoting from Wikipedia:<\/p>\n\n<blockquote>\n  <p>Cyclomatic complexity is a software metric (measurement). It was developed by Thomas J. McCabe, Sr. in 1976 and is used to indicate the complexity of a program. It is a quantitative measure of the complexity of programming instructions. It directly measures the number of linearly independent paths through a program\u2019s source code.<\/p>\n\n  <p>Cyclomatic complexity is computed using the control flow graph of the program: the nodes of the graph correspond to indivisible groups of commands of a program, and a directed edge connects two nodes if the second command might be executed immediately after the first command. Cyclomatic complexity may also be applied to individual functions, modules, methods or classes within a program.<\/p>\n\n  <p>One testing strategy, called basis path testing by McCabe who first proposed it, is to test each linearly independent path through the program; in this case, the number of test cases will equal the cyclomatic complexity of the program.<\/p>\n<\/blockquote>\n\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Cyclomatic_complexity\" target=\"_blank\">https:\/\/en.wikipedia.org\/wiki\/Cyclomatic_complexity<\/a><\/p>\n\n<p>I was first introduced to this term by ReSharper when a legacy code showed as high cyclomatic complexity.<\/p>\n\n<h2 id=\"9--responsive-web-design\">9 \u2013 Responsive Web Design<\/h2>\n\n<p>Quoting from Wikipedia:<\/p>\n\n<blockquote>\n  <p>Responsive web design (RWD) is a web design approach aimed at crafting sites to provide an optimal viewing experience\u2014easy reading and navigation with a minimum of resizing, panning, and scrolling\u2014across a wide range of devices (from mobile phones to desktop computer monitors).<\/p>\n<\/blockquote>\n\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Responsive_web_design\" target=\"_blank\">https:\/\/en.wikipedia.org\/wiki\/Responsive_web_design<\/a><\/p>\n\n<h2 id=\"10--duck-typing\">10 \u2013 Duck Typing<\/h2>\n\n<p>Quoting from Wikipedia:<\/p>\n\n<blockquote>\n  <p>With object-oriented programming languages, duck typing is a style of typing in which an object\u2019s methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of an explicit interface. The name of the concept refers to the duck test, attributed to James Whitcomb Riley (see history below), which may be phrased as follows:<\/p>\n\n  <p><strong>When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.<\/strong><\/p>\n\n  <p>In duck typing, a programmer is only concerned with ensuring that objects behave as demanded of them in a given context, rather than ensuring that they are of a specific type. For example, in a non-duck-typed language, one would create a function that requires that the object passed into it be of type Duck, in order to ensure that that function can then use the object\u2019s walk and quack methods. In a duck-typed language, the function would take an object of any type and simply call its walk and quack methods, producing a run-time error if they are not defined. Instead of specifying types formally, duck typing practices rely on documentation, clear code, and testing to ensure correct use.<\/p>\n<\/blockquote>\n\n<p><a href=\"https:\/\/en.wikipedia.org\/wiki\/Duck_typing\" target=\"_blank\">https:\/\/en.wikipedia.org\/wiki\/Duck_typing<br \/> <\/a><\/p>\n\n<h2 id=\"conclusion\">Conclusion<\/h2>\n\n<p>Joke aside, if I am interviewing someone and he\/she is using some key phrases, where relevant, this would be a great plus which proves they know what they are talking about.<\/p>\n\n<p>We advise using these keywords in an interview with caution\u2026<\/p>\n","pubDate":"Mon, 08 Sep 2014 19:44:00 +0000","link":"https:\/\/adamtibi.net\/09-2014\/ten-software-keywords-that-make-you-look-smarter","guid":"https:\/\/adamtibi.net\/09-2014\/ten-software-keywords-that-make-you-look-smarter","category":["C#","CodeProject","Interview","Uncategorized"]},{"title":"Implementing a CQRS architecture with MVC and Document DB","description":"<figure>\n<img src=\"\/assets\/artefacts\/2013\/06\/MVC-MongoDB-Ninject-CQRS.png\" alt=\"MVC MongoDB Ninject CQRS\" \/>\n<\/figure>\n\n<p>This is a sample implementation of ASP.NET MVC4, MongoDB and Ninject to act as a starting template if you are going to use these technologies in your project with a CQRS pattern.<\/p>\n\n<h2 id=\"audience\">Audience<\/h2>\n\n<p>If most of these terms look unfamiliar then this post is probably not for you: CQRS, Repository, Aggregate (of DDD), NuGet, Unit Testing, Dependency Injection, Document DB. Due to the scope of this post, I won\u2019t be able to go in details in any of these topics as this is a direct implementation.<\/p>\n\n<p>Greg Young did a few paragraphs intro on CQRS here: <a href=\"http:\/\/codebetter.com\/gregyoung\/2010\/02\/16\/cqrs-task-based-uis-event-sourcing-agh\/\" target=\"_blank\">CQRS, Task Based UIs, Event Sourcing agh<\/a>, if you want a simple intro I recommend at least reading the first half of Greg\u2019s post (before the Event Sourcing).<\/p>\n\n<h2 id=\"scope-and-definition\">Scope and Definition<\/h2>\n\n<p>In this post, I mean the plain-CQRS pattern and not the whole patterns that are associated with CQRS. Plain CQRS opens the door for other patterns such as Event Sourcing and ES is usually associated with CQRS. This is the plain CQRS with no other associated pattern.<\/p>\n\n<!--more-->\n\n<h2 id=\"choice-of-technology\">Choice of Technology<\/h2>\n\n<p>I chose MongoDB due to its open licence policy and simplicity, Ninject due to its licence, simplicity and <code class=\"language-plaintext highlighter-rouge\">Ninject.Extensions.Conventions<\/code> extension that makes my code DRYer.<\/p>\n\n<p>I could have chosen SQL Server, but for simplicity reasons and to get the idea across, Document DBs are easier to work with. You could also tweak this sample implementation to work on an RDBMS as long as you get the repository right.<\/p>\n\n<p>This is a sample implementation of ASP.NET MVC4, MongoDB and Ninject to act as a starting template, in case you are going to use these technologies in your project with a CQRS pattern.<\/p>\n\n<h2 id=\"task-application\">Task Application<\/h2>\n\n<figure class=\"alignright\">\n<img src=\"\/assets\/artefacts\/2013\/06\/task-app.png\" alt=\"Task App\" \/> \n<\/figure>\n\n<p>This is meant to be a trivial application, so that the focus is shifted from the features to the MVC with CQRS pattern. The application:<\/p>\n\n<ul class=\"content\">\n  <li>\n    Enables querying the tasks. When the user clicks &#8220;Query&#8221;, if the <em>Completed<\/em> is selected, it will display completed tasks and if it is not selected, it will display uncompleted tasks. This is meant to represent the start of a CQRS&#8217;s Query.\n  <\/li>\n  <li>\n    Checking or unchecking any checkbox in the <em>&#8220;Completed?&#8221;<\/em> column will update the task, via Ajax. This is meant to represent the start of a CQRS&#8217;s Command.\n  <\/li>\n  <li>\n    Has no way to add or delete tasks. To load sample tasks into the DB, I have included, in the download, a MongoDB script that will populate the DB.\n  <\/li>\n<\/ul>\n\n<h2 id=\"why-using-cqrs-with-mvc\">Why using CQRS with MVC?<\/h2>\n\n<p>I recently wrote <a target=\"_blank\" href=\"https:\/\/adamtibi.net\/06-2013\/you-should-unit-test-your-controller-not\">You should unit test your controller, NOT!<\/a>, where I gave guidelines that an MVC controller should have almost no code, so it doesn\u2019t even require unit testing, but it is really difficult to show how to achieve this within the scope of that post.<\/p>\n\n<p>Using CQRS enforces better separation of concerns and produces an almost-empty controller, where the viewmodel turns to a query, when getting data or turns into a command, when posting data.<\/p>\n\n<p><img src=\"\/assets\/artefacts\/2013\/06\/MVC-with-CQRS.png\" alt=\"ASP.NET MVC with CQRS\" \/><\/p>\n\n<p>The diagram above is a sketch of the implementation of the solution, it will get clearer when you progress through the post and read the source code.<\/p>\n\n<h2 id=\"solution-structure\">Solution Structure<\/h2>\n<figure class=\"alignright\">\n<img src=\"\/assets\/artefacts\/2013\/06\/VS-MVC-CQRS-Solution.png\" alt=\"VS MVC CQRS Solution\" \/> \n<\/figure>\n\n<p>First, whenever, you notice the use of \u201cAT\u201d in the namespace, you can replace that with your company name, as you\u2019ve already concluded, ehmm, AT are my initials.<\/p>\n\n<p>The solution is using VS 2012 and has 4 projects:<\/p>\n\n<ul class=\"content\">\n  <li>\n    <code>AT.Core<\/code>: This is where the infrastructure classes are, such as the CQRS infrastructure classes.\n  <\/li>\n  <li>\n    <code>AT.SampleApp.Cqrs<\/code>: Commands, command handlers, queries, query handlers, query results and domain classes. This is where your business logic is. This project references <code>AT.Core<\/code>. In this sample project it has one sample query <code>TasksByStatusQuery<\/code> and one command <code>ChangeTaskStatusCommand<\/code>.\n  <\/li>\n  <li>\n    <code>AT.SampleApp.Cqrs.Test.Unit<\/code>: Unit tests for the <code>AT.SampleApp.Cqrs<\/code> project. They follow the conventions specified in the <a href=\"https:\/\/www.amazon.co.uk\/Art-Unit-Testing-Examples-NET\/dp\/1933988274\" target=\"_blank\">The Art of Unit Testing: with Examples in .NET by Roy Osherove<\/a>, which I recommend you read, it is a bit outdated, however, there is a newer version being cooked, while writing this post.\n  <\/li>\n  <li>\n    <code>AT.Web.Website<\/code>: ASP.NET MVC4 project that references <code>AT.Core<\/code> and <code>AT.SampleApp.Cqrs<\/code>\n  <\/li>\n<\/ul>\n\n<h2 id=\"the-code\">The Code<\/h2>\n\n<p>I felt the best way to show the pattern, is to progress in the code as if I am debugging and show what is happening in each stage, I found this is the fastest way to learn, we spend half our lives as debugging debugging!<\/p>\n\n<h2 id=\"the-command\">The Command<\/h2>\n\n<p>The user clicks the \u201cCompleted?\u201d checkbox for one task to mark it as completed, which executes the following JavaScript\/jQuery:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-js\" data-lang=\"js\"><span class=\"nx\">$<\/span><span class=\"p\">.<\/span><span class=\"nx\">post<\/span><span class=\"p\">(<\/span><span class=\"dl\">\"<\/span><span class=\"s2\">\/Task\/ChangeTaskStatus<\/span><span class=\"dl\">\"<\/span><span class=\"p\">,<\/span>\n    <span class=\"p\">{<\/span>\n    <span class=\"dl\">\"<\/span><span class=\"s2\">TaskId<\/span><span class=\"dl\">\"<\/span><span class=\"p\">:<\/span> <span class=\"nx\">$<\/span><span class=\"p\">(<\/span><span class=\"k\">this<\/span><span class=\"p\">).<\/span><span class=\"nx\">data<\/span><span class=\"p\">(<\/span><span class=\"dl\">\"<\/span><span class=\"s2\">id<\/span><span class=\"dl\">\"<\/span><span class=\"p\">),<\/span>\n    <span class=\"dl\">\"<\/span><span class=\"s2\">IsCompleted<\/span><span class=\"dl\">\"<\/span><span class=\"p\">:<\/span> <span class=\"k\">this<\/span><span class=\"p\">.<\/span><span class=\"nx\">checked<\/span><span class=\"p\">,<\/span>\n    <span class=\"dl\">\"<\/span><span class=\"s2\">UpdatedOn<\/span><span class=\"dl\">\"<\/span><span class=\"p\">:<\/span> <span class=\"nx\">fomattedNow<\/span>\n    <span class=\"p\">}<\/span>\n<span class=\"p\">);<\/span><\/code><\/pre><\/figure>\n\n<h3 id=\"command--controller\">Command &amp; Controller<\/h3>\n\n<p>The post request reaches the <code class=\"language-plaintext highlighter-rouge\">ChangeTaskStatus<\/code> action method and becomes a command:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"k\">public<\/span> <span class=\"k\">class<\/span> <span class=\"nc\">TaskController<\/span> <span class=\"p\">:<\/span> <span class=\"n\">Controller<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"k\">private<\/span> <span class=\"k\">readonly<\/span> <span class=\"n\">IQueryDispatcher<\/span> <span class=\"n\">_queryDispatcher<\/span><span class=\"p\">;<\/span>\n    <span class=\"k\">private<\/span> <span class=\"k\">readonly<\/span> <span class=\"n\">ICommandDispatcher<\/span> <span class=\"n\">_commandDispatcher<\/span><span class=\"p\">;<\/span>\n\n    <span class=\"k\">public<\/span> <span class=\"nf\">TaskController<\/span><span class=\"p\">(<\/span><span class=\"n\">IQueryDispatcher<\/span> <span class=\"n\">queryDispatcher<\/span><span class=\"p\">,<\/span> \n                          <span class=\"n\">ICommandDispatcher<\/span> <span class=\"n\">commandDispatcher<\/span><span class=\"p\">)<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"n\">_queryDispatcher<\/span> <span class=\"p\">=<\/span> <span class=\"n\">queryDispatcher<\/span><span class=\"p\">;<\/span>\n        <span class=\"n\">_commandDispatcher<\/span> <span class=\"p\">=<\/span> <span class=\"n\">commandDispatcher<\/span><span class=\"p\">;<\/span>\n    <span class=\"p\">}<\/span>\n\n    <span class=\"p\">[<\/span><span class=\"n\">HttpPost<\/span><span class=\"p\">]<\/span>\n    <span class=\"k\">public<\/span> <span class=\"n\">ActionResult<\/span> <span class=\"nf\">ChangeTaskStatus<\/span><span class=\"p\">(<\/span><span class=\"n\">ChangeTaskStatusCommand<\/span> <span class=\"n\">command<\/span><span class=\"p\">)<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"n\">_commandDispatcher<\/span><span class=\"p\">.<\/span><span class=\"nf\">Dispatch<\/span><span class=\"p\">(<\/span><span class=\"n\">command<\/span><span class=\"p\">);<\/span>\n\n        <span class=\"k\">return<\/span> <span class=\"k\">new<\/span> <span class=\"nf\">HttpStatusCodeResult<\/span><span class=\"p\">(<\/span><span class=\"n\">HttpStatusCode<\/span><span class=\"p\">.<\/span><span class=\"n\">Accepted<\/span><span class=\"p\">);<\/span>\n    <span class=\"p\">}<\/span>\n\n    <span class=\"c1\">\/\/ other action methods<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<p>Starting by the easier bit of the <code class=\"language-plaintext highlighter-rouge\">ChangeTaskStatus<\/code> method, the action method returns a HTTP code to the client to say that everything is fine.<\/p>\n\n<h3 id=\"command-dispatcher\">Command Dispatcher<\/h3>\n\n<p><code class=\"language-plaintext highlighter-rouge\">_commandDispatcher.Dispatch<\/code> takes a command and relies on the dependency injection to find a handler for this command, in this case, it will match the <code class=\"language-plaintext highlighter-rouge\">ChangeTaskStatusCommand<\/code> with <code class=\"language-plaintext highlighter-rouge\">ChangeTaskStatusCommandHanlder<\/code>.<\/p>\n\n<p>Why relying on dependency injection rather than calling the command handler directly? Simple answer: decoupling. The controller doesn\u2019t know much what is happening, it is just dispatching (some calls it publishing, but publishing might convey an async call or a bus call) a command \u201cto whom it may concern\u201d and the proper handler will take it and processes it.<\/p>\n\n<p>The <code class=\"language-plaintext highlighter-rouge\">_commandDispatcher<\/code> is injected into the controller as well, we will see what it does in more details, but before that lets look at the dependency injector code, for this, I have used Ninject and Ninject.Extensions.Convention from NuGet, this is the kernel code that I\u2019ve used:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"n\">kernel<\/span><span class=\"p\">.<\/span><span class=\"nf\">Bind<\/span><span class=\"p\">(<\/span><span class=\"n\">x<\/span> <span class=\"p\">=&gt;<\/span> <span class=\"n\">x<\/span><span class=\"p\">.<\/span><span class=\"nf\">FromAssembliesMatching<\/span><span class=\"p\">(<\/span><span class=\"s\">\"AT.Core.dll\"<\/span><span class=\"p\">,<\/span> <span class=\"s\">\"AT.Web.Website.dll\"<\/span><span class=\"p\">)<\/span>\n      <span class=\"p\">.<\/span><span class=\"nf\">SelectAllClasses<\/span><span class=\"p\">().<\/span><span class=\"nf\">BindDefaultInterface<\/span><span class=\"p\">());<\/span><\/code><\/pre><\/figure>\n\n<p><code class=\"language-plaintext highlighter-rouge\">BindDefaultInterface<\/code> is simply saying bind <code class=\"language-plaintext highlighter-rouge\">ISomething<\/code> to <code class=\"language-plaintext highlighter-rouge\">Something<\/code> by convention, so, the first line injects the dispatchers into the controller.<\/p>\n\n<p>Now, this dispatch method, how does it work? How does it match the command to its handler?<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"k\">public<\/span> <span class=\"k\">void<\/span> <span class=\"n\">Dispatch<\/span><span class=\"p\">&lt;<\/span><span class=\"n\">TParameter<\/span><span class=\"p\">&gt;(<\/span><span class=\"n\">TParameter<\/span> <span class=\"n\">command<\/span><span class=\"p\">)<\/span> <span class=\"k\">where<\/span> <span class=\"n\">TParameter<\/span> <span class=\"p\">:<\/span> <span class=\"n\">ICommand<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"kt\">var<\/span> <span class=\"n\">handler<\/span> <span class=\"p\">=<\/span> <span class=\"n\">_kernel<\/span><span class=\"p\">.<\/span><span class=\"n\">Get<\/span><span class=\"p\">&lt;<\/span><span class=\"n\">ICommandHandler<\/span><span class=\"p\">&lt;<\/span><span class=\"n\">TParameter<\/span><span class=\"p\">&gt;&gt;();<\/span>\n    <span class=\"n\">handler<\/span><span class=\"p\">.<\/span><span class=\"nf\">Execute<\/span><span class=\"p\">(<\/span><span class=\"n\">command<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<p><code class=\"language-plaintext highlighter-rouge\">_kernel<\/code> is Ninject, it is querying, at run-time, the handler of the passed command and then calling its <code class=\"language-plaintext highlighter-rouge\">Execute<\/code> method to pass it the command.<\/p>\n\n<p>You\u2019ve got to like the fact that dependency injectors promote decoupling, but your modules become coupled to them! Maybe we need a second-level dependency injector to decouple the first one. But, Ninject has a cool logo, so I don\u2019t mind my modules depending on it \ud83d\ude42<\/p>\n\n<h3 id=\"command-handler\">Command Handler<\/h3>\n<figure>\n<img src=\"\/assets\/artefacts\/2013\/06\/command-handler.png\" alt=\"command handler\" \/> \n<\/figure>\n\n<p>This is where the business logic lives. The handler might mutate a state, save to the DB (or more accurately, persists through a repository), calls another handler, etc\u2026<\/p>\n\n<p>This is the <code class=\"language-plaintext highlighter-rouge\">ChangeTaskStatusCommandHanlder<\/code>, Execute method:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"k\">public<\/span> <span class=\"k\">void<\/span> <span class=\"nf\">Execute<\/span><span class=\"p\">(<\/span><span class=\"n\">ChangeTaskStatusCommand<\/span> <span class=\"n\">command<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"k\">if<\/span> <span class=\"p\">(<\/span><span class=\"n\">command<\/span> <span class=\"p\">==<\/span> <span class=\"k\">null<\/span><span class=\"p\">)<\/span> <span class=\"p\">{<\/span> <span class=\"k\">throw<\/span> <span class=\"k\">new<\/span> <span class=\"nf\">ArgumentNullException<\/span><span class=\"p\">(<\/span><span class=\"s\">\"command\"<\/span><span class=\"p\">);<\/span> <span class=\"p\">}<\/span>\n    <span class=\"k\">if<\/span> <span class=\"p\">(<\/span><span class=\"kt\">string<\/span><span class=\"p\">.<\/span><span class=\"nf\">IsNullOrWhiteSpace<\/span><span class=\"p\">(<\/span><span class=\"n\">command<\/span><span class=\"p\">.<\/span><span class=\"n\">TaskId<\/span><span class=\"p\">))<\/span> <span class=\"p\">{<\/span> \n        <span class=\"k\">throw<\/span> <span class=\"k\">new<\/span> <span class=\"nf\">ArgumentException<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Id is not specified\"<\/span><span class=\"p\">,<\/span> <span class=\"s\">\"command\"<\/span><span class=\"p\">);<\/span> \n    <span class=\"p\">}<\/span>\n\n    <span class=\"kt\">var<\/span> <span class=\"n\">task<\/span> <span class=\"p\">=<\/span> <span class=\"n\">_taskRepository<\/span><span class=\"p\">.<\/span><span class=\"nf\">All<\/span><span class=\"p\">().<\/span><span class=\"nf\">Single<\/span><span class=\"p\">(<\/span><span class=\"n\">x<\/span> <span class=\"p\">=&gt;<\/span> <span class=\"n\">x<\/span><span class=\"p\">.<\/span><span class=\"n\">Id<\/span> <span class=\"p\">==<\/span> <span class=\"n\">command<\/span><span class=\"p\">.<\/span><span class=\"n\">TaskId<\/span><span class=\"p\">);<\/span>\n    <span class=\"n\">task<\/span><span class=\"p\">.<\/span><span class=\"n\">IsCompleted<\/span> <span class=\"p\">=<\/span> <span class=\"n\">command<\/span><span class=\"p\">.<\/span><span class=\"n\">IsCompleted<\/span><span class=\"p\">;<\/span>\n    <span class=\"n\">task<\/span><span class=\"p\">.<\/span><span class=\"n\">LastUpdated<\/span> <span class=\"p\">=<\/span> <span class=\"n\">command<\/span><span class=\"p\">.<\/span><span class=\"n\">UpdatedOn<\/span><span class=\"p\">;<\/span>\n\n    <span class=\"n\">_taskRepository<\/span><span class=\"p\">.<\/span><span class=\"nf\">Update<\/span><span class=\"p\">(<\/span><span class=\"n\">task<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<p>Please keep in mind, what we are doing here as a business logic is super simplistic and doesn\u2019t show the true power of the CQRS pattern, but it does give you an idea.<\/p>\n\n<p>Binding via Ninject (this code will apply to all my handlers, not just this one):<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"n\">kernel<\/span><span class=\"p\">.<\/span><span class=\"nf\">Bind<\/span><span class=\"p\">(<\/span><span class=\"n\">x<\/span> <span class=\"p\">=&gt;<\/span> <span class=\"n\">x<\/span><span class=\"p\">.<\/span><span class=\"nf\">FromAssembliesMatching<\/span><span class=\"p\">(<\/span><span class=\"s\">\"AT.SampleApp.Cqrs.dll\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"p\">.<\/span><span class=\"nf\">SelectAllClasses<\/span><span class=\"p\">().<\/span><span class=\"nf\">InheritedFrom<\/span><span class=\"p\">(<\/span><span class=\"k\">typeof<\/span><span class=\"p\">(<\/span><span class=\"n\">ICommandHandler<\/span><span class=\"p\">&lt;&gt;)).<\/span><span class=\"nf\">BindAllInterfaces<\/span><span class=\"p\">());<\/span><\/code><\/pre><\/figure>\n\n<h3 id=\"repository\">Repository<\/h3>\n\n<p>I have used MongoDB as a storage media, which you can NuGet. Also, rather than implementing the popular Repository DDD pattern myself, one good chap implemented it for us for MongoDB and packaged it as NuGet, look at NuGet for MongoRepository. I am simply using it as-is. You could see that from the previous code above. I am using the following Ninject code to bind to it:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"n\">kernel<\/span><span class=\"p\">.<\/span><span class=\"nf\">Bind<\/span><span class=\"p\">(<\/span><span class=\"n\">x<\/span> <span class=\"p\">=&gt;<\/span> <span class=\"n\">x<\/span><span class=\"p\">.<\/span><span class=\"nf\">FromAssembliesMatching<\/span><span class=\"p\">(<\/span><span class=\"s\">\"AT.SampleApp.Cqrs.dll\"<\/span><span class=\"p\">,<\/span> <span class=\"s\">\"MongoRepository.dll\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"p\">.<\/span><span class=\"nf\">SelectAllClasses<\/span><span class=\"p\">().<\/span><span class=\"nf\">InheritedFrom<\/span><span class=\"p\">(<\/span><span class=\"k\">typeof<\/span><span class=\"p\">(<\/span><span class=\"n\">IRepository<\/span><span class=\"p\">&lt;&gt;)).<\/span><span class=\"nf\">BindAllInterfaces<\/span><span class=\"p\">());<\/span><\/code><\/pre><\/figure>\n\n<h3 id=\"aggregate\">Aggregate<\/h3>\n\n<p>This is a simple aggregate and I am persisting it as a document in MongoDB:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"k\">public<\/span> <span class=\"k\">class<\/span> <span class=\"nc\">Task<\/span> <span class=\"p\">:<\/span> <span class=\"n\">IEntity<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"p\">[<\/span><span class=\"n\">BsonId<\/span><span class=\"p\">]<\/span>\n    <span class=\"p\">[<\/span><span class=\"nf\">BsonRepresentation<\/span><span class=\"p\">(<\/span><span class=\"n\">BsonType<\/span><span class=\"p\">.<\/span><span class=\"n\">ObjectId<\/span><span class=\"p\">)]<\/span>\n    <span class=\"k\">public<\/span> <span class=\"kt\">string<\/span> <span class=\"n\">Id<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n    <span class=\"k\">public<\/span> <span class=\"kt\">string<\/span> <span class=\"n\">Title<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n    <span class=\"k\">public<\/span> <span class=\"kt\">bool<\/span> <span class=\"n\">IsCompleted<\/span><span class=\"p\">;<\/span>\n    <span class=\"k\">public<\/span> <span class=\"n\">DateTime<\/span> <span class=\"n\">LastUpdated<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<h2 id=\"the-query\">The Query<\/h2>\n\n<p>The query has a similar path to the command, with the following differences:<\/p>\n\n<ul class=\"content\">\n  <li>\n    The controller is calling the <code>_queryDispatcher<\/code> explicitly and not implicitly like the <code>_commandDispatcher<\/code>.\n  <\/li>\n  <li>\n    The query is two ways, the query and its results while the command is one way.\n  <\/li>\n  <li>\n    There are much more differences, but I am looking at the differences from this project point of view.\n  <\/li>\n<\/ul>\n\n<h2 id=\"recap\">Recap<\/h2>\n\n<p>I hope that I was able to illustrate the diagram above, feel free to ask me in a comment if I made a mistake or if you have a question.<\/p>\n\n<p>Let\u2019s recap on the steps that the command of CQRS was implemented.<\/p>\n\n<ul class=\"content\">\n  <li>\n    Command is triggered by the view.\n  <\/li>\n  <li>\n    Command reaches the action method.\n  <\/li>\n  <li>\n    The action method dispatches the command to a handler.\n  <\/li>\n  <li>\n    The handler takes the command and does some business logic then persists it through a repository.\n  <\/li>\n<\/ul>\n\n<h2 id=\"whats-next\">What\u2019s Next?<\/h2>\n\n<p>This is only the basic and the first building block in your CQRS application. You will probably add other CQRS related pattern on top of this. Here are some ideas to polish your architecture:<\/p>\n\n<h3 id=\"base-controller\">Base Controller<\/h3>\n\n<p>You might want to have a Base Controller and inject your dispatchers into it. Something like this:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"k\">public<\/span> <span class=\"k\">abstract<\/span> <span class=\"k\">class<\/span> <span class=\"nc\">BaseController<\/span> <span class=\"p\">:<\/span> <span class=\"n\">Controller<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"p\">[<\/span><span class=\"n\">Inject<\/span><span class=\"p\">]<\/span>\n    <span class=\"k\">public<\/span> <span class=\"n\">ICommandDispatcher<\/span> <span class=\"n\">CommandDispatcher<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n    <span class=\"p\">[<\/span><span class=\"n\">Inject<\/span><span class=\"p\">]<\/span>\n    <span class=\"k\">public<\/span> <span class=\"n\">IQueryDispatcher<\/span> <span class=\"n\">QueryDispatcher<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<h3 id=\"event-sourcing\">Event Sourcing<\/h3>\n\n<p>Now, you have seen the basic pattern, what about looking further: Here is another good article that has a different focus to the stuff I\u2019ve discussed here: <a href=\"https:\/\/www.codeproject.com\/Articles\/555855\/Introduction-to-CQRS\" target=\"_blank\">Introduction to CQRS<\/a>.<\/p>\n\n<h3 id=\"enhancing-the-basic-architecture\">Enhancing the basic Architecture<\/h3>\n\n<p>There is no logging, there is no error handling, ofcourse, as this is not meant for production, it meant to be a sample, make it mainstream \ud83d\ude42<\/p>\n\n<h2 id=\"conclusion\">Conclusion<\/h2>\n\n<p>The results? Controllers are nearly empty, DRY code and a pattern that is open for unit testing. Obviously, the amount of code is over killing for such a small application, but this is only to trigger your software design imagination so you could apply this pattern to a real-life application (obviously not by forcing the pattern if it doesn\u2019t fit).<\/p>\n\n<p>I hope I made somebody\u2019s day, if you like this then do let me know in a comment so I would be encouraged to write more. While I tried to keep it to a minimum, this was longer than what I wanted it to be. Note that the source code in the download area contains the complete code.<\/p>\n\n<p>I am open for suggestions to change for the better, do let me know your ideas in a comment.<\/p>\n\n<h2 id=\"download\">Download<\/h2>\n\n<p>Using Visual Studio 2012 Ultimate. I had to delete all the Nuget files to keep the file size to the minimum, it will probably ask you to download these packages from NuGet when you try to build it.<\/p>\n\n<p class=\"download\">\n  <a href=\"\/assets\/artefacts\/2013\/06\/MvcWithCqrsSample.zip\">MvcWithCqrsSample.zip (432 KB)<\/a>\n<\/p>\n\n<h2 id=\"disclaimer\">Disclaimer<\/h2>\n\n<p>I tried to ensure that the information posted here are up to date and accurate, however, I do not hold any responsibility to any damages that might occur from using or misusing the information and the posted code.<\/p>\n","pubDate":"Sat, 22 Jun 2013 02:06:00 +0000","link":"https:\/\/adamtibi.net\/06-2013\/implementing-a-cqrs-based-architecture-with-mvc-and-document-db","guid":"https:\/\/adamtibi.net\/06-2013\/implementing-a-cqrs-based-architecture-with-mvc-and-document-db","category":["CodeProject","CQRS","Dependency Injection","Document DB","MongoDB","MVC","Ninject","Unit Test","Uncategorized"]},{"title":"5 Essential Front-End tools you should use with MVC Projects","description":"<p>Microsoft is doing a good job in shipping standard front-end libraries with Visual Studio 2012 \u201cASP.NET MVC 4 Web Application\u201d and \u201cASP.NET Web Forms Application\u201d templates, they are raising the bar for the .NET web developers.<\/p>\n\n<p>The VS template is a good starting base, however, I have been adding the libraries of this post to every new web project, they act as a completion to the ones shipped with VS and I wanted to share them with you.<\/p>\n\n<!--more-->\n\n<h2 id=\"1--css-normalizer\">1 \u2013 CSS Normalizer<\/h2>\n<figure>\n<img src=\"\/assets\/artefacts\/2013\/06\/Browser-Reset.png\" alt=\"Browser Reset\" \/> \n<\/figure>\n\n<p>One common problem we used to face is the fact that every browser has different default settings. If you don\u2019t explicitly style an element (a tag), it may not look the same cross-browsers.<\/p>\n\n<p>The image above shows the following code with and without resetting:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-html\" data-lang=\"html\"><span class=\"nt\">&lt;abbr<\/span> <span class=\"na\">title=<\/span><span class=\"s\">\"Title text\"<\/span><span class=\"nt\">&gt;<\/span>abbr<span class=\"nt\">&lt;\/abbr&gt;<\/span> has an underline in FF.<\/code><\/pre><\/figure>\n\n<p>Today, the de facto CSS resetting tool is <a href=\"https:\/\/necolas.github.io\/normalize.css\/\" target=\"_blank\">Normalize.css<\/a>, it does much more than my demo above to target cross-browsers differences. Quoting the authors: <em>Normalize.css makes browsers render all elements more consistently and in line with modern standards. It precisely targets only the styles that need normalizing.<\/em><\/p>\n\n<p><strong>N.B.<\/strong> Normalize is meant to replace what was called as \u201cCSS Reset\u201d so, never call it \u201cReset\u201d or you will be accused of being uncool!<\/p>\n\n<p>Website: <a href=\"https:\/\/necolas.github.io\/normalize.css\/\" target=\"_blank\">https:\/\/necolas.github.io\/normalize.css\/<\/a><\/p>\n\n<p>Nuget: <em>PM&gt; Install-Package normalize.css<\/em><\/p>\n\n<p><acronym title=\"Content Delivery Network\">CDN<\/acronym>: <em>https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/normalize\/2.1.0\/normalize.css<\/em><\/p>\n\n<h2 id=\"2--html5-on-legacy-ie-browsers\">2 \u2013 HTML5 on legacy IE Browsers<\/h2>\n\n<p>It is a shame that IE versions prior to IE9 will not recognise HTML5 new elements such as <code class=\"language-plaintext highlighter-rouge\">&lt;nav&gt;<\/code>. However, fear not, <a href=\"https:\/\/github.com\/afarkas\/html5shiv\" target=\"_blank\">html5shiv<\/a> to the rescue. You can use it in the document <code class=\"language-plaintext highlighter-rouge\">&lt;head&gt;<\/code> like this:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-html\" data-lang=\"html\"><span class=\"c\">&lt;!--[if lt IE 9]&gt;\n&lt;script src=\"dist\/html5shiv.js\"&gt;&lt;\/script&gt;\n&lt;![endif]--&gt;<\/span><\/code><\/pre><\/figure>\n\n<p>If you are using <a href=\"https:\/\/modernizr.com\/\" target=\"_blank\">Modernizr<\/a> then it does contain the html5shiv and you do not need to reference it separately, unless you have downloaded a custom version of Modernizr. Modernizr that comes with VS 2012 web templates already has html5shiv.<\/p>\n\n<p>Website: <a href=\"https:\/\/github.com\/afarkas\/html5shiv\" target=\"_blank\">https:\/\/github.com\/afarkas\/html5shiv<\/a><\/p>\n\n<p>Nuget: <em>PM&gt; Install-Package html5shiv<\/em><\/p>\n\n<p><acronym title=\"Content Delivery Network\">CDN<\/acronym>: <em>https:\/\/cdnjs.cloudflare.com\/ajax\/libs\/html5shiv\/3.6\/html5shiv.min.js<\/em><\/p>\n\n<h2 id=\"3--css-generators\">3 \u2013 CSS Generators<\/h2>\n\n<figure>\n<img src=\"\/assets\/artefacts\/2013\/06\/Less-Sass.png\" alt=\"LESS and SASS\" \/> \n<\/figure>\n\n<p>CSS has to maintain backward compatibility, it cannot break the web. CSS is verbose and not DRY.<\/p>\n\n<p><a href=\"http:\/\/lesscss.org\/\" target=\"_blank\">LESS<\/a> and <a href=\"https:\/\/sass-lang.com\/\" target=\"_blank\">SASS<\/a> are two popular CSS generators, they use more modern language that will render plain old CSS when compiled.<\/p>\n\n<p>The web is divided on which is better LESS, SASS or not using a generator at all. I am personally with the LESS generator as it is straight forward to learn and covers the gaps of CSS, such as the lack of variables, rather than replacing it with completely new syntax. Here is a very simple example that would give you a flavour of LESS:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-css\" data-lang=\"css\"><span class=\"o\">\/\/<\/span> <span class=\"nt\">LESS<\/span>\n<span class=\"k\">@baseColor<\/span><span class=\"p\">:<\/span> <span class=\"m\">#4D926F<\/span><span class=\"p\">;<\/span>\n<span class=\"nf\">#header<\/span> <span class=\"p\">{<\/span>\n  <span class=\"nl\">color<\/span><span class=\"p\">:<\/span> <span class=\"err\">@<\/span><span class=\"n\">baseColor<\/span><span class=\"p\">;<\/span>\n  <span class=\"nl\">background-color<\/span><span class=\"p\">:<\/span> <span class=\"n\">lighten<\/span><span class=\"p\">(<\/span><span class=\"err\">@<\/span><span class=\"n\">baseColor<\/span><span class=\"p\">,<\/span> <span class=\"m\">20%<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"nt\">h2<\/span> <span class=\"p\">{<\/span>\n  <span class=\"nl\">color<\/span><span class=\"p\">:<\/span> <span class=\"err\">@<\/span><span class=\"n\">baseColor<\/span><span class=\"p\">;<\/span>\n  <span class=\"nl\">background-color<\/span><span class=\"p\">:<\/span> <span class=\"n\">darken<\/span><span class=\"p\">(<\/span><span class=\"err\">@<\/span><span class=\"n\">baseColor<\/span><span class=\"p\">,<\/span> <span class=\"m\">20%<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<p>This will compile to the following CSS:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-css\" data-lang=\"css\"><span class=\"c\">\/* Compiled CSS *\/<\/span>\n<span class=\"nf\">#header<\/span> <span class=\"p\">{<\/span>\n  <span class=\"nl\">color<\/span><span class=\"p\">:<\/span> <span class=\"m\">#4d926f<\/span><span class=\"p\">;<\/span>\n  <span class=\"nl\">background-color<\/span><span class=\"p\">:<\/span> <span class=\"m\">#86bfa2<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"nt\">h2<\/span> <span class=\"p\">{<\/span>\n  <span class=\"nl\">color<\/span><span class=\"p\">:<\/span> <span class=\"m\">#4d926f<\/span><span class=\"p\">;<\/span>\n  <span class=\"nl\">background-color<\/span><span class=\"p\">:<\/span> <span class=\"m\">#2a4f3c<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<p>I use this wonderful Visual Studio 2012 plugin to compile LESS to CSS the moment I hit <em>Save<\/em> : <a href=\"https:\/\/marketplace.visualstudio.com\/items?itemName=MadsKristensen.WebEssentials2012\" target=\"_blank\">Web Essentials 2012<\/a>. You can use it to compile SASS as well, but I never tried it for SASS.<\/p>\n\n<p>Websites: <a href=\"http:\/\/lesscss.org\/\" target=\"_blank\">http:\/\/lesscss.org\/<\/a> &amp; <a href=\"https:\/\/sass-lang.com\/\" target=\"_blank\">https:\/\/sass-lang.com\/<\/a>. The websites contain good tutorials that will get you up to speed.<\/p>\n\n<p>Online LESS Compiler (for learning purpose): <a href=\"http:\/\/winless.org\/online-less-compiler\" target=\"_blank\">http:\/\/winless.org\/online-less-compiler<\/a>.<\/p>\n\n<h2 id=\"4--icon-fonts\">4 \u2013 Icon Fonts<\/h2>\n\n<figure>\n<img src=\"\/assets\/artefacts\/2013\/06\/font-awesome.png\" alt=\"Font Awesome\" \/> \n<\/figure>\n\n<p>A new trend in the web has started recently which is using font for icons (well, I am saying started, however, Webdings came in 1997). The icons are vector graphics which means they will scale well at any size and on any platform (in theory), such as the mobile platform. They are quite useful for menus, bottoms, forms and whenever you want to break the text silence with a small icon. They speed up your site and your design process.<\/p>\n\n<p>There are plenty of font icons, just Google it, my favourite is <a href=\"https:\/\/fontawesome.com\/\" target=\"_blank\">Font Awesome<\/a>, here is an example of using it:<\/p>\n\n<p><img src=\"\/assets\/artefacts\/2013\/06\/font-awesome-sample.png\" \/><\/p>\n\n<p>Website: <a href=\"https:\/\/fontawesome.com\/\" target=\"_blank\">https:\/\/fontawesome.com\/<\/a><\/p>\n\n<p>Nuget: <em>PM&gt; Install-Package FontAwesome<\/em><\/p>\n\n<h2 id=\"5--css-frameworks\">5 \u2013 CSS Frameworks<\/h2>\n\n<figure>\n<img src=\"\/assets\/artefacts\/2013\/06\/CSS-Frameworks.png\" alt=\"CSS Frameworks\" \/> \n<\/figure>\n\n<p>If you\u2019ve reached so far, then congratulations, here is the ultimate library that will save you time and will make you deliver faster.<\/p>\n\n<p>A CSS Framework is meant to get you up to speed with the basic stuff that you do every time you start a new website. Things like normalizing CSS (check point 1 of this post), setting padding and margins, forms design, making your site responsive (reacts well when resized to mobile and slate devices), animation, cool buttons, modal dialogs, font icons (check point 4 of this post), they rely on CSS generators (check point 3), modern alerts, and more!<\/p>\n\n<p>There are hundreds of CSS frameworks some of them are generic and some of them focus on certain areas (such as being more responsive or have special features for the mobile), the top competing two are <a href=\"https:\/\/getbootstrap.com\/\" target=\"_blank\">Twitter Bootstrap<\/a> and <a href=\"https:\/\/foundation.zurb.com\/\" target=\"_blank\">Zurb Foundation<\/a>. A complete comparison between the two is beyond the scope of this post (Google \u201cBootstrap vs Foundation\u201d and enjoy), here are some quick points:<\/p>\n\n<ul class=\"content\">\n  <li>\n    Twitter Bootstrap is more popular due to the brand and the amount of plugins.\n  <\/li>\n  <li>\n    Zurb Foundation has better layout grid, however, at the time of this writing, Bootstrap is preparing for a new grid in release 3 which is currently in beta.\n  <\/li>\n  <li>\n    Bootstrap uses LESS (review point 3).\n  <\/li>\n  <li>\n    Foundation uses SASS.\n  <\/li>\n  <li>\n    Both use CSS3 and jQuery.\n  <\/li>\n  <li>\n    While you can&#8217;t compare them like-to-like, using one of them will cancel the need to use jQuery UI (I am talking about jQuery UI and not jQuery).\n  <\/li>\n<\/ul>\n\n<p>You could even find free and commercial templates based on these two framework that will definitely save you more time, especially if the project is a low-budget and\/or for intranet use. This is a popular Bootstrap templates site <a href=\"https:\/\/wrapbootstrap.com\/\" target=\"_blank\">{wrap}bootstrap<\/a>.<\/p>\n\n<p>There is much more to say about CSS frameworks, but the point here is to get you interested versus being a tutorial or a reference.<\/p>\n\n<p>Websites: <a href=\"https:\/\/getbootstrap.com\/\" target=\"_blank\">https:\/\/getbootstrap.com\/<\/a> &amp; <a href=\"https:\/\/foundation.zurb.com\/\" target=\"_blank\">https:\/\/foundation.zurb.com\/<\/a><\/p>\n\n<p>Nuget: <em>PM&gt; Install-Package Twitter.Bootstrap.Less<\/em> &amp; <em>PM&gt; Install-Package Foundation4.MVC4<\/em><\/p>\n\n<h2 id=\"conclusion\">Conclusion<\/h2>\n\n<p><acronym title=\"Don't Repeat Yourself\">DRY<\/acronym> and don\u2019t reinvent the wheel are the points I wanted to make by this post. I hope I did highlight at least one library you didn\u2019t know about and I hope that will make your day, please feel free to mention more libraries that you think are missing, in comments.<\/p>\n","pubDate":"Tue, 18 Jun 2013 05:56:00 +0000","link":"https:\/\/adamtibi.net\/06-2013\/five-essential-front-end-tools-that-should-be-used-with-modern-mvc-projects","guid":"https:\/\/adamtibi.net\/06-2013\/five-essential-front-end-tools-that-should-be-used-with-modern-mvc-projects","category":["ASP.NET","CodeProject","CSS","HTML","JavaScript","jQuery","MVC","Productivity","Visual Studio","Webforms","Uncategorized"]},{"title":"A call To drop the SOLID's \"Open Closed Principle\"","description":"<figure>\n<img src=\"\/assets\/artefacts\/2013\/06\/SLID.png\" alt=\"SLID\" \/>\n<\/figure>\n\n<p>The OCP or \u201cThe Open Closed Principle\u201d is the popular \u201cO\u201d from the <a href=\"https:\/\/en.wikipedia.org\/wiki\/SOLID_(object-oriented_design)\" target=\"_blank\">SOLID<\/a> principles of Object-Oriented Design.<\/p>\n\n<p>As an architect consultant working in London, I get a question about SOLID, every other interview. As usually the interview is about an hour, I answer the question by an out-of-the-textbook type of answer, otherwise, the interview will span for hours. I keep my opinions for myself and I am a happy puppy.<\/p>\n\n<!--more-->\n\n<h2 id=\"the-principle-origin\">The principle origin<\/h2>\n\n<p>First of all, let me cite the OCP origin. This is first mentioned by <a href=\"https:\/\/en.wikipedia.org\/wiki\/Bertrand_Meyer\" target=\"_blank\">Bertrand Meyer<\/a> the creator of Eiffel then surfaced in 2000 by Robert C. Martin (Uncle Bob) in <a href=\"http:\/\/www.cvc.uab.es\/shared\/teach\/a21291\/temes\/object_oriented_design\/materials_adicionals\/principles_and_patterns.pdf\" target=\"_blank\">Principles and Patterns<\/a>.<\/p>\n\n<p>Quoting form Martin\u2019s paper:<\/p>\n\n<blockquote>\n  <p><em>A module should be open for extension but closed for modification.<\/em><\/p>\n<\/blockquote>\n\n<blockquote>\n  <p>Of all the principles of object oriented design, this is the most important. [\u2026] . It means simply this: We should write our modules so that they can be extended, without requiring them to be modified. In other words, we want to be able to change what the modules do, without changing the source code of the modules.<\/p>\n<\/blockquote>\n\n<h2 id=\"what-is-a-module\">What is a module?<\/h2>\n\n<p>A module can be a class, a group of classes or a component, such as a library, that forms a feature. I will assume all of these in the discussion below.<\/p>\n\n<h2 id=\"virtual-everywhere\">Virtual everywhere<\/h2>\n\n<p>The moment I release a class I should not change it! I should think of all possibilities of how it can be extended, prepare all my methods to work well as virtual functions, drop \u201cstart with the simplest thing that works\u201d agile principle and think of the complete architecture, right now! I am going to lose my last chance of modifying it, I better act now, before I even check-in, this is the point of no return, the close to open moment, my last chance, mwahh ha ha haaaa!<\/p>\n\n<h2 id=\"why-in-the-hell-are-we-writing-unit-tests\">Why, in the hell, are we writing unit tests?<\/h2>\n\n<p>If every time I want to leave existing implementation, following OCP, without changing it and extending my module, then I don\u2019t actually have to write future proof code as the code will not change, every time I will be extending existing code and as the norm in the software in change, I will keep extending and I will be reaching hundreds of inheriting class chains. I could maybe write much less unit tests as the logic of this module will not change!<\/p>\n\n<h2 id=\"but-what-happened-to-favour-composition-over-inheritance\">But what happened to \u201cFavour composition over inheritance\u201d?<\/h2>\n\n<p>Doesn\u2019t this contradict with the OCP? Now, every time I want to change, I will wrap my existing class with another class (sort of the Decorator <acronym title=\"Gang of Four\">GoF<\/acronym> Design Pattern) and then the original implementation would be covered with 10s of classes and can\u2019t be reached.<\/p>\n\n<h2 id=\"seriously-lets-drop-it\">Seriously, let\u2019s drop it<\/h2>\n\n<p>Maybe this principle has worked in the Waterfall era, or it might, I used the term \u201cmight\u201d, work in 3rd party components or frameworks, but it doesn\u2019t work in the day-to-day business development.<\/p>\n\n<h2 id=\"conclusion\">Conclusion<\/h2>\n\n<p>We are used to propagate this term, no longer calling it a principle, without giving it much thoughts. The next time an interviewer asks me about the SOLID principles I will ask him\/her did you mean SLID?<\/p>\n\n<p>I was reviewing this before posting it and the tone looks like I am raging, but the fact is, I am laughing and enjoying it. I hope you share me a similar joy.<\/p>\n","pubDate":"Mon, 17 Jun 2013 01:42:20 +0000","link":"https:\/\/adamtibi.net\/06-2013\/call-to-drop-the-open-closed-principle-from-solid","guid":"https:\/\/adamtibi.net\/06-2013\/call-to-drop-the-open-closed-principle-from-solid","category":["Architecture","CodeProject","SOLID","Uncategorized"]},{"title":"You should unit test your controller, NOT!","description":"<figure>\n<img src=\"\/assets\/artefacts\/2013\/06\/unit-testing-mvc.png\" alt=\"Unit Testing MVC\" \/>\n<\/figure>\n\n<p>Unit testing per se is a controversial topic, what you should unit test is another controversial topic. The topic of this post started by a short conversation during a .NET London Group meeting back in 2010, I thought about it and then gave it more thoughts, I started using it in my projects, then now I have enough experience to share my thoughts. Here is my opinion, if you agree or disagree, then please do comment.<\/p>\n\n<!--more-->\n\n<h2 id=\"controllers-should-be-slim\">Controllers should be slim<\/h2>\n\n<p>You\u2019ve heard this before: \u201cControllers shouldn\u2019t be fat, controllers should contain minimal code\u201d, it\u2019s a mantra.<\/p>\n\n<p>The S in SOLID stands for <acronym title=\"Single Responsibility Principle\">SRP<\/acronym>. A controller should have one role, it is the communication layer between a model and a view. Even with this role, it is violating SRP, one could say maybe we need two classes to take the role of a controller or a controller per action method, but let\u2019s not delve into that.<\/p>\n\n<p>The controller, by role, is overloaded with responsibilities, adding more responsibilities to it is a design crime (maybe one should be penalised by losing some StackOverflow or CodeProject points \ud83d\ude42 ).<\/p>\n\n<h2 id=\"why-do-controllers-get-fat\">Why do controllers get fat?<\/h2>\n\n<p>I did blog earlier on how views become fat <a href=\"https:\/\/adamtibi.net\/06-2013\/three-steps-to-get-fat-razor-mvc-views-on-diet\" target=\"_blank\">Three Steps to Get Fat-Razor MVC Views on Diet<\/a>, some points are common and some are specific to controllers:<\/p>\n\n<h3 id=\"explicit-validation-of-data-in-the-action-method\">Explicit validation of data in the action method<\/h3>\n\n<p>Validation of your viewmodel data in your controller violates two principles:<\/p>\n\n<ol>\n  <li><strong><acronym title=\"Single Responsibility Principle\">SRP<\/acronym> Design Principle<\/strong>: You are attaching more responsibilities to the controller.<\/li>\n  <li><strong>Encapsulation <acronym title=\"Object-Oriented Programming\">OOP<\/acronym> Principle<\/strong>: You will have to expose your data outside your viewmodel to allow another object, the controller, to validate it, while the object itself should be responsible for its own data.<\/li>\n<\/ol>\n\n<p>ASP.NET MVC 4 has a good validation ecosystem that will help you moving your validation code to where it belongs.<\/p>\n\n<h3 id=\"mapping-a-model-to-a-viewmodel\">Mapping a model to a viewmodel<\/h3>\n\n<p>The mapping from a model to a viewmodel should not be done in the action method. My favourite solution is to use a CQRS type query pattern so I don\u2019t have to do this boilerplate anywhere. Here is a good <a href=\"https:\/\/www.codeproject.com\/Articles\/555855\/Introduction-to-CQRS\" target=\"_blank\">Introduction to CQRS<\/a>.<\/p>\n\n<h3 id=\"leaking-some-business-logic\">Leaking some business logic<\/h3>\n\n<p>This is not a place for any business logic. The controller should be calling a service, of a classical <acronym href=\"Domain-Driven Design\">DDD<\/acronym> <acronym>implementation, or issuing a query or a command of CQRS.<\/acronym><\/p>\n\n<h3 id=\"http-related-code-in-the-action-method\">Http-related code in the action method<\/h3>\n\n<p>Having a special HTTP case that requires special handling should not be done here. Action filters might be the answer.<\/p>\n\n<h2 id=\"what-are-you-unit-testing\">What are you unit testing?!<\/h2>\n\n<p>Given the above and if your action methods have almost no code, then what are you unit testing? Do you want to test if you are returning the proper view or do you want to test if you have decorated your action method with the proper attributes? I wouldn\u2019t, I usually have a deadline to hit and I am against boilerplate code.<\/p>\n\n<p>If someone tells me their controller requires unit testing, I will ask, did you design your controller properly?<\/p>\n\n<h2 id=\"conclusion\">Conclusion<\/h2>\n\n<p>Unit testing is a mean for providing higher quality software and not an aim per se. Having too many redundant unit tests will cause a future maintenance headache and will cost more project development time.<\/p>\n\n<p>If an area\/layer requires unit testing then you should probably test it, but for other areas more tests may be less quality.<\/p>\n\n<p><strong>Update \u2013<\/strong> I told you not to unit test your controllers, by keeping them empty, here is one way to keep your controllers thin: <a href=\"https:\/\/adamtibi.net\/06-2013\/implementing-a-cqrs-based-architecture-with-mvc-and-document-db\">Implementing a CQRS-based Architecture with MVC and Document DB<\/a>.<\/p>\n","pubDate":"Sun, 16 Jun 2013 21:10:00 +0000","link":"https:\/\/adamtibi.net\/06-2013\/you-should-unit-test-your-controller-not","guid":"https:\/\/adamtibi.net\/06-2013\/you-should-unit-test-your-controller-not","category":["Architecture","ASP.NET","C#","CodeProject","CQRS","MVC","Unit Test","Uncategorized"]},{"title":"Three Steps to Get Fat-Razor MVC Views on Diet","description":"<figure>\n<img src=\"\/assets\/artefacts\/2013\/06\/Fat-Razor.png\" alt=\"Fat Razor in MVC\" \/>\n<\/figure>\n\n<p>Let me first define the terms that I will be referring to:<\/p>\n\n<p><strong>Presentation Code<\/strong>: Is the minimal code in a view that is necessary to display visual elements, but does not take any business decision. This is a fictional simple example:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"c1\">\/\/ Business Logic Code. This code understands how the business works<\/span>\n<span class=\"c1\">\/\/ (don't do this)<\/span>\n<span class=\"k\">if<\/span> <span class=\"p\">(<\/span><span class=\"n\">Model<\/span><span class=\"p\">.<\/span><span class=\"n\">IsMonthly<\/span> <span class=\"p\">&amp;&amp;<\/span> <span class=\"p\">!<\/span><span class=\"n\">Model<\/span><span class=\"p\">.<\/span><span class=\"n\">IsPaid<\/span> <span class=\"p\">&amp;&amp;<\/span> <span class=\"n\">Model<\/span><span class=\"p\">.<\/span><span class=\"n\">Payment<\/span> <span class=\"p\">&gt;=<\/span> <span class=\"m\">12<\/span> <span class=\"p\">&amp;&amp;<\/span> <span class=\"p\">...)<\/span>\n<span class=\"p\">{<\/span>\n  <span class=\"p\">&lt;<\/span><span class=\"n\">p<\/span><span class=\"p\">&gt;<\/span><span class=\"n\">Some<\/span> <span class=\"n\">warning<\/span> <span class=\"n\">message<\/span><span class=\"p\">&lt;\/<\/span><span class=\"n\">p<\/span><span class=\"p\">&gt;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"c1\">\/\/ Presentation Code. This code is only concerned with whether to<\/span>\n<span class=\"c1\">\/\/ show or hide a UI element.<\/span>\n<span class=\"k\">if<\/span> <span class=\"p\">(<\/span><span class=\"n\">Model<\/span><span class=\"p\">.<\/span><span class=\"n\">ShouldWarn<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">{<\/span>\n  <span class=\"p\">&lt;<\/span><span class=\"n\">p<\/span><span class=\"p\">&gt;<\/span><span class=\"n\">Some<\/span> <span class=\"n\">warning<\/span> <span class=\"n\">message<\/span><span class=\"p\">&lt;\/<\/span><span class=\"n\">p<\/span><span class=\"p\">&gt;<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<p><strong>Fat-Razor<\/strong>: I\u2019ve coined this term to define ASP.NET Razor views with a lot of Razor\/C# code that is not presentation code. This is about the Razor\/C# code specifically and not about HTML\/CSS\/JS.<\/p>\n\n<p><strong>Model<\/strong>: This is an overloaded term. However, in this context, it is an object of data representation such as a record in the database.<\/p>\n\n<p><strong>Viewmodel<\/strong>: They are data transfer objects that are meant to be view-specific and to carry exactly what the view needs, no less and no more. Generally, viewmodels are non-reusable and each vm is meant to to be tightly coupled to one view, however, there are exceptions depending on what you are doing.<\/p>\n\n<p>To give you a flavour of a model and a viewmodel:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"c1\">\/\/ An example of a model<\/span>\n<span class=\"k\">public<\/span> <span class=\"k\">class<\/span> <span class=\"nc\">Person<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"k\">public<\/span> <span class=\"n\">Guid<\/span> <span class=\"n\">PersonId<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n    <span class=\"k\">public<\/span> <span class=\"kt\">string<\/span> <span class=\"n\">FirstName<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n    <span class=\"k\">public<\/span> <span class=\"kt\">string<\/span> <span class=\"n\">LastName<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n    <span class=\"k\">public<\/span> <span class=\"kt\">short<\/span> <span class=\"n\">YearOfBirth<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n    <span class=\"k\">public<\/span> <span class=\"n\">DateTime<\/span> <span class=\"n\">LastAuth<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n    <span class=\"c1\">\/\/ This might represent a one-to-many db relationship<\/span>\n    <span class=\"k\">public<\/span> <span class=\"n\">Order<\/span><span class=\"p\">[]<\/span> <span class=\"n\">Orders<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"c1\">\/\/ An example of a viewmodel<\/span>\n<span class=\"k\">public<\/span> <span class=\"k\">class<\/span> <span class=\"nc\">ProfileViewModel<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"c1\">\/\/ Doesn't necessarily need an id<\/span>\n\n    <span class=\"c1\">\/\/ Combined first and last name<\/span>\n    <span class=\"k\">public<\/span> <span class=\"kt\">string<\/span> <span class=\"n\">Name<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n    <span class=\"c1\">\/\/ Calculated from YearOfBirth<\/span>\n    <span class=\"k\">public<\/span> <span class=\"kt\">short<\/span> <span class=\"n\">Age<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n    <span class=\"c1\">\/\/ E.g. \"One day ago\" and constructed from LastAuth<\/span>\n    <span class=\"k\">public<\/span> <span class=\"kt\">string<\/span> <span class=\"n\">LastSeen<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n    <span class=\"c1\">\/\/ Calculated by projections on Orders<\/span>\n    <span class=\"k\">public<\/span> <span class=\"kt\">short<\/span> <span class=\"n\">NumberOfAllOrders<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n    <span class=\"k\">public<\/span> <span class=\"kt\">short<\/span> <span class=\"n\">NumberOfUndeliveredOrders<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<!--more-->\n\n<h2 id=\"why-would-it-hurt-to-have-fat-razor-views\">Why would it hurt to have Fat-Razor views?<\/h2>\n\n<p>Before we discuss a solution, we need to agree that there is a problem.<\/p>\n\n<h3 id=\"distribution-non-centralisation-of-business-logic\">Distribution (non-centralisation) of Business Logic<\/h3>\n\n<p>Fat-Razors carry similar criticism to what the old classical ASP had (and what PHP currently has), that is no separation of concerns. The concern of this piece of code is to show visuals and not to do business logic.<\/p>\n\n<p>The business logic for your domain should be centralised, having Fat-Razor views highlights the use of business logic in your views, hence you are giving more control to what should be a dumb layer and violating \u201cthe power in the wrong hand\u201d principle. You would be risking a fragile business logic that will break more often.<\/p>\n\n<p>Due to the scope of this post, I will just tell you \u201cIt is bad, don\u2019t do it\u201d and won\u2019t dive into this topic but don\u2019t take my word for it, here is Uncle Bob\u2019s <a href=\"https:\/\/blog.cleancoder.com\/uncle-bob\/2012\/08\/13\/the-clean-architecture.html\" target=\"_blank\">Clean Architecture<\/a>.<\/p>\n\n<h3 id=\"unit-testing\">Unit Testing<\/h3>\n\n<p>You\u2019e heard it before, views aren\u2019t unit testable (well, you can unit test them with some tools like <a href=\"https:\/\/marketplace.visualstudio.com\/items?itemName=DavidEbbo.RazorGenerator\" target=\"_blank\">Razor Generator<\/a> but this is not the norm), or maybe more accurately shouldn\u2019t be unit tested and should rely on different type of testing such as web testing like Visual Studio Testing Tools, Selenium or Capybara. So, Fat-Razor views mean more code you cannot unit test.<\/p>\n\n<h3 id=\"refactoring\">Refactoring<\/h3>\n\n<p>How many times did you change your code and compiled fine until you hit the page with your browser? And boom, your code refactoring did not propagate to the views, because it sees the views as text. Today, it is not that dramatic with tools like ReSharper, but it is still a problem. Having less C# code would reduce the problem size but not eliminate it.<\/p>\n\n<h2 id=\"why-would-views-become-fat-razor-views\">Why would views become Fat-Razor views?<\/h2>\n\n<p>This is my experience of the symptoms from the industry, feel free to highlight more reasons in comments.<\/p>\n\n<h3 id=\"using-a-generic-model-rather-than-a-specific-viewmodel\">Using a generic model rather than a specific viewmodel<\/h3>\n\n<p>The MVC beginner tutorials try to show how simple MVC is by loading a record from the DB, transferring it into an object with an OR Mapper (Entity Framework, NHibernate and the likes) and then passing it to the view which renders it. Building a blog with MVC tutorials, I am looking at you.<\/p>\n\n<p>Good example for beginners, gets them up to speed, but only works in trivial applications. Why? If your view is not getting exactly what it wants, then it is going to have to do some inspections on the model, hence, code and more code! If you treat the view as dumb and give it exactly what it wants, you will reduce the need for it to have any non-presentation logic.<\/p>\n\n<h2 id=\"get-your-fat-razor-into-shape\">Get your Fat-Razor into shape<\/h2>\n\n<p><img src=\"\/assets\/artefacts\/2013\/06\/razor-ramon.jpg\" alt=\"Razor Ramon\" \/><\/p>\n\n<p>Big Boss Man, RIP, was my early childhood wrestling hero (he was strong and cool!), but Razor Ramon fits better in this post.<\/p>\n\n<p>Now that I have touched some of the necessary concepts around this subject, I could highlight some steps for Thin-Razor views.<\/p>\n\n<h3 id=\"1--use-a-viewmodel-for-your-view\">1 \u2013 Use a viewmodel for your view<\/h3>\n\n<p>Do not take a model from the database and throw it directly into your view. This will couple your views to your entities and will probably invite business logic code.<\/p>\n\n<p>My favourite way of doing this is by using a <acronym title=\"Command Query Responsibility Segregation\">CQRS<\/acronym> type query, this article does a good job in introducing CQRS: <a href=\"https:\/\/www.codeproject.com\/Articles\/555855\/Introduction-to-CQRS\" target=\"_blank\">Introduction to CQRS<\/a>. I query exactly what my view needs into a viewmodel, no intermediate model (or DTO), have a look at <a href=\"https:\/\/github.com\/StackExchange\/Dapper\" target=\"_blank\">Dapper \u2013 a simple object mapper for .Net<\/a>.<\/p>\n\n<p>If you have a different architecture or legacy code, perhaps you could have a layer that would map a model into a viewmodel, have a look at <a href=\"https:\/\/github.com\/AutoMapper\/AutoMapper\" target=\"_blank\">AutoMapper<\/a>, it may help.<\/p>\n\n<h3 id=\"2--try-to-differentiate-business-from-presentation-code\">2 \u2013 Try to differentiate business from presentation code<\/h3>\n\n<p>When writing views, always flag the question \u201cIs this presentation code or business logic?\u201d This is a hard question as in some cases, it might be a fine line between the two. Sometimes I ask for a second opinion and encourage a healthy debate.<\/p>\n\n<h3 id=\"3--package-repeated-presentation-patterns-into-html-helpers-and-partial-views\">3 \u2013 Package repeated presentation patterns into Html Helpers and Partial Views<\/h3>\n\n<p>Sometimes one repeats the same presentation code again and again in different views. I do that as well following the agile principle \u201cDo the simplest thing that works, then refactor\u201d then when I notice a pattern forming, I do refactor it into a Html Helper or a Partial View.<\/p>\n\n<h2 id=\"conclusion\">Conclusion<\/h2>\n\n<p>As they say \u201cMore is less\u201d, the less code you write is the less code you have to maintain and the proper code you write will keep you safe if the developer inheriting the project, knows where you live.<\/p>\n\n<p>I did review this post multiple times to cut it shorter, however, it is a big topic and it is still not complete. If you have any points that you would like to share, then please do comment.<\/p>\n","pubDate":"Sun, 16 Jun 2013 01:33:00 +0000","link":"https:\/\/adamtibi.net\/06-2013\/three-steps-to-get-fat-razor-mvc-views-on-diet","guid":"https:\/\/adamtibi.net\/06-2013\/three-steps-to-get-fat-razor-mvc-views-on-diet","category":["Architecture","ASP.NET","C#","CodeProject","CQRS","MVC","Razor","Uncategorized"]},{"title":"Using C# .NET User Defined Functions (UDF) in Excel","description":"<figure>\n<img src=\"\/assets\/artefacts\/2012\/07\/excel-udf-with-c-sharp.png\" alt=\"Excel auto complete showing functions\" \/>\n<\/figure>\n\n<p><strong>N.B.<\/strong>Throughout this post I am using Excel 2010 and Visual Studio 2010.<\/p>\n\n<p>Writing a UDF in VBA to be exposed to Excel cells is straight forward, just write the function in a VBA module and Bob\u2019s your uncle. However, it is slightly trickier to expose your functions to Excel in a managed language, such as C# or F#.<\/p>\n\n<!--more-->\n\n<p>Essentially there are two ways to achieve this and for every method there are pros and cons:<\/p>\n\n<ol type=\"1\">\n  <li>\n    Automation Add-Ins Method\n  <\/li>\n  <li>\n    XLL Add-Ins Method\n  <\/li>\n<\/ol>\n\n<p>I will demonstrate how to implement each method then I will discuss my verdict. I have created a sample project in each method; you could download it at the end of this post.<\/p>\n\n<h2 id=\"automation-add-ins-method\">Automation Add-Ins Method<\/h2>\n\n<p><img src=\"\/assets\/artefacts\/2012\/07\/automation-project.png\" alt=\"Solution Explorer in Visual Studio showing the project structure\" class=\"alignright\" \/><\/p>\n\n<p>Automation Add-ins are COM functions to be called from formulas in Excel worksheets, it is supported since Excel 2002. The idea is that .NET can expose a COM interface that can be consumed from Excel through Automation Add-ins support.<\/p>\n\n<p>To create your custom functions, you need to create a new C# code library project from Visual Studio, then go to:<br \/>\nRight click Project &gt; Properties &gt; Build &gt; Register for COM Interop and enable it.<\/p>\n\n<p>Then go to Assembly.cs and set <code class=\"language-plaintext highlighter-rouge\">ComVisible<\/code> to <code class=\"language-plaintext highlighter-rouge\">true<\/code>. Then you need to create a base class that you will inherit later to create your UDF:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"k\">using<\/span> <span class=\"nn\">System<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">using<\/span> <span class=\"nn\">System.Runtime.InteropServices<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">using<\/span> <span class=\"nn\">Microsoft.Win32<\/span><span class=\"p\">;<\/span>\n\n<span class=\"k\">namespace<\/span> <span class=\"nn\">ExcelUdf.Automation<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"k\">public<\/span> <span class=\"k\">abstract<\/span> <span class=\"k\">class<\/span> <span class=\"nc\">UdfBase<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"p\">[<\/span><span class=\"n\">ComRegisterFunction<\/span><span class=\"p\">]<\/span>\n<span class=\"k\">public<\/span> <span class=\"k\">static<\/span> <span class=\"k\">void<\/span> <span class=\"nf\">ComRegisterFunction<\/span><span class=\"p\">(<\/span><span class=\"n\">Type<\/span> <span class=\"n\">type<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"n\">Registry<\/span><span class=\"p\">.<\/span><span class=\"n\">ClassesRoot<\/span><span class=\"p\">.<\/span><span class=\"nf\">CreateSubKey<\/span><span class=\"p\">(<\/span>\n        <span class=\"nf\">GetClsIdSubKeyName<\/span><span class=\"p\">(<\/span><span class=\"n\">type<\/span><span class=\"p\">,<\/span> <span class=\"s\">\"Programmable\"<\/span><span class=\"p\">));<\/span>\n\n    <span class=\"c1\">\/\/ Solves an intermittent issue where Excel<\/span>\n    <span class=\"c1\">\/\/ reports that it cannot find mscoree.dll<\/span>\n    <span class=\"c1\">\/\/ Register the full path to mscoree.dll.<\/span>\n    <span class=\"kt\">var<\/span> <span class=\"n\">key<\/span> <span class=\"p\">=<\/span> <span class=\"n\">Registry<\/span><span class=\"p\">.<\/span><span class=\"n\">ClassesRoot<\/span><span class=\"p\">.<\/span><span class=\"nf\">OpenSubKey<\/span><span class=\"p\">(<\/span>\n        <span class=\"nf\">GetClsIdSubKeyName<\/span><span class=\"p\">(<\/span><span class=\"n\">type<\/span><span class=\"p\">,<\/span> <span class=\"s\">\"InprocServer32\"<\/span><span class=\"p\">),<\/span> <span class=\"k\">true<\/span><span class=\"p\">);<\/span>\n    <span class=\"k\">if<\/span> <span class=\"p\">(<\/span><span class=\"n\">key<\/span> <span class=\"p\">==<\/span> <span class=\"k\">null<\/span><span class=\"p\">)<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"k\">return<\/span><span class=\"p\">;<\/span>\n    <span class=\"p\">}<\/span>\n    <span class=\"n\">key<\/span><span class=\"p\">.<\/span><span class=\"nf\">SetValue<\/span><span class=\"p\">(<\/span><span class=\"s\">\"\"<\/span><span class=\"p\">,<\/span> \n        <span class=\"n\">String<\/span><span class=\"p\">.<\/span><span class=\"nf\">Format<\/span><span class=\"p\">(<\/span><span class=\"s\">\"{0}\\\\mscoree.dll\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">Environment<\/span><span class=\"p\">.<\/span><span class=\"n\">SystemDirectory<\/span><span class=\"p\">),<\/span> \n        <span class=\"n\">RegistryValueKind<\/span><span class=\"p\">.<\/span><span class=\"n\">String<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"p\">[<\/span><span class=\"n\">ComUnregisterFunction<\/span><span class=\"p\">]<\/span>\n<span class=\"k\">public<\/span> <span class=\"k\">static<\/span> <span class=\"k\">void<\/span> <span class=\"nf\">ComUnregisterFunction<\/span><span class=\"p\">(<\/span><span class=\"n\">Type<\/span> <span class=\"n\">type<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"c1\">\/\/ Adds the \"Programmable\" registry key under CLSID<\/span>\n    <span class=\"n\">Registry<\/span><span class=\"p\">.<\/span><span class=\"n\">ClassesRoot<\/span><span class=\"p\">.<\/span><span class=\"nf\">DeleteSubKey<\/span><span class=\"p\">(<\/span>\n        <span class=\"nf\">GetClsIdSubKeyName<\/span><span class=\"p\">(<\/span><span class=\"n\">type<\/span><span class=\"p\">,<\/span> <span class=\"s\">\"Programmable\"<\/span><span class=\"p\">));<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">private<\/span> <span class=\"k\">static<\/span> <span class=\"kt\">string<\/span> <span class=\"nf\">GetClsIdSubKeyName<\/span><span class=\"p\">(<\/span><span class=\"n\">Type<\/span> <span class=\"n\">type<\/span><span class=\"p\">,<\/span> <span class=\"n\">String<\/span> <span class=\"n\">subKeyName<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"k\">return<\/span> <span class=\"kt\">string<\/span><span class=\"p\">.<\/span><span class=\"nf\">Format<\/span><span class=\"p\">(<\/span><span class=\"s\">\"CLSID\\\\&amp;#123;&amp;#123;&amp;#123;0&amp;#124;&amp;#124;&amp;#124;\\\\{1}\"<\/span><span class=\"p\">,<\/span> \n        <span class=\"n\">type<\/span><span class=\"p\">.<\/span><span class=\"n\">GUID<\/span><span class=\"p\">.<\/span><span class=\"nf\">ToString<\/span><span class=\"p\">().<\/span><span class=\"nf\">ToUpper<\/span><span class=\"p\">(),<\/span> <span class=\"n\">subKeyName<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"c1\">\/\/ Hiding these methods from Excel<\/span>\n<span class=\"p\">[<\/span><span class=\"nf\">ComVisible<\/span><span class=\"p\">(<\/span><span class=\"k\">false<\/span><span class=\"p\">)]<\/span>\n<span class=\"k\">public<\/span> <span class=\"k\">override<\/span> <span class=\"kt\">string<\/span> <span class=\"nf\">ToString<\/span><span class=\"p\">()<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"k\">return<\/span> <span class=\"k\">base<\/span><span class=\"p\">.<\/span><span class=\"nf\">ToString<\/span><span class=\"p\">();<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"p\">[<\/span><span class=\"nf\">ComVisible<\/span><span class=\"p\">(<\/span><span class=\"k\">false<\/span><span class=\"p\">)]<\/span>\n<span class=\"k\">public<\/span> <span class=\"k\">override<\/span> <span class=\"kt\">bool<\/span> <span class=\"nf\">Equals<\/span><span class=\"p\">(<\/span><span class=\"kt\">object<\/span> <span class=\"n\">obj<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"k\">return<\/span> <span class=\"k\">base<\/span><span class=\"p\">.<\/span><span class=\"nf\">Equals<\/span><span class=\"p\">(<\/span><span class=\"n\">obj<\/span><span class=\"p\">);<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"p\">[<\/span><span class=\"nf\">ComVisible<\/span><span class=\"p\">(<\/span><span class=\"k\">false<\/span><span class=\"p\">)]<\/span>\n<span class=\"k\">public<\/span> <span class=\"k\">override<\/span> <span class=\"kt\">int<\/span> <span class=\"nf\">GetHashCode<\/span><span class=\"p\">()<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"k\">return<\/span> <span class=\"k\">base<\/span><span class=\"p\">.<\/span><span class=\"nf\">GetHashCode<\/span><span class=\"p\">();<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<p>Then your UDF class should inherit <code class=\"language-plaintext highlighter-rouge\">UdfBase<\/code> as such:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"k\">using<\/span> <span class=\"nn\">System.Runtime.InteropServices<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">using<\/span> <span class=\"nn\">ExcelUdf.Automation<\/span><span class=\"p\">;<\/span>\n\n<span class=\"k\">namespace<\/span> <span class=\"nn\">AutomationSample<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"p\">[<\/span><span class=\"nf\">ClassInterface<\/span><span class=\"p\">(<\/span><span class=\"n\">ClassInterfaceType<\/span><span class=\"p\">.<\/span><span class=\"n\">AutoDual<\/span><span class=\"p\">)]<\/span>\n    <span class=\"p\">[<\/span><span class=\"nf\">Guid<\/span><span class=\"p\">(<\/span><span class=\"s\">\"7a9de936-0e99-4d37-9c2b-a02a09fb371f\"<\/span><span class=\"p\">)]<\/span>\n    <span class=\"k\">public<\/span> <span class=\"k\">class<\/span> <span class=\"nc\">AutomationSample<\/span> <span class=\"p\">:<\/span> <span class=\"n\">UdfBase<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"k\">public<\/span> <span class=\"kt\">double<\/span> <span class=\"nf\">AutomationSampleAdd<\/span><span class=\"p\">(<\/span><span class=\"kt\">double<\/span> <span class=\"n\">a<\/span><span class=\"p\">,<\/span> <span class=\"kt\">double<\/span> <span class=\"n\">b<\/span><span class=\"p\">)<\/span>\n        <span class=\"p\">{<\/span>\n            <span class=\"k\">return<\/span> <span class=\"n\">a<\/span> <span class=\"p\">+<\/span> <span class=\"n\">b<\/span><span class=\"p\">;<\/span>\n        <span class=\"p\">}<\/span>\n\n        <span class=\"k\">public<\/span> <span class=\"kt\">double<\/span> <span class=\"nf\">AutomationSampleSubtract<\/span><span class=\"p\">(<\/span><span class=\"kt\">double<\/span> <span class=\"n\">a<\/span><span class=\"p\">,<\/span> <span class=\"kt\">double<\/span> <span class=\"n\">b<\/span><span class=\"p\">)<\/span>\n        <span class=\"p\">{<\/span>\n            <span class=\"k\">return<\/span> <span class=\"n\">a<\/span> <span class=\"p\">-<\/span> <span class=\"n\">b<\/span><span class=\"p\">;<\/span>\n        <span class=\"p\">}<\/span>\n    <span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<p>Build your project, then the last step is opening an Excel file, going to: File &gt; Options then selecting Add-Ins. Select \u201cExcel Add-Ins\u201d in the drop down list and then hit \u201cGo\u2026\u201d. Select the \u201cAutomation\u201d button and select your component (in this example, the item name to select is <code class=\"language-plaintext highlighter-rouge\">AutomationSample.AutomationSample<\/code>).<\/p>\n\n<p>Write <code class=\"language-plaintext highlighter-rouge\">=AutomationSampleAdd(1,2)<\/code> in a worksheet cell and you should get 3.<\/p>\n\n<h2 id=\"automation-add-ins-method-with-a-reference-to-excel\">Automation Add-Ins Method with a Reference to Excel<\/h2>\n\n<p><img src=\"\/assets\/artefacts\/2012\/07\/automation-extensibility-project.png\" alt=\"Solution Explorer in Visual Studio showing the project structure\" class=\"alignright\" \/><\/p>\n\n<p>The previous method, mentioned above, allows Excel to call .NET, not the other way around. What if you want to have a reference to the Excel application executing your .NET code? Say to colour certain worksheet columns based on some criteria or for asynchronous call back. In this case, you need to implement <code class=\"language-plaintext highlighter-rouge\">IDTExtensibility2<\/code> interface.<\/p>\n\n<p>To implement this method, you need to reference the assemblies displayed to the right, inherit the <code class=\"language-plaintext highlighter-rouge\">UdfBase<\/code> abstract class and implement <code class=\"language-plaintext highlighter-rouge\">IDTExtensibility2<\/code> interface.<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"k\">using<\/span> <span class=\"nn\">System<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">using<\/span> <span class=\"nn\">ExcelUdf.Automation<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">using<\/span> <span class=\"nn\">Extensibility<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">using<\/span> <span class=\"nn\">Microsoft.Office.Interop.Excel<\/span><span class=\"p\">;<\/span>\n\n<span class=\"k\">namespace<\/span> <span class=\"nn\">ExcelUdf.ExtensibilityAutomation<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"k\">public<\/span> <span class=\"k\">abstract<\/span> <span class=\"k\">class<\/span> <span class=\"nc\">UdfExtensibilityBase<\/span> <span class=\"p\">:<\/span> <span class=\"n\">UdfBase<\/span><span class=\"p\">,<\/span> <span class=\"n\">IDTExtensibility2<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"k\">protected<\/span> <span class=\"n\">Application<\/span> <span class=\"n\">ExcelApplication<\/span> <span class=\"p\">{<\/span> <span class=\"k\">get<\/span><span class=\"p\">;<\/span> <span class=\"k\">set<\/span><span class=\"p\">;<\/span> <span class=\"p\">}<\/span>\n\n<span class=\"k\">public<\/span> <span class=\"k\">void<\/span> <span class=\"nf\">OnConnection<\/span><span class=\"p\">(<\/span><span class=\"kt\">object<\/span> <span class=\"n\">application<\/span><span class=\"p\">,<\/span> \n    <span class=\"n\">ext_ConnectMode<\/span> <span class=\"n\">connectMode<\/span><span class=\"p\">,<\/span> <span class=\"kt\">object<\/span> <span class=\"n\">addInInst<\/span><span class=\"p\">,<\/span>\n    <span class=\"k\">ref<\/span> <span class=\"n\">Array<\/span> <span class=\"n\">custom<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"n\">ExcelApplication<\/span> <span class=\"p\">=<\/span> <span class=\"n\">application<\/span> <span class=\"k\">as<\/span> <span class=\"n\">Application<\/span><span class=\"p\">;<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">public<\/span> <span class=\"k\">void<\/span> <span class=\"nf\">OnDisconnection<\/span><span class=\"p\">(<\/span><span class=\"n\">ext_DisconnectMode<\/span> <span class=\"n\">removeMode<\/span><span class=\"p\">,<\/span> \n    <span class=\"k\">ref<\/span> <span class=\"n\">Array<\/span> <span class=\"n\">custom<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">public<\/span> <span class=\"k\">void<\/span> <span class=\"nf\">OnAddInsUpdate<\/span><span class=\"p\">(<\/span><span class=\"k\">ref<\/span> <span class=\"n\">Array<\/span> <span class=\"n\">custom<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">public<\/span> <span class=\"k\">void<\/span> <span class=\"nf\">OnStartupComplete<\/span><span class=\"p\">(<\/span><span class=\"k\">ref<\/span> <span class=\"n\">Array<\/span> <span class=\"n\">custom<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"p\">}<\/span>\n\n<span class=\"k\">public<\/span> <span class=\"k\">void<\/span> <span class=\"nf\">OnBeginShutdown<\/span><span class=\"p\">(<\/span><span class=\"k\">ref<\/span> <span class=\"n\">Array<\/span> <span class=\"n\">custom<\/span><span class=\"p\">)<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<p>In my download project, I implemented this class in a standalone project rather than combining it with the existing one. The reason is this approach requires references to specific Excel interop component version. And once you have these references, your deployment project is increased in complexity as now you need to manage more dependencies and make sure that the right referenced version of Excel is installed on the target machine (check <a href=\"https:\/\/osdn.net\/projects\/netoffice\/\" target=\"_blank\">NetOffice<\/a> if you want to avoid that).<\/p>\n\n<p>To create your UDF methods and to have a reference to the current Excel instance:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"k\">using<\/span> <span class=\"nn\">System.Runtime.InteropServices<\/span><span class=\"p\">;<\/span>\n<span class=\"k\">using<\/span> <span class=\"nn\">ExcelUdf.ExtensibilityAutomation<\/span><span class=\"p\">;<\/span>\n\n<span class=\"k\">namespace<\/span> <span class=\"nn\">ExtensibilitySample<\/span>\n<span class=\"p\">{<\/span>\n<span class=\"p\">[<\/span><span class=\"nf\">ClassInterface<\/span><span class=\"p\">(<\/span><span class=\"n\">ClassInterfaceType<\/span><span class=\"p\">.<\/span><span class=\"n\">AutoDual<\/span><span class=\"p\">)]<\/span>\n<span class=\"p\">[<\/span><span class=\"nf\">Guid<\/span><span class=\"p\">(<\/span><span class=\"s\">\"7a9de936-0e99-4d38-9c2b-a02a09fb371f\"<\/span><span class=\"p\">)]<\/span>\n<span class=\"k\">public<\/span> <span class=\"k\">class<\/span> <span class=\"nc\">ExtensibilitySample<\/span> <span class=\"p\">:<\/span> <span class=\"n\">UdfExtensibilityBase<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"k\">public<\/span> <span class=\"kt\">double<\/span> <span class=\"nf\">ExtensibilitySampleAdd<\/span><span class=\"p\">(<\/span><span class=\"kt\">double<\/span> <span class=\"n\">a<\/span><span class=\"p\">,<\/span> <span class=\"kt\">double<\/span> <span class=\"n\">b<\/span><span class=\"p\">)<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"k\">return<\/span> <span class=\"n\">a<\/span> <span class=\"p\">+<\/span> <span class=\"n\">b<\/span><span class=\"p\">;<\/span>\n    <span class=\"p\">}<\/span>\n\n    <span class=\"k\">public<\/span> <span class=\"kt\">string<\/span> <span class=\"nf\">WhoAreYou<\/span><span class=\"p\">()<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"kt\">string<\/span> <span class=\"n\">name<\/span> <span class=\"p\">=<\/span> \n           <span class=\"n\">ExcelApplication<\/span><span class=\"p\">.<\/span><span class=\"n\">Application<\/span><span class=\"p\">.<\/span><span class=\"nf\">InputBox<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Who are you?\"<\/span><span class=\"p\">);<\/span>\n        <span class=\"k\">if<\/span> <span class=\"p\">(<\/span><span class=\"kt\">string<\/span><span class=\"p\">.<\/span><span class=\"nf\">IsNullOrWhiteSpace<\/span><span class=\"p\">(<\/span><span class=\"n\">name<\/span><span class=\"p\">))<\/span>\n        <span class=\"p\">{<\/span>\n            <span class=\"k\">return<\/span> <span class=\"kt\">string<\/span><span class=\"p\">.<\/span><span class=\"n\">Empty<\/span><span class=\"p\">;<\/span>\n        <span class=\"p\">}<\/span>\n        <span class=\"k\">return<\/span> <span class=\"s\">\"Hello \"<\/span> <span class=\"p\">+<\/span> <span class=\"n\">name<\/span><span class=\"p\">;<\/span>\n    <span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<p>Use this project with Excel as mentioned above.<\/p>\n\n<h2 id=\"xll-add-ins-method\">XLL Add-Ins Method<\/h2>\n<figure class=\"alignright\">\n<img src=\"\/assets\/artefacts\/2012\/07\/xll-excel-dna.png\" alt=\"Solution Explorer in Visual Studio showing the project structure\" \/> \n<\/figure>\n\n<p>An XLL is an add-in for Excel that you can build with any compiler that supports building native DLLs (dynamic link libraries), it is supported since Excel 97. It is faster than the Automation Add-Ins and has more features, but XLL components are usually built via C\/C++.<\/p>\n\n<p>Luckily for .NET, there is an open source component with permissive licence called <a href=\"https:\/\/github.com\/Excel-DNA\/ExcelDna\" target=\"_blank\">Excel DNA<\/a> that allows .NET to build XLL add-ins effortlessly.<\/p>\n\n<p>To build an XLL component, create a new project, download <a href=\"https:\/\/github.com\/Excel-DNA\/ExcelDna\" target=\"_blank\">Excel DNA<\/a> and reference <code class=\"language-plaintext highlighter-rouge\">ExcelDna.Integration.dll<\/code> then write your functions<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-cs\" data-lang=\"cs\"><span class=\"k\">using<\/span> <span class=\"nn\">ExcelDna.Integration<\/span><span class=\"p\">;<\/span>\n\n<span class=\"k\">namespace<\/span> <span class=\"nn\">XllSample<\/span>\n<span class=\"p\">{<\/span>\n    <span class=\"k\">public<\/span> <span class=\"k\">class<\/span> <span class=\"nc\">XllSample<\/span>\n    <span class=\"p\">{<\/span>\n        <span class=\"p\">[<\/span><span class=\"nf\">ExcelFunction<\/span><span class=\"p\">(<\/span><span class=\"n\">Description<\/span> <span class=\"p\">=<\/span> <span class=\"s\">\"Adds two numbers\"<\/span><span class=\"p\">,<\/span> \n                <span class=\"n\">Category<\/span> <span class=\"p\">=<\/span> <span class=\"s\">\"XLL with .NET Sample Function\"<\/span><span class=\"p\">)]<\/span>\n        <span class=\"k\">public<\/span> <span class=\"k\">static<\/span> <span class=\"kt\">double<\/span> <span class=\"nf\">XllSampleAdd<\/span><span class=\"p\">(<\/span><span class=\"kt\">double<\/span> <span class=\"n\">a<\/span><span class=\"p\">,<\/span> <span class=\"kt\">double<\/span> <span class=\"n\">b<\/span><span class=\"p\">)<\/span>\n        <span class=\"p\">{<\/span>\n            <span class=\"k\">return<\/span> <span class=\"n\">a<\/span> <span class=\"p\">+<\/span> <span class=\"n\">b<\/span><span class=\"p\">;<\/span>\n        <span class=\"p\">}<\/span>\n    <span class=\"p\">}<\/span>\n<span class=\"p\">}<\/span><\/code><\/pre><\/figure>\n\n<p>Build then create a file called <code class=\"language-plaintext highlighter-rouge\">YourDllName.dna<\/code>, in this case <code class=\"language-plaintext highlighter-rouge\">XllSample.dna<\/code> with the following content:<\/p>\n\n<figure class=\"highlight\"><pre><code class=\"language-xml\" data-lang=\"xml\"><span class=\"nt\">&lt;DnaLibrary<\/span> <span class=\"na\">RuntimeVersion=<\/span><span class=\"s\">\"v4.0\"<\/span><span class=\"nt\">&gt;<\/span>\n\t<span class=\"nt\">&lt;ExternalLibrary<\/span> <span class=\"na\">Path=<\/span><span class=\"s\">\"XllSample.dll\"<\/span> <span class=\"nt\">\/&gt;<\/span>\n<span class=\"nt\">&lt;\/DnaLibrary&gt;<\/span><\/code><\/pre><\/figure>\n\n<figure class=\"alignright\">\n<img src=\"\/assets\/artefacts\/2012\/07\/excel-dna-folder-structure.png\" alt=\"Excel DNA folder structure\" \/> \n<\/figure>\n\n<p>Drop it next to your dll, then copy <code class=\"language-plaintext highlighter-rouge\">ExcelDna.xll<\/code> or <code class=\"language-plaintext highlighter-rouge\">ExcelDna64.xll<\/code> next to your dll and rename it to match your dll name, in this case <code class=\"language-plaintext highlighter-rouge\">XllSample.xll<\/code>.<\/p>\n\n<p>Build your project, then the last step is opening an Excel file, going to: File &gt; Options then selecting Add-Ins. Select \u201cExcel Add-Ins\u201d in the drop down list and then hit \u201cGo\u2026\u201d. Select the \u201cBrowse\u201d button and select your <code class=\"language-plaintext highlighter-rouge\">XllSample.xll<\/code>.<\/p>\n\n<p>In an Excel cell, start typing <code class=\"language-plaintext highlighter-rouge\">XllSampleAdd<\/code> and you will get the rest of the function via Excel\u2019s auto complete.<\/p>\n\n<h2 id=\"comparison\">Comparison<\/h2>\n\n<p>Here is a comparison table between the two methods:<\/p>\n\n<table class=\"comparison\">\n  <tr>\n    <th>\n    <\/th>\n    <th>\n      Automation Add-Ins\n    <\/th>\n    <th>\n      XLL Add-Ins\n    <\/th>\n  <\/tr>\n  \n  <tr>\n    <td>\n      Minimum Supported Version\n    <\/td>\n    <td>\n      Excel 2002\n    <\/td>\n    <td>\n      Excel 97\n    <\/td>\n  <\/tr>\n  \n  <tr>\n    <td>\n      Performance\n    <\/td>\n    <td>\n      Slower\n    <\/td>\n    <td>\n      Faster\n    <\/td>\n  <\/tr>\n  \n  <tr>\n    <td>\n      UDF Auto complete\n    <\/td>\n    <td>\n      Not supported\n    <\/td>\n    <td>\n      Supported\n    <\/td>\n  <\/tr>\n  \n  <tr>\n    <td>\n      UDF Documentation Tooltip\n    <\/td>\n    <td>\n      Not supported\n    <\/td>\n    <td>\n      Supported\n    <\/td>\n  <\/tr>\n  \n  <tr>\n    <td>\n      Building in .NET\n    <\/td>\n    <td>\n      Easier\n    <\/td>\n    <td>\n      Harder (without a 3<sup>rd<\/sup> party component)\n    <\/td>\n  <\/tr>\n<\/table>\n\n<h2 id=\"conclusion\">Conclusion<\/h2>\n\n<p>Automation Add-Ins support feels more like it is made with VB6 in mind rather than .NET and lacks some important features like auto complete and description when typing in a cell.<\/p>\n\n<p>XLL Add-Ins per se are complicated from a .NET development point of view, however, Excel DNA did an excellent job in making the interface transparent and abstracted all the nifty details away for the .NET developers.<\/p>\n\n<h2 id=\"download\">Download<\/h2>\n\n<p>I have created a Visual Studio 2010 project with all the sample code demonstrated above, feel free to use it and distribute it.<\/p>\n\n<p class=\"download\">\n  <a href=\"\/assets\/artefacts\/2012\/07\/excel-udf-c-sharp-sample.zip\">Excel UDF with C# Sample (203 KB)<\/a>\n<\/p>\n","pubDate":"Mon, 30 Jul 2012 00:46:00 +0000","link":"https:\/\/adamtibi.net\/07-2012\/using-c-sharp-net-user-defined-functions-udf-in-excel","guid":"https:\/\/adamtibi.net\/07-2012\/using-c-sharp-net-user-defined-functions-udf-in-excel","category":["Automation","CodeProject","COM","Excel","Excel DNA","UDF","User Defined Functions","Uncategorized"]},{"title":"PayPal Charity Hack 2010 and JustGiving REST APIs","description":"<figure>\n  <img src=\"\/assets\/artefacts\/2010\/09\/adam-tibi-paypal-charity-hack-2010-speaking-to-the-audience.jpg\" alt=\"Adam Tibi at Paypal Charity Hack 2010 speaking to the audience\" \/>\n  <figcaption>Speaking to the audience about JustGiving's RESTful APIs<\/figcaption>\n<\/figure>\n\n<p><a href=\"http:\/\/charityhack.org\/\" target=\"_blank\">Charity Hack<\/a> is an annual event held and sponsored by PayPal UK at their venue in Richmond, London on a Saturday and a Sunday. It is an event where developers from different backgrounds are invited and introduced to different charity-relaled organisations APIs where developers are encouraged to hack useful apps using these APIs.<\/p>\n\n<p>We introduced, as JustGiving, our new <a href=\"https:\/\/developer.justgiving.com\/\" target=\"_blank\">RESTful APIs<\/a> and demonstrated how to use them.<\/p>\n\n<figure>\n  <img src=\"\/assets\/artefacts\/2010\/09\/adam-tibi-paypal-charity-hack-2010-back-to-camera.jpg\" alt=\"Adam Tibi Paypal Charity Hack 2010 speaking to the developers (back to camera)\" \/>\n  <figcaption>Having a discussion with JustGiving developers (back to camera)<\/figcaption>\n<\/figure>\n","pubDate":"Mon, 20 Sep 2010 09:52:00 +0000","link":"https:\/\/adamtibi.net\/09-2010\/paypal-charity-hack-2010-and-justgiving-rest-apis","guid":"https:\/\/adamtibi.net\/09-2010\/paypal-charity-hack-2010-and-justgiving-rest-apis","category":["REST","Uncategorized"]}]}}