<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Rui Figueiredo</title>
    <description>The latest articles on DEV Community by Rui Figueiredo (@ruidfigueiredo).</description>
    <link>https://dev.to/ruidfigueiredo</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F2691%2Fskype.jpg</url>
      <title>DEV Community: Rui Figueiredo</title>
      <link>https://dev.to/ruidfigueiredo</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/ruidfigueiredo"/>
    <language>en</language>
    <item>
      <title>How to get perfect intellisense in JavaScript</title>
      <dc:creator>Rui Figueiredo</dc:creator>
      <pubDate>Tue, 20 Oct 2020 10:13:18 +0000</pubDate>
      <link>https://dev.to/ruidfigueiredo/how-to-get-perfect-intellisense-in-javascript-34jd</link>
      <guid>https://dev.to/ruidfigueiredo/how-to-get-perfect-intellisense-in-javascript-34jd</guid>
      <description>&lt;p&gt;TypeScript is often described as the solution for making large scale JavaScript projects manageable. One of the arguments supporting this claim is that having type information helps catch a lot of mistakes that are easy to make and hard to spot.&lt;/p&gt;

&lt;p&gt;Adopting TypeScript might not always be an option, either because you are dealing with an old codebase or even by choice.&lt;/p&gt;

&lt;p&gt;Whatever the reason for sticking with plain JavaScript, it is possible to get a nearly identical development experience in terms of having intellisense and development time error highlighting. That is the topic of this blog post.&lt;/p&gt;

&lt;h2&gt;
  
  
  VS Code and JavaScript intellisense
&lt;/h2&gt;

&lt;p&gt;If you create a new &lt;code&gt;index.js&lt;/code&gt; in VS Code and type &lt;code&gt;conso&lt;/code&gt; followed by &lt;code&gt;Ctrl+space&lt;/code&gt; (or the Mac equivalent) you'll see something similar to this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--hKRUno7i--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/intellisense_console.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--hKRUno7i--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/intellisense_console.png" alt="Intellisense for 'conso' in VS Code"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The source of the intellisense data is from the type definition files that that are bundled with VS Code, namely console is defined in &lt;code&gt;[VS Code installation folder]/code/resources/app/extensions/node_modules/typescript/lib/lib.dom.d.ts&lt;/code&gt;. All the files with the &lt;code&gt;.d.ts&lt;/code&gt; extension in that folder will contribute for what you see in the intellisense dropdown.&lt;/p&gt;

&lt;p&gt;TypeScript definition files are one of the sources of intellisense in VS Code.&lt;/p&gt;

&lt;p&gt;They are not the only source though. Another source is what VS Code infers from your code.&lt;/p&gt;

&lt;p&gt;Here's an example of declaring a variable and assigning it a value. The intellisense is coherent with the type of that value:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--xzRncgIZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/string_intellisense.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--xzRncgIZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/string_intellisense.png" alt="string intellisense example"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;(and yes, you can call &lt;code&gt;.blink()&lt;/code&gt; or &lt;code&gt;.bold()&lt;/code&gt; on a string, even in Node.js)&lt;/p&gt;

&lt;p&gt;Here's another example where the type is inferred from the usage of a variable in a class definition:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zWIiHF86--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/class_intellisense.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zWIiHF86--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/class_intellisense.png" alt="class where a variable is used as a number and as a string, the inferred type is number or string"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;And additionally to type inference, VS Code will add all the unique words on the file you are editing to the intellisense dropdown:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--fBseSecq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/fall_back_to_words_in_file.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--fBseSecq--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/fall_back_to_words_in_file.png" alt="intellisense dropdown with methods from a class plus all the unique words in the file"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Even though the type inference available in VS Code is very clever, it's also very passive.&lt;/p&gt;

&lt;p&gt;It won't warn you if you call &lt;code&gt;myInstance.pethodName()&lt;/code&gt; instead of &lt;code&gt;myInstance.methodName()&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--zsOSr9de--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/no_error_highlighting.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--zsOSr9de--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/no_error_highlighting.png" alt="incorrect method name and no error highlighting"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We usually only figure this out at runtime when we get a &lt;code&gt;TypeError: myInstance.pethodA is not a function&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Turns out that VS Code has a flag that is turned off by default that when turned on will enable type checking to run through your code, and report errors:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--fhAPVRn0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/check_js_enabled.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--fhAPVRn0--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/check_js_enabled.png" alt="checkjs highlights that pmethod doesn't exist in myInstance"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The flag name is called &lt;code&gt;checkJs&lt;/code&gt; and the easiest way to enable it is to open "Show all commands" (&lt;code&gt;Ctrl+Shift+p&lt;/code&gt;) and type "Open workspace settings" and then activate checkJs:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--9X55qGRP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/enable_check_js.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--9X55qGRP--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/enable_check_js.gif" alt="animation showing the opening of all commands typing open workspace and then clicking checkjs"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You might discover that after turning on &lt;code&gt;checkJs&lt;/code&gt; your file turns into a Christmas Tree of red squiggles. Some of these might be legitimate errors, but sometimes they might not. It doesn't happen often but I've encountered instances where the type definition files for a JavaScript library don't match the latest version (how this happens will become clearer later in the blog post).&lt;/p&gt;

&lt;p&gt;If this happens and you are sure that the code you have is correct you can always add at the very top of the file:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//@ts-nocheck
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This will turn off type checking for the whole file. If you just want to ignore a statement you add this immediately before the statement to be ignored:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//@ts-ignore
variableThatHoldsANumber = false; //this won't be reported as an error
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Manually providing type information in JavaScript
&lt;/h2&gt;

&lt;p&gt;There are situation where it is impossible for type inference to figure out the type information about a variable.&lt;/p&gt;

&lt;p&gt;For example, if you call a REST endpoint and get a list of orders:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const orders = await getOrdersForClient(clientId);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;There's not enough information available for any useful type inference there. The "shape" of what an order looks like depends on what the server that hosts the REST api sends to us.&lt;/p&gt;

&lt;p&gt;We can, however, specify what an order looks like using &lt;a href="https://jsdoc.app/"&gt;JsDoc&lt;/a&gt; comments, and those will be picked up by VS Code and used to provide intellisense.&lt;/p&gt;

&lt;p&gt;Here's how that could look like for the orders:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/** @type {Array&amp;lt;{id: string, quantity: number, unitPrice: number, description: string}&amp;gt;} */
const orders = await getOrdersForClient(clientId);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here's how that looks like in VS Code when you access an order:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EEpDCTlQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/jsdoc_type_annotation.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EEpDCTlQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/jsdoc_type_annotation.png" alt="Intellisense sourced from JsDoc annotations"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Even though this can look a little bit cumbersome it's almost as flexible having TypeScript type information. &lt;strong&gt;Also, you can add it just where you need it&lt;/strong&gt;. I found that if I'm not familiar with a legacy codebase that has no documentation, adding this type of &lt;code&gt;JsDoc&lt;/code&gt; annotations can be really helpful in the process of becoming familiar with the codebase.&lt;/p&gt;

&lt;p&gt;Here are some examples of what you can do with &lt;code&gt;JsDoc&lt;/code&gt; type annotations:&lt;/p&gt;

&lt;h3&gt;
  
  
  Define a type and use it multiple times
&lt;/h3&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
* @typedef {object} MyType
* @property {string} aString
* @property {number} aNumber
* @property {Date} aDate
*/

/** @type {MyType} */
let foo;
/** @type {MyType} */
let bar;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If you use &lt;code&gt;@typedef&lt;/code&gt; in a file that is a module (for VS Code to assume this there only needs to be an &lt;code&gt;exports&lt;/code&gt; statement in the file) you can even import the type information from another file.&lt;/p&gt;

&lt;p&gt;For example if &lt;code&gt;@typedef&lt;/code&gt; is in a file named &lt;code&gt;my-type.js&lt;/code&gt; and you type this from &lt;code&gt;another-file.js&lt;/code&gt; in the same folder:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/** @type {import('./my_type').MyType} */
let baz;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The intellisense for the &lt;code&gt;baz&lt;/code&gt; variable will be based on &lt;code&gt;MyType&lt;/code&gt;'s type information.&lt;/p&gt;

&lt;h3&gt;
  
  
  Function parameters and return values
&lt;/h3&gt;

&lt;p&gt;Another scenario where type inference can't do much is regarding the parameter types in function definitions. For example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function send(type, args, onResponse) {
    //...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;There's not much that can be inferred here regarding the parameters &lt;code&gt;type&lt;/code&gt;, &lt;code&gt;args&lt;/code&gt; and &lt;code&gt;onResponse&lt;/code&gt;. It's the same for the return value of the function.&lt;/p&gt;

&lt;p&gt;Thankfully there's &lt;code&gt;JsDoc&lt;/code&gt; constructs that we can use to describe all of those, here's how it would look like if &lt;code&gt;type&lt;/code&gt; is a &lt;code&gt;string&lt;/code&gt;, &lt;code&gt;args&lt;/code&gt; can be anything and &lt;code&gt;onResponse&lt;/code&gt; is an &lt;strong&gt;optional&lt;/strong&gt; function function with two arguments, &lt;code&gt;error&lt;/code&gt; and &lt;code&gt;result&lt;/code&gt; and finally the return value is a &lt;code&gt;Promise&lt;/code&gt; or nothing.&lt;/p&gt;

&lt;p&gt;It's a pretty involved example, but it serves to illustrate that there's really no restrictions on the type information we can provide. Here's how that would look like:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
 * You can add a normal comment here and that will show up when calling the function
 * @param {string} type You can add extra info after the params
 * @param {any} args As you type each param you'll see the intellisense updated with this description
 * @param {(error: any, response: any) =&amp;gt; void} [onResponse]
 * @returns {Promise&amp;lt;any&amp;gt; | void} You can add extra an description here after returns
 */
function send(type, args, onResponse) {
    //...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And here it is in action:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--H3LsAoyI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/function_parameters_optimized-2.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--H3LsAoyI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/function_parameters_optimized-2.gif" alt="Animated gif that shows how intellisense is displayed as you type the function name and then its parameters"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Class and inheritance
&lt;/h3&gt;

&lt;p&gt;One thing that happens often is that you have to create a class that inherits from other classes. Sometimes these classes can even be templeted.&lt;/p&gt;

&lt;p&gt;This is very common for example with React where it's useful to have intellisense for the props and state of a class component. Here's how we could do that for a component named &lt;code&gt;ClickCounter&lt;/code&gt; whose state is a property named &lt;code&gt;count&lt;/code&gt; which is a number and that also has a component &lt;em&gt;prop&lt;/em&gt; named &lt;code&gt;message&lt;/code&gt; of type string:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/** @extends {React.Component&amp;lt;{message: string}, {count: number}&amp;gt;}  */
export class ClickCounter extends React.Component {
    //this @param jsdoc statement is required if you want intellisense
    //in the ctor, to avoid repetition you can always define a @typedef
    //and reuse the type
    /** @param { {message: string} } props */
    constructor(props) {
        super(props);
        this.state = {
            count: 0,
        }
    }

    render() {
        return (
            &amp;lt;div onClick={_ =&amp;gt; this.setState({ count: this.state.count + 1 })}&amp;gt;{this.props.message} - {this.state.count} &amp;lt;/div&amp;gt;
        );
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This is how it looks like when you are using your component:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--cnba-f_B--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/intellisense_in_jsx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cnba-f_B--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/09/intellisense_in_jsx.png" alt="Intellisense in JSX"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This also possible in function components, for example this function component would have the same intellisense on usage than the class component from the example above:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/**
* @param {object} props
* @param {string} props.message
*/
export function ClickCounter(props) {
    const [count, setCount] = useState(0);

    return (
        &amp;lt;div onClick={_ =&amp;gt; setCount(count + 1)}&amp;gt;{props.message} - {count} &amp;lt;/div&amp;gt;
    );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Casting
&lt;/h3&gt;

&lt;p&gt;Sometimes you might want to force a variable to be of a particular type, for example imagine you have a variable that can be either a number or a string and you have this:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (typeof numberOrString === 'string') {
    //there will be intellisense for substring
    const firstTwoLetters = /** @type {string} */ (numberOrString).substring(0, 2);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  Use type information from other modules
&lt;/h3&gt;

&lt;p&gt;Imagine you are writing code in Node.js and you have the following function:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function doSomethignWithAReadableStream(stream) {
    //...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;To enable intellisense for the &lt;code&gt;stream&lt;/code&gt; parameter as a readable stream we need the type information that is in the stream module. We have to use the import syntax like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;/** @param {import('stream').Readable} stream */
function doSomethindWithAReadableStream(stream) {
    //...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;There might be cases though where the module you want to import the type from isn't available out of the box (as stream is). In those cases you can install an npm package with just the type information from &lt;a href="https://definitelytyped.org/"&gt;DefinitelyTyped&lt;/a&gt;. There's even a &lt;a href="https://www.typescriptlang.org/dt/search?search="&gt;search tool&lt;/a&gt; for looking up the correct package with the typing information you need for a specific npm package.&lt;/p&gt;

&lt;p&gt;For example, imagine you wanted typing information for &lt;code&gt;mocha&lt;/code&gt;'s options, you'd install the type definition package:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install @types/mocha --save-dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And then you could reference them in &lt;code&gt;JsDoc&lt;/code&gt; and get intellisense for the options:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--nzhhdC-K--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/10/mocha_options.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--nzhhdC-K--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/10/mocha_options.png" alt="example of intellisense for mocha's options"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  Providing type information to consumers of your module/package
&lt;/h2&gt;

&lt;p&gt;If you were to create a module that exposed functions and classes with the &lt;code&gt;JsDoc&lt;/code&gt; type annotations that we've been looking at in this blog post, you'd get intellisense for them when that module is consumed from another module.&lt;/p&gt;

&lt;p&gt;There's an alternative way of doing this though, with type definition files. Say you have this very simple module using &lt;code&gt;CommonJS&lt;/code&gt; and this module is defined in a file named &lt;code&gt;say-hello.js&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function sayHello(greeting) {
    console.log(greeting);
}

module.exports = {
    sayHello
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If you create a file named &lt;code&gt;say-hello.d.ts&lt;/code&gt; (and place it in the same folder as &lt;code&gt;say-hello.js&lt;/code&gt;) with this inside:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export function sayHello(message: string): void;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And you import this function in another module, you'll get the the typing information defined in the &lt;code&gt;.d.ts&lt;/code&gt; file.&lt;/p&gt;

&lt;p&gt;In fact, this is the type of file that the TypeScript compiler generates (along with the &lt;code&gt;.js&lt;/code&gt; files) when you compile with the &lt;code&gt;--declaration&lt;/code&gt; flag.&lt;/p&gt;

&lt;p&gt;As a small aside, say that you are creating an npm module written totally in JavaScript that you want to share. Also, you haven't included any &lt;code&gt;JsDoc&lt;/code&gt; type annotations but you still want to provide intellisense.&lt;/p&gt;

&lt;p&gt;You can create a type declaration file, usually named &lt;code&gt;index.d.ts&lt;/code&gt; or &lt;code&gt;main.d.ts&lt;/code&gt; and update your &lt;code&gt;package.json&lt;/code&gt; with the &lt;code&gt;types&lt;/code&gt; (or &lt;code&gt;typings&lt;/code&gt;) property set to the path to that file:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "name": "the-package-name",
    "author": "Rui",
    "version": "1.0.0",
    "main": "main.js",
    "types": "index.d.ts"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The type declarations that you put in &lt;code&gt;index.d.ts&lt;/code&gt; define the intellisense you'll get when you consume the npm package.&lt;/p&gt;

&lt;p&gt;The contents of &lt;code&gt;index.d.ts&lt;/code&gt; don't even have to match the code in the module (in fact that's what the type definition packages in &lt;a href="https://definitelytyped.org/"&gt;&lt;code&gt;DefinitelyTyped&lt;/code&gt;&lt;/a&gt; do).&lt;/p&gt;

&lt;p&gt;I'm intentionally leaving the topic of how to write typescript definition files very light here because it's a very dense topic and it's usually easy to find how to provide type information in most cases in the &lt;a href="https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html"&gt;official docs&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;A quick note about TypeScript definition files: a &lt;code&gt;.d.ts&lt;/code&gt; file does &lt;strong&gt;not&lt;/strong&gt; affect the file it "describes", i.e. if you create a type declaration file for module &lt;code&gt;my-module.js&lt;/code&gt; and in that type declaration file you specify that &lt;code&gt;functionA&lt;/code&gt; receives a parameter of type &lt;code&gt;number&lt;/code&gt; and you invoke that function from &lt;code&gt;functionB&lt;/code&gt; also inside &lt;code&gt;my-module&lt;/code&gt; you won't get intellisense for &lt;code&gt;functionA&lt;/code&gt;. Only modules that require/import &lt;code&gt;my-module&lt;/code&gt; will take advantage of the type information in the type declaration file.&lt;/p&gt;

&lt;p&gt;That's it, now think about that large 30+ property configuration object for which you can never remember the exact name of the property you want to set (is it &lt;code&gt;includeArrayIndex&lt;/code&gt; or &lt;code&gt;enableArrayIndex&lt;/code&gt; and does it take a &lt;code&gt;boolean&lt;/code&gt; or a &lt;code&gt;string&lt;/code&gt;?). Now you don't have to worry about mistyping it and you don't have to look it up everytime.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>productivity</category>
      <category>node</category>
    </item>
    <item>
      <title>The story of how I created a way to port Windows Apps to Linux</title>
      <dc:creator>Rui Figueiredo</dc:creator>
      <pubDate>Thu, 09 Apr 2020 22:19:57 +0000</pubDate>
      <link>https://dev.to/ruidfigueiredo/the-story-of-how-i-created-a-way-to-port-windows-apps-to-linux-91j</link>
      <guid>https://dev.to/ruidfigueiredo/the-story-of-how-i-created-a-way-to-port-windows-apps-to-linux-91j</guid>
      <description>&lt;p&gt;Some day during a weekend sometime around the summer in 2018 I was doing house chores while listening to a podcast.&lt;/p&gt;

&lt;p&gt;The podcast I was listening to is called &lt;a href="https://www.jupiterbroadcasting.com/show/coderradio/"&gt;Coder Radio&lt;/a&gt;, and I was specifically listening to episode &lt;a href="https://www.jupiterbroadcasting.com/126681/not-so-qt-cr-322/"&gt;#322 Not so QT&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;That episode is about using QT to develop a cross-platform GUI for a .NET application. In the end they decided to give up on the idea, mainly because it was very complicated to setup, required it to be developed on Windows (QT does not support cross compilation) and in the end the license was prohibitively expensive.&lt;/p&gt;

&lt;p&gt;When I heard this I though, humm, I think I know of a way to solve this problem. I think I can come up with a solution that would work well in this context, specifically for business applications where memory usage is not too constrained.&lt;/p&gt;

&lt;p&gt;A bit presumptuous and naive of me to think like this? Perhaps, but let me take you through that journey. I promise it won't disappoint.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--7WvX-vT9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/04/WindowsToLinux.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--7WvX-vT9--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/04/WindowsToLinux.png" alt="windows logo and tux with an arrow going from windows to tux"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The idea
&lt;/h2&gt;

&lt;p&gt;.NET does not have a solution for developing cross-platform GUIs. There are a few options, but they are not easy to set up and develop for.&lt;/p&gt;

&lt;p&gt;On the other hand there's a technology that has been super popular for developing cross-platform apps which is &lt;a href="https://www.electronjs.org/"&gt;Electron&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Electron has been heavily criticized because of its heavy memory use (mostly because of Slack), but there are great applications written in it that feel super smooth (VSCode) and are probably responsible for enabling people to be able to choose a different operating system than what they normally use.&lt;/p&gt;

&lt;p&gt;The problem is, you can't develop using .NET in Electron, it's all JavaScript and Node.js (I know, I know, there's Electron.NET, but trust me, what I'm talking about here is completely different).&lt;/p&gt;

&lt;p&gt;So the idea was, if Electron is basically Node.js and we can start a .NET process from Node why can't we use Electron to build the UI and have all the behavior written in .NET. We just need a (non-convoluted) way of sending commands/requests between Node and .NET and it all should work, right?&lt;/p&gt;

&lt;p&gt;Turns out that yes, it works and you probably already use this approach all the time.&lt;/p&gt;

&lt;p&gt;Any time you pipe the output of a command to another in the shell, you are basically using the same idea I'm going to describe next.&lt;/p&gt;

&lt;p&gt;And if you are skeptical about how robust this is, let me tell you that people do database restores/backups using this technique (e.g.: &lt;code&gt;cat backup.archive | mongorestore --archive&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Ok, no more beating around the bush: the idea is to use the &lt;code&gt;stdin&lt;/code&gt; and &lt;code&gt;stdout&lt;/code&gt; streams to create a two way communication channel between two processes, in this case between Node.js and .NET.&lt;/p&gt;

&lt;p&gt;In case these streams are news to you, the &lt;code&gt;stdin&lt;/code&gt; (standard input stream) is normally used to read data from the terminal (like when a program asks you for input) and the &lt;code&gt;stdout&lt;/code&gt; (standard output stream) is where you write to in your program to get data to show up in the terminal. These can be redirected (piped) so that the output of one becomes the input of the other.&lt;/p&gt;

&lt;p&gt;Node.js has a module named &lt;code&gt;child_process&lt;/code&gt; that contains a function, &lt;code&gt;spawn&lt;/code&gt;, that we can use to &lt;em&gt;spawn&lt;/em&gt; new processes and grab hold of their &lt;code&gt;stdin&lt;/code&gt;, &lt;code&gt;stdout&lt;/code&gt; and &lt;code&gt;stderr&lt;/code&gt; streams.&lt;/p&gt;

&lt;p&gt;When using &lt;code&gt;spawn&lt;/code&gt; to create a .NET process we have the ability to send data to it through its &lt;code&gt;stdin&lt;/code&gt; and receive data from it from its &lt;code&gt;stdout&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Here's how that looks like:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const spawnedProcess = spawn('pathToExecutable', [arg1, arg2]);
spawnedProcess.stdin.write('hello .NET from Node.js');
spawnedProcess.stdout.on('data', data =&amp;gt; {
    //data from .NET;
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;Very simple idea, very few moving parts and very simple to set up.&lt;/p&gt;

&lt;p&gt;Obviously, the code above in that form is not very usable. Here's an example of what I ended up creating:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const connection = new ConnectionBuilder()
        .connectTo('DotNetExecutable')
        .build();
connection.send('greeting', 'John', (err, theGreeting) =&amp;gt; {
    console.log(theGreeting);
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;The code above sends a request to .NET of type "greeting" with argument "John" and expects a response from .NET with a proper greeting to John.&lt;/p&gt;

&lt;p&gt;I'm omitting a lot of details here, namely what actually gets sent over the &lt;code&gt;stdin&lt;/code&gt;/&lt;code&gt;stdout&lt;/code&gt; streams but that's not terribly important here.&lt;/p&gt;

&lt;p&gt;What I left out and is important is how this works in .NET.&lt;/p&gt;

&lt;p&gt;In a .NET application it's possible to get access to its process' &lt;code&gt;stdin&lt;/code&gt; and &lt;code&gt;stdout&lt;/code&gt; streams. They are available through the &lt;code&gt;Console&lt;/code&gt;'s properties &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.console.in?view=netframework-4.8"&gt;&lt;code&gt;In&lt;/code&gt;&lt;/a&gt; and &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.console.out?view=netframework-4.8"&gt;&lt;code&gt;Out&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The only care that is required here is reading from the streams and keeping them open. Thankfully &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.io.streamreader?view=netframework-4.8"&gt;&lt;code&gt;StreamReader&lt;/code&gt;&lt;/a&gt; supports this through an overload of its &lt;a href="https://docs.microsoft.com/en-us/dotnet/api/system.io.streamreader.read?view=netframework-4.8#System_IO_StreamReader_Read_System_Char___System_Int32_System_Int32_"&gt;Read&lt;/a&gt; method.&lt;/p&gt;

&lt;p&gt;Here's how all that ended up looking in the first implementation of this idea in .NET:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var connection = new ConnectionBuilder()
                    .WithLogging()
                    .Build();

// expects a request named "greeting" with a string argument and returns a string
connection.On&amp;lt;string, string&amp;gt;("greeting", name =&amp;gt;
{
    return $"Hello {name}!";
});

// wait for incoming requests
connection.Listen();
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3&gt;
  
  
  First experiments
&lt;/h3&gt;

&lt;p&gt;I called the implementation of this idea &lt;a href="https://www.blinkingcaret.com/2020/03/25/electroncgi-1-0-cross-platform-guis-for-net-core/"&gt;ElectronCGI&lt;/a&gt; (which is probably not the best of names given that what this idea really enables is to execute .NET code from Node.js). &lt;/p&gt;

&lt;p&gt;It allowed me to create these demo applications where the UI was built using Electron + Angular and/or plain JavaScript with all non-ui code running in .NET.&lt;/p&gt;

&lt;p&gt;Calculator Demo:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--oScIat9a--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/04/electron-cgi-calculator.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--oScIat9a--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/04/electron-cgi-calculator.gif" alt="Animation of a simple calculator running"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;PostgreSQL database records browser:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Dp44oPq1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/04/enceladus-viewer.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Dp44oPq1--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/04/enceladus-viewer.gif" alt="An application to filter records from a database"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;On that last one on every keystroke a query is being performed and the results returned and rendered. The perceived performance is so good that it totally feels like a native application, and all the non-UI code is .NET in both examples.&lt;/p&gt;

&lt;p&gt;One thing that might not be obvious by looking at the examples is that you can maintain the state of your application in .NET. &lt;/p&gt;

&lt;p&gt;One approach that is common with Electron apps is to use Electron to display a web &lt;br&gt;
page, and the actions you perform end up being HTTP requests to the server that hosts that web page. That means you have to deal with all that is HTTP related (you need to pick an port, send http requests, deal with routing, cookies, etc etc).&lt;/p&gt;

&lt;p&gt;With this approach however, because there's no server and the .NET process "sticks" around you can keep all your state there, and setup is super simple, literally two lines in Node.js and .NET and you you can have the processes "talking" to each other.&lt;/p&gt;

&lt;p&gt;All in all, this gave me confidence that this idea was good and worth exploring further. &lt;/p&gt;
&lt;h3&gt;
  
  
  Pushing on, adding concurrency and two-way communication between the processes
&lt;/h3&gt;

&lt;p&gt;At the time of these demos it was possible to send messages from Node.js to .NET, but not the other way around. &lt;/p&gt;

&lt;p&gt;Also, everything was synchronous, meaning that if you sent two requests from Node.js and the first took one minute to finish, you'd have to wait that full minute before you got a response for the second request.&lt;/p&gt;

&lt;p&gt;Because an image is worth more than a thousand words here's how that would look visually if you sent 200 requests from Node.js to .NET and where every request took an average of 200ms to complete:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LmP_DPCN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2019/11/electron-cgi-no-concurrency.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LmP_DPCN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2019/11/electron-cgi-no-concurrency.gif" alt="Grid where the numbered cells change color whenever the corresponding request complete"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Enabling request running concurrently involved dealing with concurrency. Concurrency is hard.&lt;/p&gt;

&lt;p&gt;This took me a while to get right but in the end I used the &lt;a href="https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/dataflow-task-parallel-library"&gt;.NET Task Parallel Library's Data Flow&lt;/a&gt; library.&lt;/p&gt;

&lt;p&gt;It is a complicated subject and in the process of figuring it out I wrote these two blog posts, in case you are curious about DataFlow here they are: TPL Dataflow in .Net Core, in Depth – &lt;a href="https://www.blinkingcaret.com/2019/05/15/tpl-dataflow-in-net-core-in-depth-part-1/"&gt;Part 1&lt;/a&gt; and &lt;a href="https://www.blinkingcaret.com/2019/06/05/tpl-dataflow-in-net-core-in-depth-part-2/"&gt;Part 2&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This is how much better the example above is when requests can be served concurrently:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kgRGOpLF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2019/11/electron-cgi-concurrency.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kgRGOpLF--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2019/11/electron-cgi-concurrency.gif" alt="Grid where the numbered cells change color whenever the corresponding request complete resolving much much faster"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The other big feature that was missing was to be able to send request from .NET to Node.js, previously all it was only possible to send a request from Node.js with an argument and get a response from .NET with some result.&lt;/p&gt;

&lt;p&gt;For example:&lt;/p&gt;
&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;connection.send('event.get', 'enceladus', events =&amp;gt; {
    //events is a list of filtered events using the filter 'enceladus'
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This was enough for simple applications but for more complex ones having the ability to have .NET send requests was super important.&lt;/p&gt;

&lt;p&gt;To do this I had to change the format of the messages that were exchanged using the &lt;code&gt;stdin&lt;/code&gt; and &lt;code&gt;stdout&lt;/code&gt; streams. &lt;/p&gt;

&lt;p&gt;Previously .NET's &lt;code&gt;stdin&lt;/code&gt; stream would receive requests from Node, and responses to those requests were sent using its &lt;code&gt;stdout&lt;/code&gt; stream. &lt;/p&gt;

&lt;p&gt;To support duplex communication the messages included a type, which could be REQUEST of RESPONSE, and later on I added ERROR as well and also changed the API, in Node.js:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;connection.send('requestType', 'optionalArgument', (err, optionalResponse) =&amp;gt; {
    //err is the exception object if there's an exception in the .NET handler
});

//also added the ability to use promises:

try {
    const response = await connection.send('requestType', 'optionalArg');
}catch(err) {
    //handle err
}

//to handle request from .NET:

connection.on('requesType', optionalArgument =&amp;gt; {
    //optionally return a response
});
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;And in .NET:&lt;/p&gt;


&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;connection.On&amp;lt;T&amp;gt;("requestType", (T argument) =&amp;gt; {&lt;br&gt;
    //return optional response&lt;br&gt;
});

&lt;p&gt;//and to send:&lt;/p&gt;

&lt;p&gt;connection.Send&amp;lt;T&amp;gt;("requestType", optionalArgument, (T optionalResponse) =&amp;gt; {&lt;br&gt;
    //use response&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;// there's also an async version:&lt;/p&gt;

&lt;p&gt;var response = await connection.SendAsync("requestType", optionalArgument);&lt;br&gt;
&lt;/p&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;h3&gt;
&lt;br&gt;
  &lt;br&gt;
  &lt;br&gt;
  Proof: Porting a windows store application to Linux&lt;br&gt;
&lt;/h3&gt;

&lt;p&gt;When I first started with this idea I imagined a good proof that it would be viable would be to pick an application that was built using MVVM and be able to take the ViewModels, which are (should be) UI agnostic, and use them, unaltered, in an application using this approach.&lt;/p&gt;

&lt;p&gt;Thankfully I had a game I built for the Windows Store around 2014 for which I still had the source code for. That game was named Memory Ace and you can still find it in the Windows Store &lt;a href="https://www.microsoft.com/en-us/p/memory-ace/9wzdncrddbtd?activetab=pivot:overviewtab"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LFQu-DFl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/03/Memorization-show-card-association.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LFQu-DFl--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/03/Memorization-show-card-association.png" alt="Memory ace screenshot"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Turns out I was able to re-use all of the code to create the cross-platform version with no problems. Here it is running on Ubuntu:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--yxorSU85--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/03/memory-ace-ubuntu-small.gif" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--yxorSU85--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_66%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2020/03/memory-ace-ubuntu-small.gif" alt="Memory Ace running on Ubuntu"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I also was able to run it on Windows with no problems. I don't own a Mac so I could not try it there.&lt;/p&gt;

&lt;p&gt;If you want to have a look at the source code, you can find it &lt;a href="https://github.com/ruidfigueiredo/MemorizeADeck"&gt;here&lt;/a&gt;. Also, the source for ElectronCGI is &lt;a href="https://github.com/ruidfigueiredo/electron-cgi"&gt;here for Node.js&lt;/a&gt; and &lt;a href="https://github.com/ruidfigueiredo/electron-cgi-dotnet"&gt;here for .NET&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Also, here are some blog posts with extra information: &lt;a href="https://www.blinkingcaret.com/2020/03/25/electroncgi-1-0-cross-platform-guis-for-net-core/"&gt;ElectronCGI 1.0 – Cross-platform GUIs for .Net Core&lt;/a&gt;, &lt;a href="https://www.blinkingcaret.com/2019/11/27/electroncgi-a-solution-to-cross-platform-guis-for-net-core/"&gt;ElectronCGI 1.0 – Cross-platform GUIs for .Net Core&lt;/a&gt; and &lt;a href="https://www.blinkingcaret.com/2019/02/27/electron-cgi/"&gt;ElectronCGI – Cross Platform .Net Core GUIs with Electron&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;You can also see &lt;a href="https://www.youtube.com/watch?v=-aJDzyGgNLY&amp;amp;t=61s"&gt;here&lt;/a&gt; how easy it is to setup a project with ElectronCGI (using an outdated version, but the process is identical).&lt;/p&gt;

&lt;p&gt;So that's it. If I managed to grab your attention until now, can I kindly ask for your help? &lt;/p&gt;

&lt;p&gt;I've been personally affected by the covid-19 pandemic. I was working as a contractor in a company that was badly affected (hospitality sector) and had to let everyone go. Me included.&lt;/p&gt;

&lt;p&gt;I appreciate you might not be in a position to offer me a job, but any help is appreciated, for example if your company has open roles you can suggest me (I'm well versed in .NET. Node.js, React, Angular and several other technologies). Maybe there's even a referral program.&lt;/p&gt;

&lt;p&gt;Or maybe you can add some endorsements on my &lt;a href="https://www.linkedin.com/in/ruidfigueiredo/"&gt;LinkedIn&lt;/a&gt; profile. &lt;/p&gt;

&lt;p&gt;Or if you know of any roles I could be a good fit for let me know, here's my &lt;a href="https://twitter.com/ruidfigueiredo"&gt;twitter&lt;/a&gt; (my DMs are open). &lt;/p&gt;

&lt;p&gt;Take care and stay safe.&lt;/p&gt;

</description>
      <category>node</category>
      <category>netcore</category>
      <category>javascript</category>
      <category>linux</category>
    </item>
    <item>
      <title>Software Development as an Emergent System</title>
      <dc:creator>Rui Figueiredo</dc:creator>
      <pubDate>Mon, 22 Oct 2018 21:57:15 +0000</pubDate>
      <link>https://dev.to/ruidfigueiredo/software-development-as-an-emergent-system-49a4</link>
      <guid>https://dev.to/ruidfigueiredo/software-development-as-an-emergent-system-49a4</guid>
      <description>&lt;p&gt;Emergent systems are sometimes described as systems where the whole is greater than the sum of the parts. &lt;/p&gt;

&lt;p&gt;I personally prefer to think of an emergent system as something that is complex to reason about as a whole but simple(r) to understand when you look at its individual components.&lt;/p&gt;

&lt;p&gt;Probably one of the most given examples of an emergent system in nature is that of a flock of birds flying in perfect coordination.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--AWkPwwMw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/08/flock_of_birds.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--AWkPwwMw--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/08/flock_of_birds.jpg" alt="image of a flock of birds flying together in a coordinated way"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you try to model the birds' movement as a whole it becomes difficult and convoluted. The movement they make seems almost unpredictable.&lt;/p&gt;

&lt;p&gt;But if instead you model this system by modeling one bird, then it becomes simple to understand. &lt;/p&gt;

&lt;p&gt;This has been done exactly for this problem (modeling the behavior of a flock of birds) and the solution is called &lt;a href="https://cs.stanford.edu/people/eroberts/courses/soco/projects/2008-09/modeling-natural-systems/boids.html"&gt;Boids&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;In Boids, the complex behavior of a flock of birds is achieved by having each bird follow three simple rules.&lt;/p&gt;

&lt;p&gt;The first one is &lt;em&gt;separation&lt;/em&gt;, which states that each bird will try to keep a reasonable distance from other birds. The second rule is &lt;em&gt;alignment&lt;/em&gt; which means that a bird will try to align itself with the birds in its vicinity. And finally, &lt;em&gt;cohesion&lt;/em&gt; which means that each bird will try to move to the average position of other nearby birds.&lt;/p&gt;

&lt;p&gt;It's impressive how lifelike a simulation looks using just these three simple rules. You can &lt;a href="https://www.youtube.com/watch?v=QbUPfMXXQIY"&gt;watch them in action in this video&lt;/a&gt; that does a very good job of explaining each rule in isolation.&lt;/p&gt;

&lt;p&gt;But what does this have to do with software development?&lt;/p&gt;

&lt;p&gt;Software is developed by individuals and any software system of reasonable size becomes hard to reason about as a whole.&lt;/p&gt;

&lt;p&gt;Unfortunately it isn't possible to come up with simple rules that allow us to predict how a particular piece of software will evolve. However looking at software development from this perspective surfaces some aspects that might help determine if a software product will be a quality product, or if it will derail into something that no developer wants to work on.&lt;/p&gt;

&lt;p&gt;One of the things that comes to mind are "initial conditions". In the Boids example this would be the birds' initial position in the simulation. Different starting positions might lead to one big flock or to multiple individual flocks.&lt;/p&gt;

&lt;p&gt;In software there are several things that can be thought of as initial conditions, for example the type of technology used or even the project's initial structure. &lt;/p&gt;

&lt;p&gt;I've worked on large projects where the default MVC structure (one folder for controllers, one folder for views and one folder for models) for a web application was blindly taken. Having a controller folder with hundreds of controllers quickly gets out of hand. At some point things become hard to name, to find, and a pain to work with.&lt;/p&gt;

&lt;p&gt;An aspect that is implicit from the Boids' simulation is that every bird follows its rules perfectly. If they didn't the flock would break apart.&lt;/p&gt;

&lt;p&gt;People can't be expected to follow rules perfectly, especially because there are no perfect rules in software development.&lt;/p&gt;

&lt;p&gt;However, if we have some way to measure how things are going, like we can look at a flock and see where it's breaking apart, we can nudge things back to harmony.&lt;/p&gt;

&lt;p&gt;But to do that we need to be able to measure the health of the system.&lt;/p&gt;

&lt;p&gt;If you develop in .Net and you use Visual Studio you have access to a few &lt;a href="https://docs.microsoft.com/en-ie/visualstudio/code-quality/code-metrics-values"&gt;Code Metrics&lt;/a&gt;, namely a Maintainability Index, Cyclomatic Complexity, Depth of Inheritance and Lines of Code.&lt;/p&gt;

&lt;p&gt;Those can be useful (although the Maintainabilty Index may be &lt;a href="https://docs.microsoft.com/en-ie/visualstudio/code-quality/code-metrics-values"&gt;a bit questionable&lt;/a&gt;). However, they are a bit limited and they can't be neither changed nor added to.&lt;/p&gt;

&lt;p&gt;Recently I've discovered a tool that seems to have been made to solve this problem. It's called &lt;a href="https://www.ndepend.com"&gt;NDepend&lt;/a&gt; and it not only has these metrics and hundreds more, it also allows you do change them to your needs and even and add your own.&lt;/p&gt;

&lt;h2&gt;
  
  
  NDepend
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.ndepend.com/"&gt;NDepend&lt;/a&gt; is a paid extension for Visual Studio (with a trial period). &lt;/p&gt;

&lt;p&gt;It analyzes your solution each time you build it and provides insights in the form of interactive graphs and a dashboard that shows passing/failing rules.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--w_Nn9WwN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/08/NDependDashboard.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--w_Nn9WwN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/08/NDependDashboard.png" alt="NDepend's Dashboard"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The rules in NDepend are similar to Linq queries (they are called CQLinq in NDepend where CQ stands for Code Query) and there are more than 200 available. &lt;/p&gt;

&lt;p&gt;They are easy to read as well, for example this rule creates a warning for methods that have more than 10 lines of code:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// &amp;lt;Name&amp;gt;Keep methods short and concise&amp;lt;/Name&amp;gt;
warn if count &amp;gt; 0 from method in Methods where method.NbLinesOfCode &amp;gt; 10 select method
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This is what you'll see when there are methods that are picked up by this rule:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--o0yew8Af--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/08/Rule-match-example.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--o0yew8Af--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/08/Rule-match-example.png" alt="Tree view of methods matching more than 10 lines of code"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can click any of the methods and NDepend will take you to where they are in the source code. &lt;/p&gt;

&lt;p&gt;You can find the predefined and also your custom rules in NDepend's Rule Explorer Panel:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--cKvEKs11--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/08/Queries-and-Rules-Explorer-Panel.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--cKvEKs11--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/08/Queries-and-Rules-Explorer-Panel.png" alt="Queries and rules explorer panel displaying the rule we've just created"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You've probably noticed that I've used &lt;code&gt;select method&lt;/code&gt; in the rule definition. You can add additional information by returning an anonymous object with a method property and the extra information that we want to add. That extra information will be displayed in the UI. &lt;/p&gt;

&lt;p&gt;For example, let's add the method's visibility and how many methods are called from the offending method:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// &amp;lt;Name&amp;gt;Keep methods short and concise&amp;lt;/Name&amp;gt;
warn if count &amp;gt; 0 from method in Methods where method.NbLinesOfCode &amp;gt; 10 select new {
    method,
    method.Visibility,
    method.MethodsCalled
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;You can access this information when you click the rule in the Rule Explorer. You can even hover over each of the "returned" fields and get extra information:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--i3kZK-UZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/08/MethodsCalled.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--i3kZK-UZ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/08/MethodsCalled.png" alt="Hover over MethodsCalled example"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Additionally to being able to customize how the rules are displayed you can define how they affect the project in terms of technical debt. Namely, through an arbitrary amount of time.&lt;/p&gt;

&lt;p&gt;Let's say that we think that it would take on average 5 minutes to fix each line over 10 lines of code (by breaking the method in smaller methods, for example) in a method and we want that to be quantified.&lt;/p&gt;

&lt;p&gt;We can include a &lt;em&gt;Debt&lt;/em&gt; value in the rule's &lt;code&gt;select&lt;/code&gt; statement that describes this:&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// &amp;lt;Name&amp;gt;Keep methods short and concise&amp;lt;/Name&amp;gt;
warnif count &amp;gt; 0 from method in Methods 
where method.NbLinesOfCode &amp;gt; 10 
select new { 
    method,
    method.Visibility,
    method.MethodsCalled,
    method.NbLinesOfCode,
    Debt = (5 * (method.NbLinesOfCode -10)).ToMinutes().ToDebt()
}
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;This will then add the the project's overall Debt that you can consult in NDepend's dashboard.&lt;/p&gt;

&lt;p&gt;This is just a sample of what you can do with rules. I've only mentioned methods, but you can query assemblies, types, fields, code created by you (you can fine tune what this means in NDepend), third party code, etc. You can also cherry pick which rules you want considered in case you don't agree with some of them.&lt;/p&gt;

&lt;p&gt;Also, you can integrate NDepend with a build server and have the build fail when you detect something you consider serious going on. This is achieved with a set of rules named &lt;em&gt;Quality Gates&lt;/em&gt; that you can also customize and add/remove to.&lt;/p&gt;

&lt;p&gt;Additionally to the rules you can produce graphs that provide visual insights over the code base.&lt;/p&gt;

&lt;p&gt;For example, you can create a "Code Metric View" graph that can show you two dimensions simultaneously. For instance the number of lines of code (LoC) in a class and its cyclomatic complexity. The LoC is represented by how big an area the class takes and the complexity by the color:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--4WwJO_Kg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/08/Code-Metrics-View.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--4WwJO_Kg--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/08/Code-Metrics-View.png" alt="Code Metrics View example where it is possible to see that the ManageController is the worst class in the project"&gt;&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;You can see from the example above that the &lt;code&gt;ManageController&lt;/code&gt; is the "worst" class in terms of cyclomatic complexity and it's the second largest in terms of lines of code.&lt;/p&gt;

&lt;p&gt;NDepend has other graph types that you can use to better understand your project's dependencies, inheritance hierarchies and test code coverage just to name a few. &lt;/p&gt;

&lt;p&gt;However, all of this only allows you to see one picture of how your project is doing in terms of quality &lt;em&gt;right now&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;My favorite feature of NDepend is that you can create a &lt;em&gt;baseline&lt;/em&gt; and then see how the project evolves in relation to that baseline (you can configure this from the Dashboard). &lt;/p&gt;

&lt;p&gt;For example, if you add or remove &lt;em&gt;Debt&lt;/em&gt; or have more or less rules passing/failing this is highlighted and you can truly have a feeling of seeing the direction the project is going. &lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;Software development is a complicated discipline, especially when you consider that it is performed by several people working together. &lt;/p&gt;

&lt;p&gt;Comparing it to emergent systems is useful because it provides a perspective where we can think of software as something that evolves. &lt;/p&gt;

&lt;p&gt;Being able to measure that evolution is then crucial if we want to be able to tell if the product we are building is holding up in terms of quality.&lt;/p&gt;

&lt;p&gt;I also describe a tool named NDepend that serves exactly this purpose (and as far as I know has no competitors). It provides extensive metrics and allows for the creation of custom rules, all of this while supporting integration with a continuous integration workflow.&lt;/p&gt;

</description>
      <category>programming</category>
      <category>solid</category>
      <category>productivity</category>
    </item>
    <item>
      <title>Everyone is watching what you do online. How user tracking with cookies works</title>
      <dc:creator>Rui Figueiredo</dc:creator>
      <pubDate>Mon, 16 Jul 2018 18:20:18 +0000</pubDate>
      <link>https://dev.to/ruidfigueiredo/everyone-is-watching-what-you-do-online-how-user-tracking-with-cookies-works-aon</link>
      <guid>https://dev.to/ruidfigueiredo/everyone-is-watching-what-you-do-online-how-user-tracking-with-cookies-works-aon</guid>
      <description>&lt;p&gt;Have you ever visited a website to check out something you want to buy only to be inundated with ads for that product in other websites?&lt;/p&gt;

&lt;p&gt;I've been asked about this enough times that I thought it would be a good exercise to try and explain how this works.&lt;/p&gt;

&lt;p&gt;This blog post is an explanation of how websites that seem totally unrelated to each other seem to know about what you are doing online.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F06%2Fcookie-trail-of-crumbes.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F06%2Fcookie-trail-of-crumbes.jpg" alt="cookie trail of crumbles"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  It all starts with the Cookie
&lt;/h2&gt;

&lt;p&gt;Before we describe what a cookie is (in the context of the web), let's start by describing why they are needed.&lt;/p&gt;

&lt;p&gt;The web is mostly a disconnected system. That's an odd thing to say when the web is almost synonymous with being connected. What disconnected means in this context is that when you use your browser to open visit website, the browser connects to the server that hosts that website, gets the web page and disconnects. The web server only knows about you for that very brief period.&lt;/p&gt;

&lt;p&gt;This is what allows one website to potentially serve millions of requests. It doesn't need to hold information about you in memory for very long.&lt;/p&gt;

&lt;p&gt;Well, if that's the case how come we have websites that &lt;strong&gt;do&lt;/strong&gt; "remember" us, where we can login and see data that is ours?&lt;/p&gt;

&lt;p&gt;That's where cookies come in. A cookie is information stored in &lt;strong&gt;your&lt;/strong&gt; computer about the website you visited.&lt;/p&gt;

&lt;p&gt;When you visit a website your browser sends a HTTP request to a web server that is listening at the address of that website. The web server sends back an HTTP response with the contents of the website (HTML) and some "headers". A header is just a key value pair (for example: &lt;code&gt;Server: TheServerName&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;There's a header named &lt;code&gt;Set-Cookie&lt;/code&gt; which when present in an HTTP response will make your browser create a cookie for the website you are visiting. It's actually a little bit more complex than this. The cookie is tied to the domain of the website, but for this discussion it's ok if you think that a cookie belongs to one website.&lt;/p&gt;

&lt;p&gt;Also, a cookie is just a text file saved on your computer.&lt;/p&gt;

&lt;p&gt;Here's an example of a &lt;code&gt;Set-Cookie&lt;/code&gt; header from a response to &lt;code&gt;myawesomewebsite.com&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Set-Cookie: the_cookie_name=the_cookie_value; path=/; expires=Tue, 06 Jun 2028 21:50:30 GMT; domain=.myawesomewebsite.com
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;After this response, every time you visit &lt;code&gt;myawesomewebsite.com&lt;/code&gt; until 06 June 2028 your browser will send a &lt;code&gt;Cookie&lt;/code&gt; header in the request like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Cookie: the_cookie_name=the_cookie_value
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The easiest example to imagine of a website using this is a website that allows its users to pick a background color. In the response to the request to change the background color the web server will add a header like this: &lt;code&gt;Set-Cookie: background_color=blue ...&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now every time you go to that website your browser will "tell" the website that you want the background to be blue, and the way it will do this is by including the &lt;code&gt;Cookie&lt;/code&gt; header in the request: &lt;code&gt;Cookie: background_color=blue&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;The mechanism that allows you to log in to a website is very similar to this. When you visit a login page and enter the correct username and password the web server will send back a response with a &lt;code&gt;Set-Cookie&lt;/code&gt; header whose contents will allow the web server to find your data. The value of this cookie is usually encrypted so that only the server can create it, and also only the server will be able to read it. This way a user can't just change the value and potentially sign in as another person.&lt;/p&gt;

&lt;h2&gt;
  
  
  Tracking users with cookies
&lt;/h2&gt;

&lt;p&gt;I'm sure you've seen messages similar to this: "We use cookies to improve your experience on our site and to show you &lt;em&gt;relevant advertising&lt;/em&gt;".&lt;/p&gt;

&lt;p&gt;The way that cookies can be used to "show you relevant advertising" hinges on how they are treated by the browser. Every time your browser makes a request to a website for which it has a cookie, it will send that cookie.&lt;/p&gt;

&lt;p&gt;Also, when the request originates form a website that is different from the website the cookie is for, the browser will add a header named &lt;code&gt;Referer&lt;/code&gt; (yes, it's misspelled, but that's the way it is in the &lt;a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referer" rel="noopener noreferrer"&gt;spec&lt;/a&gt; so we have to live with it). That header will contain the URL from the website from where the request originated.&lt;/p&gt;

&lt;p&gt;This is simpler to understand with an example. Say you go to Wikipedia to read about the World Cup. While doing that you find something interesting in the references section that you want to explore. For example a page about the 2018 qualification that is hosted in another website that you have visited before (e.g. sofascore.com). &lt;/p&gt;

&lt;p&gt;When you click on the link to sofascore.com your browser will add the &lt;code&gt;Cookie&lt;/code&gt; header to the request for &lt;code&gt;sofascore.com&lt;/code&gt; and it will also add a &lt;code&gt;Referer&lt;/code&gt; header with the url from Wikipedia, for example: &lt;code&gt;Referer: https://en.wikipedia.org/wiki/2018_FIFA_World_Cup&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;How can this be exploited?&lt;/p&gt;

&lt;p&gt;For simplicity imagine that the original website you've visited is named &lt;em&gt;tracker&lt;/em&gt;. Now imagine &lt;em&gt;tracker&lt;/em&gt; set a cookie for you with a value that is unique (will act as an identifier) and has a very long expiration date. Also, &lt;em&gt;tracker&lt;/em&gt; has an agreement  with loads of other websites, and those websites host a 1x1 pixel transparent image &lt;strong&gt;from&lt;/strong&gt; &lt;em&gt;tracker&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Each time you visit one of those websites your browser will make a request to &lt;em&gt;tracker&lt;/em&gt; for the transparent image and send the cookie with your &lt;em&gt;identifier&lt;/em&gt; and with the &lt;em&gt;referer&lt;/em&gt; header. This way, not only does the &lt;em&gt;tracker&lt;/em&gt; know who you are, it also knows which websites you are visiting.&lt;/p&gt;

&lt;p&gt;The &lt;em&gt;tracker&lt;/em&gt; can then sell your info to other websites that then can choose what they want to do with it. Mainly show you ads related to things they think you are interested in. It's as simple as that.&lt;/p&gt;

&lt;p&gt;Also, this technique is known as &lt;a href="https://en.wikipedia.org/wiki/Web_beacon" rel="noopener noreferrer"&gt;web beacon&lt;/a&gt; and it's one of the most simple techniques. There are &lt;a href="https://en.wikipedia.org/wiki/Evercookie" rel="noopener noreferrer"&gt;much more elaborate versions&lt;/a&gt; that will use a combination of features to "tag" you even if you delete your browser cookies.&lt;/p&gt;

&lt;p&gt;In case you are wondering why a cookie is called a cookie maybe it's because it's like a fortune cookie? It has a message inside. I actually don't know, but if you do please leave a comment.&lt;/p&gt;

</description>
      <category>security</category>
      <category>privacy</category>
      <category>webdev</category>
    </item>
    <item>
      <title>ORM-less Data Access in .Net Core</title>
      <dc:creator>Rui Figueiredo</dc:creator>
      <pubDate>Fri, 01 Jun 2018 15:58:10 +0000</pubDate>
      <link>https://dev.to/ruidfigueiredo/orm-less-data-access-in-net-core-23ac</link>
      <guid>https://dev.to/ruidfigueiredo/orm-less-data-access-in-net-core-23ac</guid>
      <description>&lt;p&gt;The use of Object Relational Mapper libraries (ORMs) is so prevalent today that it's uncommon to see anyone question their use.&lt;/p&gt;

&lt;p&gt;There are good reasons for that. In the old days you'd see SQL code sprinkled everywhere. It was common to find examples where user input was concatenated directly with SQL statements opening the doors to SQL injection attacks (little &lt;a href="https://xkcd.com/327/"&gt;Bobby Tables&lt;/a&gt; comes to mind).&lt;/p&gt;

&lt;p&gt;Even though a lot of good came out of using ORMs, there's some less good things that came with it too. The first is performance, which is worse (sometimes much worse).&lt;br&gt;&lt;br&gt;
But apart from performance there are a set of other issues that although they are not disadvantages, they have a negative impact on the experience of using an ORM. They are all related to the fact that ORMs hide a lot of details about how the data is retrieved and saved. Frequently, people by not being aware of these details shoot themselves in the foot. &lt;/p&gt;

&lt;p&gt;Just a few examples are the use of &lt;a href="https://www.blinkingcaret.com/2017/06/07/orms-lazy-loading-and-web-applications/"&gt;lazy loading even when that is arguably not a good idea&lt;/a&gt; (e.g. web applications) or N+1 problems stemming from the mechanism that triggers data being fetched (thinking specifically of Entity Framework here) not being obvious sometimes.&lt;/p&gt;

&lt;p&gt;I'm not advocating that ORMs shouldn't be used, not at all. However, my perception is that nowadays most people working in the .Net ecosystem wouldn't be able to retrieve and create records in a database without using Entity Framework.&lt;/p&gt;

&lt;p&gt;And that's unfortunate because it's not hard at all to go raw, and it might be quicker than to have to setup Entity Framework. I've been following that approach in small projects and I'm convinced that I can put something up faster without Entity Framework than with it (&lt;a href="https://www.blinkingcaret.com/2018/03/28/setting-up-ef-core/"&gt;setting up EF can be a pain&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;What I want to do in this blog post is show you how you can use the "raw" data access mechanisms (ADO.NET) available in .Net Core and also an alternative to Entity Framework named Dapper (which is used by Stack Overflow). Dapper is sometimes described as an ORM, but as we'll see it's more of an "object mapper".&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--vhysf4wt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/04/ormless_data_access.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--vhysf4wt--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://www.blinkingcaret.com/wp-content/uploads/2018/04/ormless_data_access.jpg" alt="orm or not orm image showing wheel spinning suggesting speed, in this context it suggests that not using ORMs is much better in terms of performance"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  CRUD with ADO.NET in .NET Core
&lt;/h2&gt;

&lt;p&gt;To do data access without Entity Framework Core you need to master just three concepts. Those concepts are Connections, Commands and Data Readers.&lt;/p&gt;

&lt;p&gt;A &lt;a href="https://msdn.microsoft.com/en-us/library/system.data.idbconnection.aspx"&gt;Connection&lt;/a&gt; object represents a connection to a database. You'll have to use the specific connection object for the database you want to interact with. For example for &lt;a href="https://www.postgresql.org/"&gt;PostgreSQL&lt;/a&gt; we'd use &lt;code&gt;NpgsqlConnection&lt;/code&gt;, for MySql &lt;code&gt;MysqlConnection&lt;/code&gt;, for SQL Server &lt;code&gt;SqlConnection&lt;/code&gt;. You get the idea. All these connection types implement the interface &lt;a href="https://msdn.microsoft.com/en-us/library/system.data.idbconnection.aspx"&gt;IDbConnection&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;You need to install the right Nuget package for the database you want to use, for example for Postgres the package name is simply: &lt;code&gt;Npgsql&lt;/code&gt; (An easy way to remember it, is N - for .Net and pgsql for PostGreSQL).&lt;/p&gt;

&lt;p&gt;To create a connection object we need a connection string to the database we want to interact with. For example for a database named "example" with user "johnDoe" in Postgres we could create a connection this way:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var connection = new NpgsqlConnection("User ID=johnDoe;Password=thePassword;Host=localhost;Database=example;Port=5432");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;A great resource to find information about how to create these connection strings is &lt;a href="https://www.connectionstrings.com/"&gt;https://www.connectionstrings.com/&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;After creating the connection object, to actually connect to the database we need to call &lt;code&gt;Open&lt;/code&gt; on it:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;connection.Open();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The connection objects are all &lt;code&gt;IDisposable&lt;/code&gt;, so you should dispose of them. Because of this, usually the connection is created inside a using block:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using (var connection = new NpgsqlConnection("User ID=johnDoe;Password=thePassword;Host=localhost;Database=example;Port=5432"))
{
    connection.Open();
    //use the connection here
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That's all you need to start.&lt;/p&gt;

&lt;h2&gt;
  
  
  Creating records
&lt;/h2&gt;

&lt;p&gt;To create records we need to use a &lt;a href="https://msdn.microsoft.com/en-us/library/system.data.idbcommand.aspx"&gt;Command&lt;/a&gt;. A command is a container for all that is required to perform an operation in the database.&lt;/p&gt;

&lt;p&gt;The easiest way to create a command is to ask the connection object for one:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using(var command = connection.CreateCommand()) 
{
    //use command here
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You then specify the SQL you want to execute through the property &lt;code&gt;CommandText&lt;/code&gt; and the values for the parameters in the SQL in the property &lt;code&gt;Parameters&lt;/code&gt;. For example, if you want to add a record to a table named &lt;code&gt;people&lt;/code&gt; with columns &lt;code&gt;first_name&lt;/code&gt;, &lt;code&gt;last_name&lt;/code&gt;, &lt;code&gt;age&lt;/code&gt; it would look like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;command.CommandText = "insert into people (first_name, last_name, age) values (@firstName, @lastName, @age)";
command.Parameters.AddWithValue("@firstName", "John");
command.Parameters.AddWithValue("@lastName", "Doe");
command.Parameters.AddWithValue("@age", 38);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You should use parameters because that prevents SQL injection attacks. If you don't and you create your SQL by using string-concatenation using data that was entered by the user you enable situations where a user can type something that &lt;a href="https://www.troyhunt.com/everything-you-wanted-to-know-about-sql/"&gt;will be interpreted as SQL&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The way a command is "executed" depends on the result you expect from it. For adding a record, and in case you don't care about any auto-generated column values (for example the new record's id) you can do this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int numberOfUpdatedRows = command.ExecuteNonQuery();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This method returns the number of rows that were updated/created. Although it's not particularly useful on an insert statement, on an update that value might be useful.&lt;/p&gt;

&lt;p&gt;Alternatively, if you want to insert and get the new record's id you can change the insert statement's SQL so that the new id is returned. The way you do this depends on which database you are using, for example in postgres the SQL would look like this &lt;code&gt;insert into people (first_name, last_name, age) values (@firstName, @lastName, @age) returning id&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;In sql server it would look like this &lt;code&gt;insert into people (first_name, last_name, age) values (@firstName, @lastName, @age); select scope_identity()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To get the run the insert and get the new id you can use the &lt;a href="https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar(v=vs.110).aspx"&gt;&lt;code&gt;ExecuteScalar&lt;/code&gt;&lt;/a&gt; method in the Command. &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;ExecuteScalar&lt;/code&gt; method executes the SQL and returns the value (as type object) of the first column in the first row, for example in postgres:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;command.CommandText = "insert into people (first_name, last_name, age) values (@firstName, @lastName, @age) returning id";
command.Parameters.AddWithValue("@firstName", "Jane");
command.Parameters.AddWithValue("@lastName", "Doe");
command.Parameters.AddWithValue("@age", 37);

var newId = (int)command.ExecuteScalar();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You might be thinking right now that these SQL statements involve a lot of typing. And on top of that, all of that is with no intellisense. Thankfully there are techniques around that. &lt;a href="https://www.youtube.com/watch?v=R2XGaOz42i8"&gt;You can watch me creating an insert statement from scratch without actually having to manually type any column names&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Reads
&lt;/h2&gt;

&lt;p&gt;To read data you simply need to write your SQL query and call the &lt;code&gt;ExecuteReader&lt;/code&gt; method in the command object. That will return an instance of a &lt;code&gt;DataReader&lt;/code&gt; which you can then use to retrieve the actual results of your query.&lt;/p&gt;

&lt;p&gt;For example, if we want to retrieve all records in the &lt;code&gt;people&lt;/code&gt; table:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;command.CommandText = "select * from people";
DataReader reader = command.ExecuteReader();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now, the way you get to the actual values is a little bit clunky. Definitely not as comfortable to do as with Entity Framework, but as I showed in the &lt;a href="https://www.youtube.com/watch?v=R2XGaOz42i8"&gt;video on how to use Sublime to build the queries&lt;/a&gt;, you can also use the same techniques to create this code faster.&lt;/p&gt;

&lt;p&gt;Here's how you could iterate over all results assuming that first_name and last_name are strings and age is an int.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;command.CommandText = "select * from people";
using(DataReader reader = command.ExecuteReader()) 
{
    while(reader.Read())
    {
        string firstName = reader.GetString(reader.GetOrdinal("first_name"));
        string lastName = reader.GetString(reader.GetOrdinal("last_name"));
        int age = reader.GetInt32(reader.GetOrdinal("age"));

        //do something with firstName, lastName and age

    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;GetString&lt;/code&gt;, &lt;code&gt;GetIn32&lt;/code&gt;, &lt;code&gt;GetBoolean&lt;/code&gt;, etc, methods expect a number that represents the column index. You can get that column index by calling &lt;code&gt;reader.GetOrdinal("columnName")&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Updates and Deletes
&lt;/h2&gt;

&lt;p&gt;Updating and deleting records involves creating a command with the right SQL, and calling the &lt;code&gt;ExecuteNonQuery&lt;/code&gt; in that command.&lt;/p&gt;

&lt;p&gt;For example if we wanted to update all records on the people table that have the surname "Doe" to "Smith" we could do this&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;command.CommandText = "update people set last_name='Smith' where last_name='Doe'";
int numberOfAffectedRows = command.ExecuteNonQuery();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Deletions are very similar, for example, let's delete all records which have no last_name&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;command.CommandText = "delete from people where last_name is null";
int numberOfAffectedRows = command.ExecuteNonQuery();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Transactions
&lt;/h2&gt;

&lt;p&gt;One thing that you get for free when using an ORM like Entity Framework is that when you persist your changes (i.e. call&lt;code&gt;.SaveChanges()&lt;/code&gt;) that happens inside a transaction so that all the changes are persisted or none is.&lt;/p&gt;

&lt;p&gt;Thankfully creating a transaction using ADO.NET is very simple. Here's an example where we add a new person, delete another and update another yet all inside a db transaction:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using (var transaction = connection.BeginTransaction())
{
    var insertCommand = connection.CreateCommand();
    insertCommand.CommandText = "insert into people (first_name) values (@first_name)";
    insertCommand.Parameters.AddWithValue("@first_name", "Jane Smith");
    insertCommand.ExecuteNonQuery();

    var deleteCommand = connection.CreateCommand();
    deleteCommand.CommandText = "delete from people where last_name is null";
    deleteCommand.ExecuteNonQuery();

    var updateCommand = connection.CreateCommand();
    updateCommand.CommandText = "update people set first_name='X' where first_name='Y'";
    updateCommand.ExecuteNonQuery();

    transaction.Commit();
}    
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The easiest way to create a transaction is to request one from the connection object. A transaction is created using an &lt;em&gt;IsolationLevel&lt;/em&gt;. Although we didn't specify one here (the particular database's default will be used) you should check the list of available &lt;a href="https://msdn.microsoft.com/en-us/library/system.data.isolationlevel.aspx"&gt;isolation levels&lt;/a&gt; and choose the one that is appropriate to your needs.&lt;/p&gt;

&lt;p&gt;After having the transaction created we can do all operations as before and in the end we call &lt;code&gt;.Commit()&lt;/code&gt; on the transaction. If anything goes wrong before &lt;code&gt;.Commit()&lt;/code&gt; is called all the changes are rolled back.&lt;/p&gt;

&lt;h2&gt;
  
  
  Getting metadata from the database
&lt;/h2&gt;

&lt;p&gt;This is an aside but it's something that is useful to know. Using ADO.NET it is possible to extract metadata about your database. For example all the column names and their types form a particular table. &lt;/p&gt;

&lt;p&gt;The following snippet shows how you can get all the column names and data types form all the columns in a particular database table:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;command.CommandText = "select * from people";
using(var reader = command.ExecuteReader()) 
{
    var columnSchema = reader.GetColumnSchema();
    foreach(var column in columnSchema)
    {
        Console.WriteLine($"{column.ColumnName} {column.DataTypeName}");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Using Dapper
&lt;/h2&gt;

&lt;p&gt;Alternatively to using just ADO.NET using &lt;a href="https://github.com/StackExchange/Dapper"&gt;Dapper&lt;/a&gt; is just as easy and with small differences in terms of performance. &lt;/p&gt;

&lt;p&gt;In case you are unfamiliar with Dapper, it's a project from &lt;a href="https://stackexchange.com/"&gt;StackExchange&lt;/a&gt; and it powers the StackExchange familiy of websites (&lt;a href="https://stackoverflow.com/"&gt;StackOverflow&lt;/a&gt;, &lt;a href="https://superuser.com/"&gt;SuperUser&lt;/a&gt;, &lt;a href="https://askubuntu.com/"&gt;AskUbuntu&lt;/a&gt;, etc).&lt;/p&gt;

&lt;p&gt;To use Dapper you need to install a Nuget package conveniently named &lt;code&gt;Dapper&lt;/code&gt; along with the specific Nuget package for the database you are targeting. For example for Postgres:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ dotnet add package Npgsql
$ dotnet add package Dapper
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Dapper adds a few extension methods to your connection object, namely &lt;code&gt;Query&amp;lt;T&amp;gt;&lt;/code&gt; and &lt;code&gt;Execute&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;&lt;code&gt;Query&amp;lt;T&amp;gt;&lt;/code&gt; allows you to run a query and map the results to the type you specify in the generic parameter. For example, this is how you can get all records in the people table:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using Dapper; //you need this to get the extension methods on the connection object
//...

using (var connection = new NpgsqlConnection("theConnectionString"))
{
    IEnumerable&amp;lt;Person&amp;gt; people = connection.Query&amp;lt;Person&amp;gt;("select * from people");                        
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The &lt;code&gt;Query&amp;lt;T&amp;gt;&lt;/code&gt; method always returns an &lt;code&gt;IEnumerable&amp;lt;T&amp;gt;&lt;/code&gt; even if you only expect one record. For example you could do this to insert a new person and get the new Id:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;int newId = connection.Query&amp;lt;int&amp;gt;("insert into people (first_name, last_name, age) values (@FirstName, @LastName, @Age) returning id", new {
    FirstName = "John",
    LastName = "Doe",
    Age = "40"
}).FirstOrDefault();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In the example above we are providing 2 parameters to the &lt;code&gt;Query&lt;/code&gt; method, the first is the SQL statement and the second one is an anonymous object with property names that match the parameters in the SQL statement. You can also use an instance of a class (e.g. &lt;code&gt;new Person { ... }&lt;/code&gt;) instead.&lt;/p&gt;

&lt;p&gt;If you don't care about any results, for example you just want to delete a record, you can use the &lt;code&gt;Execute&lt;/code&gt; method instead which will return the number of records affected in the database. For example if you want to delete all the records for which last_name is null:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var numberOfDeletedRecords = connection.Execute("delete from person where last_name is null");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This was just a gentle introduction to Dapper, the &lt;a href="https://github.com/StackExchange/Dapper"&gt;github page for the project&lt;/a&gt; is a good resource if you are interested in learning more.&lt;/p&gt;

&lt;p&gt;I hope this blog post has given you enough information about how to go ORMless in .Net Core. Let me know your thoughts in the comments.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>database</category>
      <category>orm</category>
    </item>
    <item>
      <title>ASP.NET Core Development in Linux</title>
      <dc:creator>Rui Figueiredo</dc:creator>
      <pubDate>Wed, 28 Mar 2018 13:45:04 +0000</pubDate>
      <link>https://dev.to/ruidfigueiredo/aspnet-core-development-in-linux-fge</link>
      <guid>https://dev.to/ruidfigueiredo/aspnet-core-development-in-linux-fge</guid>
      <description>&lt;p&gt;When .Net Core came out there was a lot of excitement about the idea of developing .Net code outside of Windows.&lt;/p&gt;

&lt;p&gt;The IDE of choice for .Net, Visual Studio, is and probably will always be, a Windows-only program.&lt;/p&gt;

&lt;p&gt;There are alternatives though, and today it is possible to fully develop an ASP.NET Core application outside of Windows.&lt;/p&gt;

&lt;p&gt;In this blog post we will be looking into that, specifically in Linux.&lt;/p&gt;

&lt;p&gt;Please note that all of the tooling described here is cross-platform all of this will work on any platform that supports .Net Core. &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F03%2FNET-CoreLinux.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F03%2FNET-CoreLinux.png" alt=".NET Core Linux"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;
  
  
  The IDE
&lt;/h2&gt;

&lt;p&gt;The full version of Visual Studio is only available in Windows. However, there's an alternative that has a somewhat confusing name: &lt;a href="https://code.visualstudio.com/" rel="noopener noreferrer"&gt;Visual Studio Code&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;You might think that VS Code is an inferior version of the full Visual Studio product, but that is not the case. &lt;/p&gt;

&lt;p&gt;VS Code is a different project altogether. It's built using a different set of technologies and this brings some features that full VS doesn't have, for example being easily extensible and customizable, and also less demanding in terms of resources.&lt;/p&gt;

&lt;p&gt;VS Code offers the ability to extend its functionality by the installation of extensions. For C# you should install the &lt;a href="https://code.visualstudio.com/docs/languages/csharp" rel="noopener noreferrer"&gt;C# extension&lt;/a&gt;. You don't need to go through the trouble of looking for it though. When you open a project that has C#, Visual Studio Code will prompt you to install the C# extension if you don't have it already.&lt;/p&gt;

&lt;p&gt;In the rest of the blog post we will create a hypothetical ASP.NET Core web application in order to illustrate most of the required tasks when developing in .Net. Namely how to create projects and solutions, reference projects, install nuget packages, use dotnet tools (like entity framework) and run tests.&lt;/p&gt;

&lt;h2&gt;
  
  
  A Typical Project
&lt;/h2&gt;

&lt;p&gt;The imaginary project we'll be creating is a reminder application. The idea here is to describe a project with sufficient complexity that would require multiple projects that reference each other, a solution file and tests.&lt;/p&gt;

&lt;p&gt;The solution will contain an ASP.NET Core project that could, for example, be used to see past and future reminders. A Console application so that we can create reminders from the command line (and to illustrate how we can have a solution with more than one running project) and a class library that will contain all the common logic. We'll also add a test project to illustrate how unit tests can be run from the command line and inside VS Code.&lt;/p&gt;

&lt;h3&gt;
  
  
  Creating the projects and solution file
&lt;/h3&gt;

&lt;p&gt;By this time you should have installed &lt;a href="https://www.microsoft.com/net/download/linux" rel="noopener noreferrer"&gt;.Net Core&lt;/a&gt; and &lt;a href="https://code.visualstudio.com/" rel="noopener noreferrer"&gt;Visual Studio Code&lt;/a&gt;. You should be able to open a terminal window and type &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ dotnet 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;and get an output something similar to this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Usage: dotnet [options]
Usage: dotnet [path-to-application]

Options:
-h|--help            Display help.
--version         Display version.

path-to-application:
The path to an application .dll file to execute.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;One of the options of the dotnet command is "new". To check that and other options' help page just do &lt;code&gt;dotnet [option] --help&lt;/code&gt;, in this case &lt;code&gt;dotnet new --help&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;That will display a list of possible project templates to choose from. For example to create an ASP.NET Core MVC project:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ dotnet new mvc
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If you run that as it is, a new MVC project will be created in the current folder, using the name of the current folder as the default namespace and project name. &lt;/p&gt;

&lt;p&gt;You might not want that. In case you don't, you can use the &lt;code&gt;--name&lt;/code&gt; and &lt;code&gt;--output&lt;/code&gt; options. Using &lt;code&gt;--name&lt;/code&gt; (or &lt;code&gt;-n&lt;/code&gt;) you can specify the default namespace and with &lt;code&gt;--output&lt;/code&gt; (or &lt;code&gt;-o&lt;/code&gt;) you can specify the folder name to create and where to place the project files. If you use &lt;code&gt;--name&lt;/code&gt; and don't specify &lt;code&gt;--output&lt;/code&gt;, the output folder will implicitly take the same value as &lt;code&gt;--name&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It is probably a good idea to define the project folder structure before we continue. Here it is:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   Reminders
   +---+ Reminders.Web
   +---+ Reminders.Cli
   +---+ Reminders.Common
   +---+ Reminders.Tests
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;First thing we need to do is to create a project folder named Reminders and then inside it do:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ dotnet new mvc --name Reminders.Web
$ dotnet new console --name Reminders.Cli
$ dotnet new classlib --name Reminders.Common
$ dotnet new xunit --name Reminders.Tests
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This will create 4 projects, one MVC, one console, a class library and a xUnit test project.&lt;/p&gt;

&lt;p&gt;It's a good idea to create a solution file as well. Especially if eventually you want to open these projects in full Visual Studio, which will prompt you to create one until you eventually do it.&lt;/p&gt;

&lt;p&gt;There are advantages in having a solution file other than avoiding full Visual Studio nagging you about creating the .sln file. If you have one you can just go to the Reminders folder and do a &lt;code&gt;dotnet build&lt;/code&gt; or a &lt;code&gt;dotnet restore&lt;/code&gt; and that build/restore all projects referenced in the .sln file.&lt;/p&gt;

&lt;p&gt;Also, if you have a &lt;code&gt;.sln&lt;/code&gt; file you can open all projects in VS Code by initiating VS Code in the folder where the &lt;code&gt;.sln&lt;/code&gt; file is located.&lt;/p&gt;

&lt;p&gt;Let's create our .sln file, name it Reminders.sln and add the four projects to it (inside the Reminders folder):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ dotnet new sln --name Reminders
$ dotnet sln add Reminders.Web/Reminders.Web.csproj
$ dotnet sln add Reminders.Cli/Reminders.Cli.csproj
$ dotnet sln add Reminders.Common/Reminders.Common.csproj
$ dotnet sln add Reminders.Tests/Reminders.Tests.csproj
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Adding project references
&lt;/h2&gt;

&lt;p&gt;In full Visual Studio when you want to add a reference to a project you can just right click on references and select Add Reference, pick the project you want to add and you're done.&lt;/p&gt;

&lt;p&gt;VS Code does not have that functionality. To do this we need to resort to the command line, but it's just as easy. For example, let's reference Reminders.Common in Reminders.Web, Reminders.Cli and Reminders.Tests. &lt;/p&gt;

&lt;p&gt;Navigate to the folder where the .sln file is (Reminders) and type:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ dotnet add Reminders.Web/Reminders.Web.csproj reference Reminders.Common/Reminders.Common.csproj
$ dotnet add Reminders.Cli/Reminders.Cli.csproj reference Reminders.Common/Reminders.Common.csproj
$ dotnet add Reminders.Tests/Reminders.Tests.csproj reference Reminders.Common/Reminders.Common.csproj
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If you want to have a look at which other projects are referenced by a particular project you can either open the .csproj file and have a look at the &lt;code&gt;ProjectReference&lt;/code&gt; entries or if you want to do it from the command line: &lt;code&gt;dotnet list PathToCsProj reference&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;You can also navigate to the folder where a particular project is and simply do &lt;code&gt;dotnet add reference pathToOtherProject.csprj&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Picking the startup project
&lt;/h2&gt;

&lt;p&gt;Open the solution in VS Code. The easiest way to do that is to navigate to the Reminders folder (where the .sln file is) and type &lt;code&gt;code .&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;When you do that you should get a message in VS Code: "Required assets to build and debug are missing from 'Reminders'. Add them?"&lt;/p&gt;

&lt;p&gt;Click Yes.&lt;/p&gt;

&lt;p&gt;That will create a &lt;code&gt;.vscode&lt;/code&gt; folder.&lt;/p&gt;

&lt;p&gt;In that folder there are two files: &lt;code&gt;launch.json&lt;/code&gt; and &lt;code&gt;tasks.json&lt;/code&gt;. &lt;code&gt;launch.json&lt;/code&gt; configures what happens when you press F5 inside VS Code. &lt;/p&gt;

&lt;p&gt;For me the project that will run is the Reminders.Cli console project:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
        {
            "name": ".NET Core Launch (console)",
            "type": "coreclr",
            "request": "launch",
            "preLaunchTask": "build",
            // If you have changed target frameworks, make sure to update the program path.
            "program": "${workspaceFolder}/Reminders.Cli/bin/Debug/netcoreapp2.0/Reminders.Cli.dll",
            "args": [],
            "cwd": "${workspaceFolder}/Reminders.Cli",
            // For more information about the 'console' field, see https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md#console-terminal-window
            "console": "internalConsole",
            "stopAtEntry": false,
            "internalConsoleOptions": "openOnSessionStart"
        },
        {
            "name": ".NET Core Attach",
            "type": "coreclr",
            "request": "attach",
            "processId": "${command:pickProcess}"
        }
    ]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Also, the &lt;code&gt;tasks.json&lt;/code&gt; will only compile the Reminders.Cli project:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "build",
            "command": "dotnet",
            "type": "process",
            "args": [
                "build",
                "${workspaceFolder}/Reminders.Cli/Reminders.Cli.csproj"
            ],
            "problemMatcher": "$msCompile"
        }
    ]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It is possible to customize these two files so that you can pick which project to run. In this case we want to be able to run either Reminders.Web or Reminders.Cli.&lt;/p&gt;

&lt;p&gt;The first thing you should do is to remove the second item in &lt;code&gt;tasks.json&lt;/code&gt;'s args array: "${workspaceFolder}/Reminders.Cli/Reminders.Cli.csproj". We don't need it because we have the solution file (Reminders.sln). When &lt;code&gt;dotnet build&lt;/code&gt; is executed in the folder that contains the sln file all the projects referenced in the solution get built.&lt;/p&gt;

&lt;p&gt;After that we can now go to &lt;code&gt;launch.json&lt;/code&gt; and click the "Add Configuration..." button in the bottom left corner.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F02%2Fadd_configuration_vscode.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F02%2Fadd_configuration_vscode.png" alt="Add Configuration... button"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Select ".Net: Launch a local .NET Core Web Application" and in the generated json change "program" and "cwd" (current working directory) to:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;"program": "${workspaceRoot}/Reminders.Web/bin/Debug/netcoreapp2.0/Reminders.Web.dll",
"cwd": "${workspaceRoot}/Reminders.Web"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You can now go to the Debug "section" of Visual Studio Code and see the Web and Console app configuration there:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F02%2Fselect_vscode_configuration_f5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F02%2Fselect_vscode_configuration_f5.png" alt="Select configuration"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Note that you can change the configuration names if you like, just change the "name" property in &lt;code&gt;launch.json&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now when you press F5 inside VS Code the project that will run is the one that is selected in the Debug section of VS Code.&lt;/p&gt;

&lt;p&gt;This only affects VS Code though, the &lt;code&gt;dotnet run&lt;/code&gt; command is unaffected by these changes.  In the terminal, if you navigate to the solution's folder and type &lt;code&gt;dontet run&lt;/code&gt; you'll get an error (Couldn't find a project to run...). You need to use the &lt;code&gt;--project&lt;/code&gt; argument and specify the path to the csproj file you want to run, e.g.: &lt;code&gt;dotnet run --project Reminders.Web/Reminders.Web.csproj&lt;/code&gt;. Alternatively you can navigate to the project's folder and execute &lt;code&gt;dontet run&lt;/code&gt; there.&lt;/p&gt;

&lt;h2&gt;
  
  
  Adding Classes and Interfaces
&lt;/h2&gt;

&lt;p&gt;In full Visual Studio you have several templates available when adding new files to a project. &lt;/p&gt;

&lt;p&gt;In VS Code the only out of the box option is to create a new file and use the VS Code snippets (e.g. typing class and then TAB).&lt;/p&gt;

&lt;p&gt;Fortunately there's a VS Code extension named &lt;a href="https://marketplace.visualstudio.com/items?itemName=jchannon.csharpextensions" rel="noopener noreferrer"&gt;"C# Extensions"&lt;/a&gt; which adds two options to the context menu on VS Code's explorer view: "New C# Class" and "New C# Interface".&lt;/p&gt;

&lt;p&gt;This extension also adds the ability to generate a class' constructor from properties, generate properties from the constructor and add read-only properties and initialize them (there are &lt;a href="https://marketplace.visualstudio.com/items?itemName=jchannon.csharpextensions" rel="noopener noreferrer"&gt;demos of this in the extension's page&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;This section wouldn't be complete without mentioning a currently abandoned alternative named &lt;a href="http://yeoman.io/" rel="noopener noreferrer"&gt;yeoman&lt;/a&gt;, specifically the &lt;a href="https://github.com/OmniSharp/generator-aspnet" rel="noopener noreferrer"&gt;generator-aspnet&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;Yeoman is a nodejs application that allows you to install yeoman generators which generate code. For ASP.NET Core there was a particularly interesting generator named generator-aspnet.&lt;/p&gt;

&lt;p&gt;That generator provided a set of project templates similar to what &lt;code&gt;dotnet new&lt;/code&gt; now offers (mvc application, console app, etc). But that was not the most interesting thing about generator-aspnet. It was its set of &lt;em&gt;subgenerators&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;A subgenerator in yeoman is a small generator for creating just one file, for example a class, an interface or an empty html page. Here's an example of using generator-asp to create a new class: &lt;code&gt;yo aspnet:class ClassName&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Generator-asp had loads of these:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;yo aspnet:angularcontroller [options] &amp;lt;name&amp;gt;
yo aspnet:angularcontrolleras [options] &amp;lt;name&amp;gt;
yo aspnet:angulardirective [options] &amp;lt;name&amp;gt;
yo aspnet:angularfactory [options] &amp;lt;name&amp;gt;
yo aspnet:angularmodule [options] &amp;lt;name&amp;gt;
yo aspnet:appsettings [options]
yo aspnet:bowerjson [options]
yo aspnet:class [options] &amp;lt;name&amp;gt;
yo aspnet:coffeescript [options] &amp;lt;name&amp;gt;
yo aspnet:dockerfile [options]
yo aspnet:gitignore [options]
yo aspnet:gruntfile [options]
yo aspnet:gulpfile [options] &amp;lt;name&amp;gt;
yo aspnet:htmlpage [options] &amp;lt;name&amp;gt;
yo aspnet:interface [options] &amp;lt;name&amp;gt;
yo aspnet:javascript [options] &amp;lt;name&amp;gt;
yo aspnet:json [options] &amp;lt;name&amp;gt;
yo aspnet:jsonschema [options] &amp;lt;name&amp;gt;
yo aspnet:middleware [options] &amp;lt;name&amp;gt;
yo aspnet:mvccontroller [options] &amp;lt;name&amp;gt;
yo aspnet:mvcview [options] &amp;lt;name&amp;gt;
yo aspnet:nuget [options]
yo aspnet:packagejson [options]
yo aspnet:program [options]
yo aspnet:startup [options]
yo aspnet:stylesheet [options] &amp;lt;name&amp;gt;
yo aspnet:stylesheetless [options] &amp;lt;name&amp;gt;
yo aspnet:stylesheetscss [options] &amp;lt;name&amp;gt;
yo aspnet:taghelper [options] &amp;lt;name&amp;gt;
yo aspnet:textfile [options] &amp;lt;name&amp;gt;
yo aspnet:tfignore [options]
yo aspnet:typescript [options] &amp;lt;name&amp;gt;
yo aspnet:typescriptconfig [options] &amp;lt;name&amp;gt;
yo aspnet:typescriptjsx [options] &amp;lt;name&amp;gt;
yo aspnet:usersecrets [options] &amp;lt;name&amp;gt;
yo aspnet:webapicontroller [options] &amp;lt;name&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Unfortunately they were removed in version 0.3.0. This list is from &lt;code&gt;generator-asp@0.2.6&lt;/code&gt; (latest version as of today, 25/2/2018 is 0.3.3).&lt;/p&gt;

&lt;p&gt;From the talk on the &lt;a href="https://github.com/OmniSharp/generator-aspnet/issues" rel="noopener noreferrer"&gt;generator-aspnet github issues&lt;/a&gt;, although never mentioned explicitly, it seems that dotnet new is the only way to go from now on. Unfortunately the only generation commands that are similar to these subgenerators in dotnet new are &lt;em&gt;Nuget Config&lt;/em&gt;, &lt;em&gt;Web Config&lt;/em&gt;, &lt;em&gt;Razor Page&lt;/em&gt;, &lt;em&gt;MVC ViewImports&lt;/em&gt; and &lt;em&gt;MVC Viewstart&lt;/em&gt; (you get a list of them when you type dotnet new --help).&lt;/p&gt;

&lt;p&gt;You can still install this specific version of generator-aspnet though (npm install &lt;a href="mailto:generator-aspnet@0.2.6"&gt;generator-aspnet@0.2.6&lt;/a&gt;) and use it (some of the generators are still useful).&lt;/p&gt;

&lt;p&gt;However, for creating classes the extension I &lt;a href="https://marketplace.visualstudio.com/items?itemName=jchannon.csharpextensions" rel="noopener noreferrer"&gt;mentioned previously&lt;/a&gt; is the easiest and most convenient to use. Let's use it to create a Reminder class inside the Reminder.Common project.&lt;/p&gt;

&lt;p&gt;The Reminder class has an Id property, a Description, a Date and a boolean flag IsFinished to indicate the reminder was acknowledged.&lt;/p&gt;

&lt;p&gt;First thing you need to do is install the &lt;a href="https://marketplace.visualstudio.com/items?itemName=jchannon.csharpextensions" rel="noopener noreferrer"&gt;"&lt;em&gt;C# Extensions&lt;/em&gt; extension"&lt;/a&gt;. Then right click on Reminders.Common in the explorer view and select New Class:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F03%2Fnew_class_reminders.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F03%2Fnew_class_reminders.png" alt="New Class"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Name it Reminder.cs and create the three properties. In the end it should look like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using System;

namespace Reminders.Common
{
    public class Reminder
    {
        public int Id { get; set; }
        public string Description { get; set; }
        public DateTime Date { get; set; }
        public bool IsFinished { get; set; }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Now put the cursor on the opening "{" after class Reminders and click the light bulb and select "Initialize ctor from properties":&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F03%2Finitialise_ctor_from_properties_reminders.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F03%2Finitialise_ctor_from_properties_reminders.png" alt="Initialize constructor form properties"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You should end up with this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;using System;

namespace Reminders.Common
{
    public class Reminder
    {
        public Reminder(int id, string description, DateTime date, bool isFinished)
        {
            this.Id = id;
            this.Description = description;
            this.Date = date;
            this.IsFinished = isFinished;

        }
        public int Id { get; set; }
        public string Description { get; set; }
        public DateTime Date { get; set; }
        public bool IsFinished { get; set; }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Although the constructor isn't really necessary (and it won't play well with Entity Framework if you are planning to use it) , it's just an example of some nice features you get from the extension. Also, when defining properties you can use the same snippets that are available in full Visual Studio (i.e. type prop and press TAB).&lt;/p&gt;

&lt;h2&gt;
  
  
  Razor views
&lt;/h2&gt;

&lt;p&gt;Razor pages (.cshtml) is definitely an area where VS Code is lacking. There's no intellisense or even auto-indent.&lt;/p&gt;

&lt;p&gt;There's an extension in the marketplace named &lt;a href="https://marketplace.visualstudio.com/items?itemName=schneiderpat.aspnet-helper" rel="noopener noreferrer"&gt;ASP.NET Helper&lt;/a&gt; which will get you intellisense, however you have to import the namespaces for your models in &lt;code&gt;_ViewImports.chtml&lt;/code&gt; (the extension's requirements are at the bottom of the extensions page). Also in its current version it only seems to work if the model you use is in the same project as the view. &lt;/p&gt;

&lt;p&gt;This extension can be useful in some situations but it's very limited.&lt;/p&gt;

&lt;p&gt;If this is a deal breaker for you here's the &lt;a href="https://github.com/OmniSharp/omnisharp-vscode/issues/168" rel="noopener noreferrer"&gt;github issue&lt;/a&gt; for adding Razor support to the language service that VS Code relies on and which would provide intellisense similar to what is there for the full version of Visual Studio. If you upvote or leave a comment there it will bring visibility to this issue.&lt;/p&gt;

&lt;p&gt;If you want a good experience while creating razor pages today and you don't mind paying a little bit of money you can try &lt;a href="https://www.jetbrains.com/rider/" rel="noopener noreferrer"&gt;JetBrains Rider&lt;/a&gt;. Rider runs on Windows, Mac and Linux and is from the same people that created ReSharper. I tried it a good few months ago when it was in beta. At that time it required a fairly decent machine to run smoothly and it was lacking some features. I tried it again today while I'm writing this and it seems much much better. Razor support seems perfect.&lt;/p&gt;

&lt;p&gt;Even though the experience with Razor in VS Code right now is not ideal, if you go with a front-end JavaScript framework (Angular, React, Vue, etc) instead of Razor, you'll find that VS Code is excellent. I've used mostly Angular and TypeScript and this is an area where VS Code is arguably better then the full version of Visual Studio.&lt;/p&gt;

&lt;p&gt;If you are somewhat familiar with Angular and are planning to use ASP.NET Core as a Web Api for your front end check out my other article &lt;a href="https://www.blinkingcaret.com/2018/01/24/angular-and-asp-net-core/" rel="noopener noreferrer"&gt;Angular and ASP.NET Core&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Nuget packages
&lt;/h2&gt;

&lt;p&gt;In the full version of Visual Studio there's an option to Manage NuGet packages. You get an UI where you can search, update and install NuGet packages. In VS Code there's no support for NuGet out of the box.&lt;/p&gt;

&lt;p&gt;Thankfully there's an extension you can install that will enable searching, adding and removing NuGet packages from VS Code. The extension is named &lt;a href="https://marketplace.visualstudio.com/items?itemName=jmrog.vscode-nuget-package-manager" rel="noopener noreferrer"&gt;NuGet Package Manager&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Alternatively you can use the command line. To add a package to a project the syntax is: &lt;code&gt;dotnet add PathToCsproj package PackageName&lt;/code&gt;. Or, if you navigate to the project you want to add the NuGet package to, you can omit the path to the csproj file: &lt;code&gt;dotnet add package PackageName&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Imagine you wanted to add the &lt;code&gt;Microsoft.EntityFrameworkCore&lt;/code&gt; package to Reminders.Common class library. After navigating to it:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ dotnet add package Microsoft.EntityFrameworkCore
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Adding tools
&lt;/h2&gt;

&lt;p&gt;An example of a CLI tool is for example Entity Framework's tool. That's what runs when you type in a project that has the EF tooling installed:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ dotnet ef
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And you should get this output:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;             _/\__
       ---==/    \\
___  ___   |.    \|\
| __|| __|  |  )   \\\
| _| | _|   \_/ |  //|\\
|___||_|       /   \\\/\\

Entity Framework Core .NET Command Line Tools 2.0.1-rtm-125

Usage: dotnet ef [options] [command]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Unfortunately there's no automated way of configuring dotnet tooling. If you start with a project template that doesn't have the right setup you'll have to manually edit the .csproj file. &lt;/p&gt;

&lt;p&gt;Not only that but you'll have to know the right package name and version. &lt;/p&gt;

&lt;p&gt;This is not a problem specific to VS Code or Linux. This is a tooling problem. Here are the relevant issues in github: &lt;a href="https://github.com/dotnet/cli/issues/5998" rel="noopener noreferrer"&gt;dotnet add package doesn't honor package type&lt;/a&gt; and &lt;a href="https://github.com/NuGet/Home/issues/4190" rel="noopener noreferrer"&gt;VS 2017: PackageType=DotnetCliTool fails to install&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;There's a way to manually do it though. If you open a .csproj file you'll notice that it has &lt;code&gt;ItemGroup&lt;/code&gt; sections. For example, for a new mvc project there's this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;ItemGroup&amp;gt;
    &amp;lt;PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" /&amp;gt;        
&amp;lt;/ItemGroup&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;For the tooling you should create another &lt;code&gt;ItemGroup&lt;/code&gt; and inside it instead of &lt;code&gt;PackageReference&lt;/code&gt; use &lt;code&gt;DotNetCliToolReference&lt;/code&gt; (there may already be an ItemGroup with DotNetCliToolReference in your project, if that's the case just add to it).&lt;/p&gt;

&lt;p&gt;Let's imagine we want to use the Entity Framework tooling in our web project. Navigate to &lt;code&gt;Reminders.Web&lt;/code&gt; and open the csproj file. &lt;/p&gt;

&lt;p&gt;Make note of the version of &lt;code&gt;Microsoft.AspNetCore.All&lt;/code&gt; package. For example, let's imagine it's "2.0.0".&lt;/p&gt;

&lt;p&gt;Create a new &lt;code&gt;ItemGroup&lt;/code&gt; (or find the ItemGroup that already has &lt;code&gt;DotNetCliToolReferences&lt;/code&gt;) and inside add the &lt;code&gt;DotNetCliToolReference&lt;/code&gt; for the &lt;code&gt;Microsoft.EntityFrameworkCore.Tools.DotNet&lt;/code&gt; with &lt;code&gt;Version="2.0.0"&lt;/code&gt;.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;ItemGroup&amp;gt;
    &amp;lt;PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0" /&amp;gt;            
&amp;lt;/ItemGroup&amp;gt;
&amp;lt;ItemGroup&amp;gt;
    &amp;lt;DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" /&amp;gt; &amp;lt;!-- ADD THIS --&amp;gt;
    &amp;lt;DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0" /&amp;gt;        
&amp;lt;/ItemGroup&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You should now be able to run &lt;code&gt;dotnet ef&lt;/code&gt; in the Reminders.Web project.&lt;/p&gt;

&lt;p&gt;The reason the version must match "Microsoft.AsNetCore.All" is because that package is a metapackage, i.e. a package that just references other packages. Some of those packages are Entity Framework packages which would cause compatibility issues with the tooling if the version does not match.&lt;/p&gt;

&lt;p&gt;If we were installing Entity Framework Core tooling in a console project you wouldn't need to worry about the version. &lt;a href="https://docs.microsoft.com/en-us/ef/core/miscellaneous/cli/dotnet#installing-the-tools" rel="noopener noreferrer"&gt;You would however have to add the package &lt;code&gt;Microsoft.EntityFrameworkCore.Design&lt;/code&gt; additionally to manually adding the &lt;code&gt;DotNetCliToolReference&lt;/code&gt;&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Running tests
&lt;/h2&gt;

&lt;p&gt;One thing your development workflow probably involves is writing unit tests. &lt;/p&gt;

&lt;p&gt;VS Code comes with out of the box support for running unit tests. For example if you open UnitTest1.cs you'll notice that over the test method there are two links, run test and debug test: &lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F03%2Frun_test_debug_test.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fwww.blinkingcaret.com%2Fwp-content%2Fuploads%2F2018%2F03%2Frun_test_debug_test.png" alt="run test, debug test"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This will allow you to run a unit test at a time, there's no way inside VS Code of running all the tests in a project. You can however navigate to a test project in a terminal and type:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ dotnet test
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This is the output you should get if you do it for Reminders.Tests:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Starting test execution, please wait...
[xUnit.net 00:00:00.4275346]   Discovering: Reminders.Tests
[xUnit.net 00:00:00.5044862]   Discovered:  Reminders.Tests
[xUnit.net 00:00:00.5549595]   Starting:    Reminders.Tests
[xUnit.net 00:00:00.6980509]   Finished:    Reminders.Tests

Total tests: 1. Passed: 1. Failed: 0. Skipped: 0.
Test Run Successful.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Alternatively you can specify the path to the test project you want to run, for example &lt;code&gt;dotnet test Reminders.Tests/Reminders.Tests.csproj&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It is also possible to specify which tests to run in the command line, for example say you only want to run the tests in class MyClassTests. Here's how you can do that:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ dotnet test --filter MyClassTests
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;The filter functionality has &lt;a href="https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-test?tabs=netcore2x#filter-option-details" rel="noopener noreferrer"&gt;several more options&lt;/a&gt;. The example above is short for &lt;code&gt;dotnet test --filter FullyQualifiedName~MyClassTests&lt;/code&gt; (~ means contains).&lt;/p&gt;

&lt;p&gt;There are other handy options, for example in xUnit it's possible to specify "traits" for tests, for example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[Trait("TraitName", "TraitValue")]
public class UnitTest1
{
    [Fact]        
    public void Test1()
    {
        //...
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You can then run:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ dotnet test --filter TraitName=TraitValue
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And only tests that have that trait will be run. You can specify &lt;code&gt;Trait&lt;/code&gt; on a method or class level.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://docs.microsoft.com/en-us/dotnet/core/tools/dotnet-test?tabs=netcore2x#filter-option-details" rel="noopener noreferrer"&gt;Although trait is specific to xUnit&lt;/a&gt;, there are equivalent constructs on other testing frameworks. For example, mstest has &lt;code&gt;TestCategory&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If you prefer to do everything inside VS Code you can create tasks for running tests. First go to &lt;code&gt;tasks.json&lt;/code&gt; and make a copy of the build task, change its label to test (or whatever you want to call it) and update the args so that instead of build, test is executed with the path to the test project, for example for Reminders.Tests:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    {
        "label": "test",
        "command": "dotnet",
        "type": "process",
        "args": [
            "test",
            "${workspaceFolder}/Reminders.Tests/Reminders.Tests.csproj"
        ],
        "problemMatcher": "$msCompile"
    } 
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You can run tasks in VS Code by using the command palette (Ctrl + Shift + P) and typing "Run Task" and then selecting the task you want to run. You can even set a task as the "test task" and assign a keyboard shortcut for it (the same way you can do Ctrl + Shift + B to trigger a task configured as the "build task").&lt;/p&gt;

&lt;p&gt;To set a task as the "test task" open the command palette and select "Tasks: Configure Default Test Task", choose the test task and you're done.&lt;/p&gt;

&lt;h2&gt;
  
  
  One last tip
&lt;/h2&gt;

&lt;p&gt;Sometimes VS Code (actually Omnisharp) seems to go haywire, for example intellisense stops working. When that happens you can either reload VS Code by using the command palette and selecting "Reload Window" or the less aggressive option is to restart Omnisharp (the command name is: Omnisharp: Restart Omnisharp).&lt;/p&gt;

&lt;p&gt;Hope this guide was helpful, let me know in the comments.&lt;/p&gt;

</description>
      <category>dotnet</category>
      <category>webdev</category>
      <category>linux</category>
    </item>
    <item>
      <title>Angular and ASP.NET Core</title>
      <dc:creator>Rui Figueiredo</dc:creator>
      <pubDate>Thu, 01 Mar 2018 23:01:07 +0000</pubDate>
      <link>https://dev.to/ruidfigueiredo/angular-and-aspnet-core--4m1l</link>
      <guid>https://dev.to/ruidfigueiredo/angular-and-aspnet-core--4m1l</guid>
      <description>&lt;p&gt;The &lt;a href="https://cli.angular.io/" rel="noopener noreferrer"&gt;Angular CLI&lt;/a&gt; provides a way to develop front-end applications using angular that hides a lot of details. For example there's no requirement to understand how &lt;a href="https://webpack.js.org/" rel="noopener noreferrer"&gt;Webpack&lt;/a&gt; or &lt;a href="https://github.com/systemjs/systemjs" rel="noopener noreferrer"&gt;SystemJS&lt;/a&gt; work.&lt;/p&gt;

&lt;p&gt;In fact, if you don't know a little bit about Webpack, which is what is used to build the latest version of Angular applications, the CLI almost looks like magic. You just need to do a &lt;code&gt;ng new&lt;/code&gt; and &lt;code&gt;ng serve --open&lt;/code&gt; and you have a working Angular application open in your web browser.&lt;/p&gt;

&lt;p&gt;The fact that the CLI hides all the plumbing might lead to questions like: "How do I use Angular with ASP.NET Core?".&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6ac59tlaxdliryiqsnul.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6ac59tlaxdliryiqsnul.png" alt="Angular and Asp.Net Core logos"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I hope that by the end of this blog post it will be clear to you how you can answer that question (and not only with ASP.NET Core, with whichever technology you want to use your Angular app with). &lt;/p&gt;

&lt;p&gt;You see, an angular app is an app in and of itself, it does need to be "served" somehow by a web server.&lt;/p&gt;

&lt;p&gt;When you compile an angular application you are producing a set of JavaScript, CSS and one index.html file. That's it. &lt;/p&gt;

&lt;p&gt;The default folder where those "artifacts" get copied to is &lt;code&gt;yourApplicationFolder/dist&lt;/code&gt;. You can check it out by going to your Angular application and doing an &lt;code&gt;ng build&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Go on, I'll wait.&lt;/p&gt;

&lt;p&gt;When you do &lt;code&gt;ng serve --open&lt;/code&gt; you are actually using a stand-alone web server (&lt;a href="https://github.com/webpack/webpack-dev-server" rel="noopener noreferrer"&gt;webpack-dev-server&lt;/a&gt;) to serve that index.html file in the dist folder.&lt;/p&gt;

&lt;p&gt;The rest of this blog post will describe several approaches that you can take for using Angular with ASP.NET Core. The first is to have ASP.NET Core serve the Angular files. &lt;/p&gt;

&lt;p&gt;The second approach is to have Angular and ASP.NET Core as different applications. There's an example of how to achieve this using Nginx where both Angular and ASP.NET Core are served using port 80 and in IIS where each application is served from its own port.&lt;/p&gt;

&lt;p&gt;The final part of the post describes a setup that I consider ideal where you can use Angular's &lt;code&gt;ng serve&lt;/code&gt; during development.&lt;/p&gt;

&lt;p&gt;This post is quite long but the sections are fairly independent. If your are only interested in the last section and you are using Windows I recommend also reading the section on how to configure Angular in IIS.&lt;/p&gt;

&lt;h2&gt;
  
  
  Using ASP.NET Core to serve the Angular application
&lt;/h2&gt;

&lt;p&gt;It can be argued that serving an Angular application "within" ASP.NET Core is wasteful in terms of resources. In the end the Angular application is just a set of static files, there's no need to have the request for those files go through the ASP.NET Core middleware pipeline.&lt;/p&gt;

&lt;p&gt;There might be some good reasons for doing it though, also there's no harm in knowing how to do it and since it seems to be a common approach, being familiar with it might be useful.&lt;/p&gt;

&lt;p&gt;One important thing to know in order to understand how we can serve an  ASP.NET Core and Angular application together is to understand how a request is processed in ASP.NET Core.&lt;/p&gt;

&lt;p&gt;When you run an ASP.NET Core application your request goes through a "pipeline" of &lt;a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware?tabs=aspnetcore2x" rel="noopener noreferrer"&gt;middlewares&lt;/a&gt;. Every time a request comes in it goes through the middlewares in the order they are defined, and then in reverse order. &lt;/p&gt;

&lt;p&gt;Every middleware has an opportunity to change the request or response two times, once before the other middlewares have been executed, and then after the other middlewares have executed. This allows for a middleware at the top of the pipeline to handle for example, a 401 response set by a middleware further down in the pipeline. &lt;/p&gt;

&lt;p&gt;An example of this are the authentication middlewares that change a 401 response to a 302 redirect to a login page.&lt;/p&gt;

&lt;p&gt;You can find the definition of this pipeline on the &lt;code&gt;Startup.cs&lt;/code&gt; file, in the &lt;code&gt;Configure&lt;/code&gt; method. For example, here's the pipeline that you get when you do a &lt;code&gt;dotnet new mvc&lt;/code&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseStaticFiles();

    app.UseMvc(routes =&amp;gt;
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Every time a request comes in to this ASP.NET Core application it can go through at most three middlewares. First the &lt;code&gt;DeveloperExceptionPage&lt;/code&gt;/&lt;code&gt;ExceptionHandler&lt;/code&gt; middleware depending if the ASP.NET Core application is running in development mode or not. Then the &lt;code&gt;StaticFiles&lt;/code&gt; middleware and then finally the &lt;code&gt;Mvc&lt;/code&gt; middleware.&lt;/p&gt;

&lt;p&gt;The middleware that is key here is &lt;code&gt;StaticFiles&lt;/code&gt;. This is the middleware that serves files contained in the &lt;code&gt;wwwroot&lt;/code&gt; folder, i.e. if a request comes in for index.html and there's an index.html file at &lt;code&gt;wwwroot/index.html&lt;/code&gt; then that file is sent to the client. &lt;code&gt;StaticFiles&lt;/code&gt; middleware won't call the middlewares below it after this (in this case it would be &lt;code&gt;Mvc&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;You can probably already see how this could work with an Angular application. Just put it under &lt;code&gt;wwwroot&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;That's absolutely correct, however there's a detail about &lt;code&gt;StaticFiles&lt;/code&gt; that is important to know. &lt;code&gt;StaticFiles&lt;/code&gt; won't try to do any guesses for you, i.e. if your request is for &lt;code&gt;/&lt;/code&gt;, &lt;code&gt;StaticFiles&lt;/code&gt; won't look for &lt;code&gt;/index.html&lt;/code&gt;. It will just assume that this request isn't supposed to be handled by it and it will call the next middleware in the pipeline, in this case &lt;code&gt;Mvc&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;For this approach to work you need another middleware named &lt;code&gt;DefaultFiles&lt;/code&gt; which must come before &lt;code&gt;StaticFiles&lt;/code&gt; in the pipeline:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//...
app.UseDefaultFiles();
app.UseStaticFiles();
//...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;&lt;a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files" rel="noopener noreferrer"&gt;&lt;code&gt;DefaultFiles&lt;/code&gt;&lt;/a&gt; will cause cause &lt;code&gt;StaticFiles&lt;/code&gt; to look for &lt;code&gt;index.html&lt;/code&gt; if the url ends with &lt;code&gt;/&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now the only thing left to do is to configure your Angular CLI to compile to your ASP.NET Core application's wwwroot folder.&lt;/p&gt;

&lt;p&gt;If you look in your Angular's application folder you'll find a .angular-cli.json file. In that file look for the &lt;code&gt;outDir&lt;/code&gt; property:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
"apps": [
{
    ...
    "outDir": "dist",
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Change it from "dist" to the path of your ASP.NET Core's wwwroot folder. Run &lt;code&gt;ng build&lt;/code&gt; in your Angular application and now if you run your ASP.NET Core web application you should see your Angular application in the browser.&lt;/p&gt;

&lt;p&gt;A nice development workflow is to run the Angular CLI build in watch mode: In a console window do &lt;code&gt;ng build --watch&lt;/code&gt; or &lt;code&gt;ng build -w&lt;/code&gt; if you want to save a few key strokes, and leave it running. Now every time you make a change in your Angular application you can just refresh the browser and see the change (you also need to have your ASP.NET Core application running).&lt;/p&gt;

&lt;p&gt;There is one thing missing from this approach, though. Deep-linking support, i.e. if your Angular application uses routing and you send a user a url with a valid Angular route (e.g &lt;a href="http://yourapplication.com/products/5" rel="noopener noreferrer"&gt;http://yourapplication.com/products/5&lt;/a&gt;) the receiving user won't be able to open it. Trying to get to that route will result in a 404 Not Found response.&lt;/p&gt;

&lt;p&gt;That's because the request will go all the way through your ASP.NET Core application's pipeline and when it reaches the MVC middleware it won't know what to do with it and will set the response's status code to 404 Page Not Found.&lt;/p&gt;

&lt;p&gt;What we can do is at the top of the pipeline we look for a 404 response that is about to be sent and change its path to our Angular application's index.html file (that way what gets served is the Angular application which will know what to do with the url in terms of routing). After this we make the request go through the pipeline again:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//add this at the start of Configure
app.Use(async (HttpContext context, Func&amp;lt;Task&amp;gt; next) =&amp;gt;
{
    await next.Invoke();

    if (context.Response.StatusCode == 404)
    {
        context.Request.Path = new PathString("/index.html");
        await next.Invoke();
    }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That fixes deep links but introduces a new problem. What if your web api (that you've implemented in your ASP.NET Core application) needs to send a 404 response. That's something more than reasonable to do. Instead of a 404, the service call will receive a 200 response with index.html.&lt;/p&gt;

&lt;p&gt;The solution here is to look at the url and decide if it's intended for the web api or an Angular route. Usually a call to the web api will have &lt;code&gt;/api&lt;/code&gt; in the url. That's a simple test to perform and it will solve this problem. Here's the revised version of a custom middleware that solves this problem:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;//add this at the start of Configure
app.Use(async (HttpContext context, Func&amp;lt;Task&amp;gt; next) =&amp;gt;
{
    await next.Invoke();

    if (context.Response.StatusCode == 404 &amp;amp;&amp;amp; !context.Request.Path.Value.Contains("/api")))
    {
        context.Request.Path = new PathString("/index.html");
        await next.Invoke();
    }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;One last note about this approach. I've seen examples where the Angular application is in the same Visual Studio solution as the ASP.NET application. Visual Studio (not VS Code) will try to compile the typescript files. If you are using &lt;code&gt;ng build -w&lt;/code&gt; you'll want Visual Studio to leave your Typescript files alone. &lt;a href="https://stackoverflow.com/questions/42430300/disable-msbuild-typescript-compile" rel="noopener noreferrer"&gt;To do that open your project's &lt;code&gt;.csproj&lt;/code&gt; and add in any &lt;code&gt;PropertyGroup&lt;/code&gt;&lt;/a&gt;: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;TypescriptCompileBlocked&amp;gt;true&amp;lt;/TypescriptCompileBlocked&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Nginx
&lt;/h2&gt;

&lt;p&gt;&lt;a href="https://www.nginx.com/" rel="noopener noreferrer"&gt;Nginx&lt;/a&gt; is a web server that can act as a reverse proxy for ASP.NET Core applications and which is also very good at serving static content.&lt;/p&gt;

&lt;p&gt;The setup for having an Angular application work with ASP.NET Core is much simpler in Nginx. You just need a configuration similar to this:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;server {
    listen 80;        

    location / {
        root /pathToYourAngularApplication/dist;
        index index.html;
        try_files $uri $uri/ /index.html;
    }

    location /api/ {
        proxy_pass http://localhost:5000;
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This is how a typical Nginx configuration file looks like. If you are not familiar with Nginx and ASP.NET Core I recommend my blog post: &lt;a href="http://www.blinkingcaret.com/2017/03/01/https-asp-net-core/" rel="noopener noreferrer"&gt;HTTPS in ASP.NET Core from Scratch&lt;/a&gt;. It has a section with instructions on how to install and setup websites using Nginx.&lt;/p&gt;

&lt;p&gt;This configuration allows us to have both the Angular and ASP.NET Core application on port 80. Let's look at the important parts in it. &lt;/p&gt;

&lt;p&gt;The &lt;code&gt;listen 80&lt;/code&gt; statement establishes that Nginx will respond to requests coming in on port 80.&lt;/p&gt;

&lt;p&gt;The &lt;code&gt;location&lt;/code&gt; blocks are where we are going to define how our two applications will be served (Angular and ASP.NET). Each time a request comes in, Nginx will look at the URL and try to find the location block &lt;a href="https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms" rel="noopener noreferrer"&gt;that best matches it&lt;/a&gt;. In this case the location blocks urls act like a "prefix match", i.e., the first block will match every URL (every url that starts with a &lt;code&gt;/&lt;/code&gt;). The second location block matches URLs that start with &lt;code&gt;/api/&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Nginx picks the most "specific" location block, so even though a request for &lt;code&gt;/api/users&lt;/code&gt; would match both location blocks, since the second one (&lt;code&gt;/api/&lt;/code&gt;) is more specific, it will be the one that would be used to handle the request.&lt;/p&gt;

&lt;p&gt;In the first location block (&lt;code&gt;/&lt;/code&gt;):&lt;/p&gt;

&lt;p&gt;&lt;code&gt;root /pathToYourAngularApplication/dist&lt;/code&gt; sets the path where static content will be looked for as the location where your compiled Angular application files are (&lt;code&gt;dist&lt;/code&gt; is the CLI's default output folder).&lt;/p&gt;

&lt;p&gt;&lt;code&gt;index index.html&lt;/code&gt; specifies which file should be served for URLs that end in &lt;code&gt;/&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;try_files $uri $uri/ /index.html&lt;/code&gt; can be read this way: check if there's a file that matches the normalized URL (e.g. &lt;a href="http://www.yourwebsite.com/assets/image.jpg" rel="noopener noreferrer"&gt;http://www.yourwebsite.com/assets/image.jpg&lt;/a&gt; -&amp;gt; /assets/image.jpg), if that file does not exist try the normalized URL plus a &lt;code&gt;/&lt;/code&gt; (e.g. &lt;a href="http://www.yourwebsite.com/documents" rel="noopener noreferrer"&gt;http://www.yourwebsite.com/documents&lt;/a&gt; -&amp;gt; /documents/ -&amp;gt; /documents/index.html because of the &lt;code&gt;index&lt;/code&gt; rule). If all of that fails serve the file &lt;code&gt;/index.html&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Serving &lt;code&gt;/index.html&lt;/code&gt; if no match is found is what enables us to use deep linking. For example a URL such as &lt;code&gt;http://www.yourwebsite.com/documents&lt;/code&gt; with no math in the file system will be served with the Angular application's index.html. &lt;code&gt;Index.html&lt;/code&gt; will load all the necessary files for the Angular application to run, specifically the routing module. The routing module will then look at the url, and according to the routes defined in the angular app will decide which component to load.&lt;/p&gt;

&lt;p&gt;Finally, the last location block. It instructs Nginx to forward the requests that start with &lt;code&gt;/api/&lt;/code&gt; to a webserver that is listening on port 5000 on &lt;code&gt;localhost&lt;/code&gt;. That will be your ASP.NET Core's application.&lt;/p&gt;

&lt;p&gt;One note about the Nginx's syntax for &lt;code&gt;proxy_pass&lt;/code&gt;. It matters a lot if the URL for the application has a &lt;code&gt;/&lt;/code&gt; at the end or not. The url in &lt;code&gt;proxy_pass&lt;/code&gt; is treated differently if it has what is described in &lt;a href="http://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass" rel="noopener noreferrer"&gt;Nginx's documentation as a "optional URI"&lt;/a&gt; (optional URI isn't a great name, since in the end a &lt;a href="https://danielmiessler.com/study/url-uri/" rel="noopener noreferrer"&gt;URL is a URI&lt;/a&gt;). &lt;/p&gt;

&lt;p&gt;An example of a URL with an optional URI is: &lt;code&gt;http://localhost:5000/optionalURI/&lt;/code&gt;. If the location's path is &lt;code&gt;/api/&lt;/code&gt;, then a request for &lt;code&gt;http://yourwebsite.com/api/users&lt;/code&gt; will be forwarded to your ASP.NET Core's application as &lt;code&gt;http://localhost:5000/optionalURI/users&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;That's why not adding the &lt;code&gt;/&lt;/code&gt; at the end in &lt;code&gt;proxy_pass&lt;/code&gt; is so important, because if you do (e.g.: &lt;code&gt;proxy_pass http://localhost:5000/;&lt;/code&gt;) it falls into the "optional URI" category (it will be interpreted as an empty optional URI), and a request for &lt;code&gt;http://yourwebsite.com/api/users&lt;/code&gt; will be seen in your ASP.NET Core's application as a request for &lt;code&gt;http://localhost:5000/users&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;If you don't add the &lt;code&gt;/&lt;/code&gt; at the end (e.g.: &lt;code&gt;proxy_pass http://localhost:5000;&lt;/code&gt;) then a request for &lt;code&gt;http://yourwebsite.com/api/users&lt;/code&gt; will be seen in the ASP.NET Core application as a request for &lt;code&gt;http://localhost:5000/api/users&lt;/code&gt; which is probably what you want.&lt;/p&gt;

&lt;p&gt;If you need a more complete example that explains how you can make this work outside a development-time scenario (i.e. have your ASP.NET Core application auto start and remain online even if there's an exception) check out &lt;a href="http://www.blinkingcaret.com/2017/03/01/https-asp-net-core/" rel="noopener noreferrer"&gt;HTTPS in ASP.NET Core from Scratch&lt;/a&gt; where there's an example describing how you can use &lt;a href="http://supervisord.org/" rel="noopener noreferrer"&gt;Supervisor&lt;/a&gt; to keep the ASP.NET application running even in the event of errors (by auto restarting it).&lt;/p&gt;

&lt;h2&gt;
  
  
  IIS
&lt;/h2&gt;

&lt;p&gt;With IIS it becomes very cumbersome to have a configuration similar to what we can do with Nginx where both the Angular and ASP.NET Core applications are served on port 80.&lt;/p&gt;

&lt;p&gt;To understand why it makes it easier if we understand the IIS concepts of Website and Application. When you create a website you define (among other settings) the port (e.g. 80) where it will be served from. A website can then have several applications "inside" it, all of which will share the website configuration (and therefore be served on the same port).&lt;/p&gt;

&lt;p&gt;We could for example put our Angular application inside the "Default Web Site" and the ASP.NET Core one as an IIS Application under it, and call it for example "api".&lt;/p&gt;

&lt;p&gt;If the "Default Web Site" responds at &lt;a href="http://localhost" rel="noopener noreferrer"&gt;http://localhost&lt;/a&gt;, then the ASP.NET Core application could be at &lt;a href="http://localhost/api" rel="noopener noreferrer"&gt;http://localhost/api&lt;/a&gt;. Which seems to be exactly what we want. However, the requests for &lt;a href="http://localhost/api" rel="noopener noreferrer"&gt;http://localhost/api&lt;/a&gt; would be seen in ASP.NET Core without the api in the url.&lt;/p&gt;

&lt;p&gt;As far as I know there's no way to change this behavior.&lt;/p&gt;

&lt;p&gt;This means your ASP.NET Core application will behave differently when running inside IIS vs when executed directly (either in Visual Studio or with dotnet run).&lt;/p&gt;

&lt;p&gt;To make matters worse an ASP.NET Core application needs to be published (dotnet publish) for it to work in IIS. It's not like a non-Core ASP.NET application where you can just point an IIS Application to the folder that contains the ASP.NET application's files .&lt;/p&gt;

&lt;p&gt;So when using IIS the reasonable options are to either have ASP.NET Core serve the angular application as it was described in the first section of this article or have two separate Websites. &lt;/p&gt;

&lt;p&gt;Lets walk-though the process of creating two separate websites. First a website for the Angular project and then for ASP.NET Core.&lt;/p&gt;

&lt;h3&gt;
  
  
  Angular in IIS
&lt;/h3&gt;

&lt;p&gt;We'll be adding a Website named &lt;em&gt;MyNgWebSite&lt;/em&gt; on port 80. That means that if you have a "Default Web Site", which in all likelihood you'll have, you need to stop it or change its bindings since the default for it is port 80.&lt;/p&gt;

&lt;p&gt;But before we get there we need to create an application pool for our Angular application. Right click on Application Pools in IIS Manager:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F02fiem5pk5gj50e2u5li.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F02fiem5pk5gj50e2u5li.png" alt="Right click on application pools"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The Application Pool for an Angular application does not require Managed Code (we only need to serve static files). We should choose "No Managed Code" in the .NET CLR Version:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0p047yyu4pb3s2gphjml.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0p047yyu4pb3s2gphjml.png" alt="No Managed Code application pool"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We can now add a new IIS web site and set the new application pool we created as its application pool:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0hdvpc8eeszuw48x3rpd.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F0hdvpc8eeszuw48x3rpd.png" alt="Add new web site"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl949936fr271026wml8h.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fl949936fr271026wml8h.png" alt="Configure website"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The physical path should be set to where your Angular project is being compiled to, usually this is the &lt;code&gt;dist&lt;/code&gt; folder.&lt;/p&gt;

&lt;p&gt;If you were to try to access &lt;code&gt;http://localhost&lt;/code&gt; right now (and assuming that you stopped the "Default Web Site" or used a different port than 80) you would get a permissions error. That's because when you create an application pool a &lt;a href="https://docs.microsoft.com/en-us/iis/manage/configuring-security/application-pool-identities" rel="noopener noreferrer"&gt;"virtual" user is created&lt;/a&gt;. That user is a &lt;strong&gt;local&lt;/strong&gt; user and must have permissions to access the folder that contains the files you are trying to serve.&lt;/p&gt;

&lt;p&gt;That user's name is &lt;code&gt;IIS AppPool\ApplicationPoolName&lt;/code&gt;, in this example it's &lt;code&gt;IIS AppPool\ApplicationPoolForAngular&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Go to the folder that contains the compiled Angular project, right click on it and select properties, go to the security tab, click edit, then add and finally add the application pool user:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgye5v92o6ij55etwivdy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgye5v92o6ij55etwivdy.png" alt="Configure permissions for the folder"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We should now be able to access your Angular application if you go to &lt;code&gt;http://localhost&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;We still need to do one more thing though. Enable deep-linking support.&lt;/p&gt;

&lt;p&gt;If you have routes in your Angular application these won't work if someone tries to access them from "outside" the Angular app. What this means is that if navigating to &lt;a href="http://localhost/documents" rel="noopener noreferrer"&gt;http://localhost/documents&lt;/a&gt; is valid inside the Angular application and you send that url to someone else, when that someone else clicks the link they will be greeted with a 404 page from IIS.&lt;/p&gt;

&lt;p&gt;That's because there is no documents folder nor index file inside it for IIS to serve. We need to tell IIS that it must serve the file &lt;code&gt;index.html&lt;/code&gt; when someone tries to access a URL that does not exists.&lt;/p&gt;

&lt;p&gt;We are going to use the same mechanism used for having a &lt;a href="https://dusted.codes/demystifying-aspnet-mvc-5-error-pages-and-error-logging" rel="noopener noreferrer"&gt;custom 404 page&lt;/a&gt;, but instead of a 404 page we'll serve the Angular application.&lt;/p&gt;

&lt;p&gt;To achieve this we need to create a &lt;code&gt;web.config&lt;/code&gt; file and put it in the src folder of the Angular application with this inside:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;?xml version="1.0" encoding="UTF-8"?&amp;gt;
&amp;lt;configuration&amp;gt;
    &amp;lt;system.webServer&amp;gt;
        &amp;lt;httpErrors errorMode="Custom" existingResponse="Replace"&amp;gt;
            &amp;lt;remove statusCode="404"/&amp;gt;
            &amp;lt;error statusCode="404" responseMode="ExecuteURL" path="/index.html"/&amp;gt;
        &amp;lt;/httpErrors&amp;gt;
    &amp;lt;/system.webServer&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;A very quick explanation of what's going on. We are using &lt;code&gt;httpErrors&lt;/code&gt; with an &lt;code&gt;errorMode="Custom"&lt;/code&gt; and &lt;code&gt;existingResponse="Replace"&lt;/code&gt;. This instructs IIS to replace the default error pages with the one we are about to specify.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;remove statusCode="404"&lt;/code&gt; will remove any custom settings for 404 pages if they already exist.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;error statusCode="404" responseMode="ExecuteURL" path="/index.html"&lt;/code&gt; will configure IIS to execute the &lt;code&gt;/index.html&lt;/code&gt; url if there's a 404 error. This will effectively serve your Angular application and won't change the URL seen by the client.&lt;/p&gt;

&lt;p&gt;Now we need to edit the &lt;code&gt;.angular-cli.json&lt;/code&gt; file so that &lt;code&gt;web.config&lt;/code&gt; gets copied to the output folder as an asset when the application is compiled. The assets section is under "app", here's an example:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
    "name": "your-app"
},
"apps": [
    {
    "root": "src",
    "outDir": "dist",
    "assets": [
        "assets",
        "favicon.ico", 
        "web.config"
    ],
    "index": "index.html",
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h3&gt;
  
  
  ASP.NET Core in IIS
&lt;/h3&gt;

&lt;p&gt;The process for the configuring an ASP.NET Core application in IIS is similar, although we need to select a different port. &lt;/p&gt;

&lt;p&gt;But before you start you need to make sure you have the &lt;a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/aspnet-core-module?tabs=aspnetcore2x" rel="noopener noreferrer"&gt;ASP.NET Core Module&lt;/a&gt; for IIS installed. It might already be installed if you installed the .Net Core SDK, however the best way to make sure is to go to IIS Manager and see if it's in the modules' list:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm42m72waehwdrzn4mha3.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fm42m72waehwdrzn4mha3.png" alt="Module list with AspNetCoreModule"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you don't have it you can find more information about it &lt;a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/servers/aspnet-core-module?tabs=aspnetcore2x" rel="noopener noreferrer"&gt;here&lt;/a&gt; and a direct link to download it &lt;a href="https://go.microsoft.com/fwlink/?linkid=837808" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;This module takes care of starting and keeping an ASP.NET Core application running.&lt;/p&gt;

&lt;p&gt;Before we create the website in IIS we need the published version of the ASP.NET Core application. You can do that in the command line with &lt;code&gt;dotnet publish&lt;/code&gt; or, in full Visual Studio, right click on the project and select Publish, then click publish to folder.&lt;/p&gt;

&lt;p&gt;Create a new Website and point it to the ASP.NET Core project published folder, give it a different port number (for example 8080) and create an Application Pool for it.&lt;/p&gt;

&lt;p&gt;An application pool for an ASP.NET Core application is also unmanaged (No Managed Code). Although this might seem odd, it's because &lt;a href="https://weblog.west-wind.com/posts/2016/Jun/06/Publishing-and-Running-ASPNET-Core-Applications-with-IIS" rel="noopener noreferrer"&gt;IIS is actually just acting as a reverse proxy&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Before we're able to run the ASP.NET Project using IIS we need to changed the published folder's permissions so that the Application Pool user can access it. If you don't you'll get this moderately unhelpful error message: &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;HTTP Error 500.19 - Internal Server Error&lt;br&gt;
The requested page cannot be accessed because the related configuration data for the page is invalid.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdofj1luj5t586roetz0m.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fdofj1luj5t586roetz0m.png" alt="IIS permissions error"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If you look at the &lt;code&gt;Config Error&lt;/code&gt; section you'll see "Cannot read configuration file due to insufficient permissions", which pretty much says it all. &lt;/p&gt;

&lt;p&gt;Go to the published folder and add the application pool user to the list of users with permissions over that folder.&lt;/p&gt;

&lt;p&gt;Your ASP.NET Core application should now be available on the port you've selected when you created the website in IIS. However, if you try to call it from the Angular application you'll get this error "Failed to load ... No 'Access-Control-Allow-Origin' header is present on the requested resource...". Here's an example of how that would look like in the developer tools console tab:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft6zxi6erta3zu71p6amm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ft6zxi6erta3zu71p6amm.png" alt="Failed CORS request"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That's because even though both our our Angular and ASP.NET Core applications are on the same domain, they are in different ports, and that's enough to qualify the request as a Cross Origin Resource Sharing (CORS) request in all browsers except IE.&lt;/p&gt;

&lt;p&gt;We need to &lt;a href="https://docs.microsoft.com/en-us/aspnet/core/security/cors" rel="noopener noreferrer"&gt;enable CORS&lt;/a&gt; on the ASP.NET Core application. To do that we need to add the package &lt;code&gt;Microsoft.AspNetCore.Cors&lt;/code&gt; and in &lt;code&gt;ConfigureServices(IServiceCollection services...&lt;/code&gt; method in &lt;code&gt;Startup.cs&lt;/code&gt; add &lt;code&gt;services.AddCors()&lt;/code&gt;:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    //...
    services.AddCors();
    //...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And in the &lt;code&gt;Configure&lt;/code&gt; method we need to create a "policy" that says that we are expecting requests from &lt;code&gt;http://localhost&lt;/code&gt;. We should do that before the MVC middleware:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //...
    app.UseCors(builder =&amp;gt; builder.WithOrigins("http://localhost"));
    app.UseMvc();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;You should be good to go. Your Angular and ASP.NET Core should both be working now.&lt;/p&gt;

&lt;h2&gt;
  
  
  Platform Agnostic Development Setup
&lt;/h2&gt;

&lt;p&gt;Both Angular and ASP.NET Core applications provide ways to detect if they are running in development or production mode. That can be leveraged to create a setup that works both in Linux, Windows or Mac.&lt;/p&gt;

&lt;p&gt;The easiest way to run an Angular application is to use run &lt;code&gt;ng serve&lt;/code&gt;. That spins up a &lt;a href="https://webpack.js.org/configuration/dev-server/" rel="noopener noreferrer"&gt;webpack development server&lt;/a&gt; that serves the Angular application on port 4200 by default.&lt;/p&gt;

&lt;p&gt;This also has the advantage of having &lt;a href="https://webpack.js.org/concepts/hot-module-replacement/" rel="noopener noreferrer"&gt;hot module replacing&lt;/a&gt;, which means you can see your changes to the Angular application as soon as you make then without even having to refresh the browser.&lt;/p&gt;

&lt;p&gt;So ideally we want to run the Angular application this way.&lt;/p&gt;

&lt;p&gt;For the ASP.NET Core application we want to run it without having to publish it which you would have to if it is being served by IIS.&lt;/p&gt;

&lt;p&gt;This is the ideal development scenario, &lt;code&gt;ng serve&lt;/code&gt; for Angular and &lt;code&gt;dotnet run&lt;/code&gt; or running the ASP.NET Core from Visual Studio without having to publish it.&lt;/p&gt;

&lt;p&gt;In this ideal scenario when developing we could have the Angular application running on port 4200 (through &lt;code&gt;ng serve&lt;/code&gt;) and the ASP.NET Core application running on port 5000. When in production the Angular application would typically be served from port 80 and the ASP.NET Core application for port 8080 for example (or from a different server on port 80).&lt;/p&gt;

&lt;p&gt;On the ASP.NET Core side of things we'd have to configure CORS to accept requests from port 4200 when in development and from port 80 when in production. In Startup.cs that would look like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    //...        
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    //...
    if (env.IsDevelopment())
    {
        //...
        app.UseCors(builder =&amp;gt; builder.WithOrigins("http://localhost:4200"));
    }else 
    {
        app.UseCors(builder =&amp;gt; builder.WithOrigins("http://localhost"));
    }

    app.UseMvc();
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;That takes care of the ASP.NET Core application.&lt;/p&gt;

&lt;p&gt;For Angular we need to leverage the environemnt.ts and environemnt.prod.ts files. You can find then under a folder name &lt;code&gt;environemnts&lt;/code&gt; under the &lt;code&gt;src&lt;/code&gt; folder on an Angular project.&lt;/p&gt;

&lt;p&gt;What you put on environment.ts will be available when you run in development mode (the default) and the values in environment.prod.ts will be used when in production. To compile the Angular project with the environment set to production use the &lt;code&gt;--env=prod&lt;/code&gt; flag (e.g. &lt;code&gt;ng build --env=prod&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Here's a simple example of how the environment files could be configured to support our hypothetical scenario, environment.ts:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const environment = {
    production: false,
    apiBaseUrl: "http://localhost:4200/"
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;environment.prod.ts:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const environment = {
    production: true,
    apiBaseUrl: "http://localhost/"
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;In your Angular services, to get to the environment values you just need to import the environment (always environment and not environment.prod):&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../environments/environment';

@Injectable()
export class MyServiceService {

    constructor(private httpClient: HttpClient) { }

    getStuff(){
        return this.httpClient.get(`${environment.apiBaseUrl}/api/suff`);
    }  
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This approach would work even if you host on Nginx or IIS so probably the best option if you need/want to support having developers using different platforms of if you just want to compare performance between them.&lt;/p&gt;

</description>
      <category>angular</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>aspnet</category>
    </item>
    <item>
      <title>Things you wanted to know about storing passwords but were afraid to ask</title>
      <dc:creator>Rui Figueiredo</dc:creator>
      <pubDate>Mon, 04 Dec 2017 22:32:38 +0000</pubDate>
      <link>https://dev.to/ruidfigueiredo/things-you-wanted-to-know-about-storing-passwords-but-were-afraid-to-ask-47f</link>
      <guid>https://dev.to/ruidfigueiredo/things-you-wanted-to-know-about-storing-passwords-but-were-afraid-to-ask-47f</guid>
      <description>&lt;p&gt;Security breaches are &lt;a href="http://breachlevelindex.com/"&gt;very common&lt;/a&gt;. To make matters worse, when it comes to users' passwords it is frequent that no reasonable precautions were taken to ensure that they can't be easily extracted from the breached data.&lt;/p&gt;

&lt;p&gt;People tend to use the same password, or simple variations of it in multiple sites. This makes it easier for one to remember a password, but it also means that when that password is exposed, an attacker can potentially get access to the other websites where that password was used.&lt;/p&gt;

&lt;p&gt;The thing is, there's no reason for this to be so common nowadays. Even though the science around cryptography is fairly complicated, the algorithms are easy to use and are readily available.&lt;/p&gt;

&lt;p&gt;This blog post is an attempt at explaining what good qualities a stored password should have and which algorithms can be used to get there.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--6AS2HPcR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://www.blinkingcaret.com/wp-content/uploads/2017/11/encryptied-data.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--6AS2HPcR--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/http://www.blinkingcaret.com/wp-content/uploads/2017/11/encryptied-data.jpg" alt="Image of 0s and 1s suggesting encrypted data for storing passwords"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So what qualities should a stored password have? First, only the user should know it. There cannot be a way of getting to the password after it is stored. &lt;/p&gt;

&lt;p&gt;That rules out saving the password in clear text, but it also rules out encrypting it.&lt;/p&gt;

&lt;p&gt;This might sound like common sense, but unfortunately there's been examples of fairly prominent online business that would just email you the password in clear text if you use their "Forgot password functionality". &lt;/p&gt;

&lt;p&gt;The example I'm thinking of right now is Tesco, one of the biggest supermarket chains in the UK and Ireland. A few years ago, when pressed about it, they said that they were &lt;a href="https://www.theregister.co.uk/2012/07/31/tesco_website_insecurity/"&gt;encrypting the passwords&lt;/a&gt;. This is not a good idea since if there's a security breach and the cryptographic key that was used to encrypt the passwords were to be discovered, the attackers would have access to all of the users' passwords.&lt;/p&gt;

&lt;p&gt;So if encrypting the passwords is not a good idea, what alternative can we use?&lt;/p&gt;

&lt;h2&gt;
  
  
  Hashing
&lt;/h2&gt;

&lt;p&gt;Maybe we could hash the passwords. But first, what is hashing?&lt;/p&gt;

&lt;p&gt;The idea behind hashing is that you can take any input and produce an output that has a specific size and from which you cannot "extract" original input. &lt;/p&gt;

&lt;p&gt;For example here's the output of the &lt;a href="https://en.wikipedia.org/wiki/SHA-1"&gt;SHA1&lt;/a&gt; hashing algorithm in &lt;a href="https://en.wikipedia.org/wiki/Base64"&gt;base64&lt;/a&gt; for the string "hello world":&lt;/p&gt;

&lt;p&gt;22596363b3de40b06f981fb85d82312e8c0ed511&lt;/p&gt;

&lt;p&gt;And here's the SHA1 hash for "hello world!":&lt;/p&gt;

&lt;p&gt;f951b101989b2c3b7471710b4e78fc4dbdfa0ca6&lt;/p&gt;

&lt;p&gt;And here's the SHA1 hash for a video file with 700Mb:&lt;/p&gt;

&lt;p&gt;1b2803f08a8f2ba251a557cd61f1a38b07427011&lt;/p&gt;

&lt;p&gt;Two very similar inputs produce completely different hashes, and irrespectively of the size of the input the output always has the same size.&lt;/p&gt;

&lt;p&gt;Hashing algorithms are typically used for detecting duplicate data. Imagine you are storing video files and you want to determine if a certain video file has already been stored. &lt;/p&gt;

&lt;p&gt;If each time you need to store a new video file you first compute its hash, you can then compare the video file's hash with previously stored hashes. If there is already a hash that is the same as the video file you are trying to save that means it's a duplicate, if not, you can save the video file with the hash. The advantage of doing this is that it is much faster to compare two hashes than two video files.&lt;/p&gt;

&lt;p&gt;Another common use case for hashing is to detect if data has been corrupted while being transmitted.&lt;/p&gt;

&lt;p&gt;For example, if a file needs to be transmitted through a medium that is not very reliable, before the file is sent a hash of it is created. Then, the file is sent together with the hash. &lt;/p&gt;

&lt;p&gt;On the receiving end the hash is computed again and compared with the hash that was transmitted. If they don't match it means the file was corrupted.&lt;/p&gt;

&lt;p&gt;Some examples of hashing algorithms are &lt;a href="https://en.wikipedia.org/wiki/Secure_Hash_Algorithms"&gt;MD5, SHA1, SHA256 and SHA512&lt;/a&gt; just to name some common ones.&lt;/p&gt;

&lt;p&gt;The qualities that the output of these algorithms have seem like they are very appropriate for storing passwords. Given a password, compute it's hash and store that. &lt;/p&gt;

&lt;p&gt;When the user tries to login, compute the hash from the password the user entered in the login form. If that hash matches the stored one, then it's the right password.&lt;/p&gt;

&lt;p&gt;Unfortunately, there's a catch here. Hashing is supposed to be very fast. In its original use cases (e.g. duplicate detection, validating that data has not been changed/corrupted) it needs to be very fast. &lt;/p&gt;

&lt;p&gt;That makes it a bad match for storing passwords because if it's fast to compute that means many hashes can be generated in a short period of time. Which means that if you want to figure out what password was used to generate a particular hash, you can try many candidate passwords in a short period of time to see if any produces a hash that matches the one you are looking for.&lt;/p&gt;

&lt;p&gt;Because most passwords people pick are somewhat predictable (e.g. words that you can find on a dictionary or simple variations of them), if an attacker manages to get access to a password's hash, most of the time finding that password becomes an exercise of computing hashes of words in a dictionary until finding a match.&lt;/p&gt;

&lt;p&gt;A way to speed up the process of getting a password from a hash is to use data from previous breaches, namely the &lt;a href="https://en.wikipedia.org/wiki/List_of_the_most_common_passwords"&gt;most commonly used passwords&lt;/a&gt;. By pre-computing the most common passwords it is possible to just do a lookup search from the hash to the password. If an attacker manages to get access to a website's database where the hashes are stored, it is very likely that this process will reveal a significant number of passwords.&lt;/p&gt;

&lt;p&gt;This method of looking up passwords by using pre-computed password hashes is called a &lt;a href="https://en.wikipedia.org/wiki/Rainbow_table"&gt;rainbow table attack&lt;/a&gt;. You don't even need to generate the hashes yourself, there are pre-computed hashes readily available online for purchase. They are not too hard to find.&lt;/p&gt;

&lt;h2&gt;
  
  
  HMAC
&lt;/h2&gt;

&lt;p&gt;If we can't stop people from using the same passwords all the time is there something we can do to make hashing more secure?&lt;/p&gt;

&lt;p&gt;What if we just appended a random string to the passwords? &lt;/p&gt;

&lt;p&gt;We can store the random string with the hash of the password + random string combination. When the user tries to sign in, we append the random string with the password the user entered and recompute the hash. If they match the password is correct.&lt;/p&gt;

&lt;p&gt;For example, if the password is "cutecats", instead of computing the hash of "cutecats", we can compute the hash of "cutecatsm@O88q39!Q^x" and store &lt;code&gt;HASH("cutecatsm@O88q39!Q^x")&lt;/code&gt; and &lt;code&gt;m@O88q39!Q^x&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;It is very unlikely you'll find &lt;code&gt;cutecatsm@O88q39!Q^x&lt;/code&gt; in a rainbow table.&lt;/p&gt;

&lt;p&gt;An effective way to counteract a rainbow table attack is to generate a random string per password. If you consider the alternative of just having a random string for all passwords an attacker could still pre-compute all the hashes once and use them to try to get to the passwords. &lt;/p&gt;

&lt;p&gt;If there's a random string per password it means that the attacker can't reuse any previously computed hashes.&lt;/p&gt;

&lt;p&gt;The random string appended to the password is commonly know as &lt;a href="https://en.wikipedia.org/wiki/Salt_(cryptography)"&gt;salt&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Although we could just use an hashing algorithm to perform these operations, for example &lt;code&gt;SHA256(password + salt)&lt;/code&gt;, there are reasons for not doing it. Imagine that the password is "cutecats" and the salt is "1salt". Now imagine that the password is "cutecats1" and the salt is "salt". These two combinations will generate the same hash. This is suboptimal.&lt;/p&gt;

&lt;p&gt;There's another algorithm that combines two inputs and generates an output with the same properties of the previously mentioned hashing algorithms. It's named &lt;a href="https://en.wikipedia.org/wiki/Hash-based_message_authentication_code"&gt;HMAC&lt;/a&gt; which stands for Hash-based Message Authentication Code. Using HMAC, "cutecats", "1salt" and "cutecats1" and "salt" generate different outputs.&lt;/p&gt;

&lt;p&gt;Before we go into what HMAC is, lets talk about &lt;a href="https://en.wikipedia.org/wiki/Message_authentication_code"&gt;MAC&lt;/a&gt; (Message Authentication Code) and what it's used for. &lt;/p&gt;

&lt;p&gt;Imagine you want to communicate with someone over the internet and although you don't mind if someone is listening to your conversation, you want to make sure that the conversation is not tampered with (i.e. no one can send a message as one of the two people participating in the conversation). A hash of the message wouldn't do the trick here. A hash only guarantees that the message wasn't corrupted, if a bad actor has access to the message and can alter it, that means that he can compute a new hash for the altered message. To the receiver of the message it would look like everything was ok.&lt;/p&gt;

&lt;p&gt;A Message Authentication Code addresses this issue by using a secret that is known only by the parties that take place in the communication. Using Alice and Bob as an example, if Alice wants to send a message to Bob she'll compute &lt;code&gt;MAC(secret, messageToBob)&lt;/code&gt; and send that together with &lt;code&gt;messageToBob&lt;/code&gt;. Bob, when he receives the message will repeat the process and compare the MAC code he generated with the one he received from Alice. If they match Bob can be confident that not only wasn't the message altered, but it was sent by Alice, since she's the only other person who could've generated a valid MAC.&lt;/p&gt;

&lt;p&gt;In case you are wondering how Alice and Bob can agree on a secret even when there might be people listening to their communications have a look at &lt;a href="http://www.blinkingcaret.com/2017/01/18/brief-ish-explanation-of-how-https-works/"&gt;Brief(ish) explanation of how https works&lt;/a&gt;, where you'll find an example of the &lt;a href="https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange"&gt;Diffie–Hellman&lt;/a&gt; algorithm that is used exactly for this.&lt;/p&gt;

&lt;p&gt;That is MAC. What about &lt;a href="https://en.wikipedia.org/wiki/Hash-based_message_authentication_code"&gt;HMAC (Hash-based Message Authentication Code)&lt;/a&gt;? It's just an implementation of MAC that allows us pick from several different hashing algorithms to compute the MAC, for example there's HMAC-SHA256 where the hashing algorithm used is SHA256, of HMAC-SHA1 where the hashing algorithm is SHA-1, etc.&lt;/p&gt;

&lt;p&gt;How can we then use HMAC to store passwords? We could, for example, pick SHA256 and compute &lt;code&gt;HMAC-SHA256(password, salt)&lt;/code&gt; and store that together with the &lt;code&gt;salt&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Solved? Unfortunately, no.&lt;/p&gt;

&lt;p&gt;Although rainbow table attacks wouldn't work here, today's hardware allows us to generate these hashes so quickly that it becomes feasible to just use passwords from a list of commonly used password or even do a brute force attack, i.e. for example compute &lt;code&gt;HMAC-SHA256(testPassword, salt)&lt;/code&gt; where &lt;code&gt;testPassword&lt;/code&gt; is "a", then "aa", then "ab", up to all combinations of characters, numbers and symbols until a certain length.&lt;/p&gt;

&lt;p&gt;To give you an idea, a high end graphics card that you can go buy today, for example a NVIDIA GTX 1080, &lt;a href="(https://gist.github.com/epixoip/6ee29d5d626bd8dfe671a2d8f188b77b)"&gt;can do ~4450 million SHA256 hashes per second&lt;/a&gt;. It is possible to have several of these cards in a single computer, so that number can be made much much higher.&lt;/p&gt;

&lt;h2&gt;
  
  
  Key Derivation
&lt;/h2&gt;

&lt;p&gt;So if &lt;code&gt;HMAC&lt;/code&gt; does not work, then what?&lt;/p&gt;

&lt;p&gt;The idea of using a salt and a password is a good one, the only reason that it doesn't work is because computing HMAC is so fast that it is possible to guess the password in a reasonable amount of time. To do this the attacker would only need the password's hash and the salt (which would happen in the case of a breach) and good enough hardware that was capable of generating many hashes per second.&lt;/p&gt;

&lt;p&gt;Maybe there's a way to make the process more computationally expensive?&lt;/p&gt;

&lt;p&gt;What if we do &lt;code&gt;HMAC(password, salt)=hash1&lt;/code&gt; and then &lt;code&gt;HMAC(password, hash1)=hash2&lt;/code&gt; and repeat this a large number of times, for example 100.000. That would significantly slow down the process. Trying out passwords one by one, or a brute force approach be not be reasonable anymore.&lt;/p&gt;

&lt;p&gt;There are a few algorithms for doing just that, and they do a little more than just repeat &lt;code&gt;HMAC&lt;/code&gt;. They are called Key Derivation function algorithms.&lt;/p&gt;

&lt;p&gt;The idea behind key derivation is that given a key you generate one or more keys from that original key that have certain properties. For example, the &lt;a href="https://en.wikipedia.org/wiki/Advanced_Encryption_Standard"&gt;AES-256 encryption algorithm&lt;/a&gt; requires a key with 256 bits. &lt;/p&gt;

&lt;p&gt;It is not reasonable to ask a user to generate an exactly 256 bit key by hand. That key would be extremely hard to memorize.&lt;/p&gt;

&lt;p&gt;That's one of the uses of key derivation. It's a way of going from a key, for example the password the user thinks up, to another key that has a specific size.&lt;/p&gt;

&lt;p&gt;But apart from that these key derivation have the property of, with the right configuration, being very computationally expensive.&lt;/p&gt;

&lt;p&gt;For example &lt;a href="https://en.wikipedia.org/wiki/PBKDF2"&gt;PBKFD2 (Password-Based Key Derivation Function 2)&lt;/a&gt; can be configured to use a password, a salt, a particular &lt;code&gt;HMAC&lt;/code&gt; algorithm and the number of iterations the &lt;code&gt;HMAC&lt;/code&gt; should be applied. There is also &lt;a href="https://en.wikipedia.org/wiki/Bcrypt"&gt;bcrypt&lt;/a&gt; and &lt;a href="https://en.wikipedia.org/wiki/Scrypt"&gt;scrypt&lt;/a&gt; that can also be used in a similar fashion.&lt;/p&gt;

&lt;p&gt;As an example here's how using PBKDF2 in dotnet core would look like, with a 128 bit salt, 100.000 iterations and an output key size of 128 bits (16 bytes).&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const int saltSize = 128 / 8;
const int outputKeySize = 128 / 8;
const int numberOfIterations = 100000;

var password = "cutecats";

using (var rng = RandomNumberGenerator.Create())
{
    var salt = new byte[saltSize];
    rng.GetBytes(salt);

    var derivedKey = KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA256, numberOfIterations, outputKeySize);

    Console.WriteLine($"The salt in base64: {Convert.ToBase64String(salt)}");
    Console.WriteLine($"The 'hash/derived key' in base64: {Convert.ToBase64String(derivedKey)}");
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;To run this example you need to install the &lt;a href="https://www.nuget.org/packages/Microsoft.AspNetCore.Cryptography.KeyDerivation/2.0.0"&gt;&lt;code&gt;Microsoft.AspNetCore.Cryptography.KeyDerivation&lt;/code&gt; nuget package&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you are wondering why I picked a 128 bit salt size or a 128 bit output key I don't have a good answer for that, but a good rule of thumb is that it should be less than what the hashing algorithm produces, for example we used SHA256 which produces a 256 bit output or 32 bytes.&lt;/p&gt;

&lt;p&gt;By the way, "cutecats" is a horrible password, you should use a password manager like &lt;a href="https://www.lastpass.com/"&gt;LastPass&lt;/a&gt;, &lt;a href="https://1password.com/"&gt;1Password&lt;/a&gt; or similar to generate passwords for you. That's because even if a password is stored correctly, if it's something like "cutecats" or for example a word you'd find in a dictionary then, even if it takes 1 second to try each password, an attacker might find it just by guessing and having a little patience.&lt;/p&gt;

&lt;p&gt;So that's it, I hope I've helped explain why we should use passwords with a reasonable length, combinations of several numbers, symbols and characters and why they should not be stored in a way that can be easily "reversed" back to the the original password.&lt;/p&gt;

</description>
      <category>security</category>
      <category>webdev</category>
    </item>
    <item>
      <title>The Road to Modern JavaScript</title>
      <dc:creator>Rui Figueiredo</dc:creator>
      <pubDate>Wed, 16 Aug 2017 12:01:48 +0000</pubDate>
      <link>https://dev.to/ruidfigueiredo/the-road-to-modern-javascript</link>
      <guid>https://dev.to/ruidfigueiredo/the-road-to-modern-javascript</guid>
      <description>&lt;p&gt;When I recently decided to learn &lt;a href="https://webpack.github.io/" rel="noopener noreferrer"&gt;webpack&lt;/a&gt; I realized just how many new things were added to the JavaScript ecosystem in the last couple of years. Things that you need to know if you want to feel comfortable with all the new frameworks and tools like Angular, React, Gulp, Webpack, etc.&lt;/p&gt;

&lt;p&gt;The goal for this blog post is to walk you through the major developments in the language that lead to what is considered modern JavaScript development. It also has examples that are illustrative of how modern tools and features work.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fov5s2ymtwhrbmp6b9pnp.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fov5s2ymtwhrbmp6b9pnp.jpg" alt="Road to Modern Javascript symbolized by a curvy road"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;JavaScript development has changed immensely in the last two decades. When JavaScript was first introduced in 1995 one of the major goals was that it should be easy for beginners. It had requirements like being embeddable directly in HTML. It was supposed to be the "glue" between Java applets.&lt;/p&gt;

&lt;p&gt;We all know that it evolved in a very different direction. All of that was motivated by JavaScript taking an ever more prominent role in web development, and that clashed with some of those earlier goals. &lt;/p&gt;

&lt;h2&gt;
  
  
  Scope and naming
&lt;/h2&gt;

&lt;p&gt;In the 90s it was common to find this in a &lt;code&gt;.html&lt;/code&gt; file:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;input type="button" value="Save" onclick="save();"/&amp;gt;
&amp;lt;script&amp;gt;
  function save() {
    //...
  }
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Script tags with large chunks of code intermingled with HTML, plus inline event handlers. All of this quickly made the code hard to read and maintain.&lt;/p&gt;

&lt;p&gt;Another thing that caused problems was it was really easy to get into a situation where you would accidentally redefine a function because you named it the same way as a previous one.&lt;/p&gt;

&lt;p&gt;For example if there were two &lt;code&gt;.js&lt;/code&gt; files that define a &lt;code&gt;save&lt;/code&gt; function, the second one would override the first. This is perfectly valid in JavaScript, so there would be no errors or warning messages. &lt;/p&gt;

&lt;p&gt;The solution for this problem was to try to mimic the &lt;code&gt;namespace&lt;/code&gt; functionality that exists in other programming languages. We started doing things like:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var MyNamespace = (function() {
  function save(){
    //...
  }

  return {
    save: save
  };
})()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And then instead of just calling &lt;code&gt;save()&lt;/code&gt; we'd call &lt;code&gt;MyNamespace.save()&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;This takes advantage of the fact that in JavaScript new scopes are only created by functions. This became so popular that IIFE became a common "word" (iffy) between JavaScript developers. It means &lt;a href="https://en.wikipedia.org/wiki/Immediately-invoked_function_expression" rel="noopener noreferrer"&gt;Immediately-invoked function expression&lt;/a&gt;. A really simple example is:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;(function() { 
    //whatever variables and functions you declare here won't be "visible" outside the function
})()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It was now possible to have more complex applications, and to reuse parts of the code because the naming of functions was not an issue. &lt;/p&gt;

&lt;p&gt;We also started making our JavaScript "unobtrusive", meaning that we didn't mix it with HMTL, and we &lt;a href="https://developer.mozilla.org/ms/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript" rel="noopener noreferrer"&gt;made more object-oriented&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Too many files to load
&lt;/h2&gt;

&lt;p&gt;As these new practices made writing more complex JavaScript more manageable we started to get into situations where we had a lot of it. That JavaScript had to be loaded to the browser, and as good practices dictate, it had to be separated over several files with meaningful names.&lt;/p&gt;

&lt;p&gt;Well, there's a limit on how many concurrent GET requests a browser can do, and they are &lt;a href="http://www.browserscope.org/?category=network" rel="noopener noreferrer"&gt;not many&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;We've started using tools to &lt;em&gt;bundle&lt;/em&gt; all our JavaScript. Bundling means that all the JavaScript code is concatenated into a single file. My first experience with &lt;a href="https://docs.microsoft.com/en-us/aspnet/mvc/overview/performance/bundling-and-minification" rel="noopener noreferrer"&gt;bundling was with ASP.NET&lt;/a&gt;. With ASP.NET it's actually .Net code that bundles the JavaScript files.&lt;/p&gt;

&lt;p&gt;This only worked in .Net so alternatives were required in order for this technique to be used with other technologies.&lt;/p&gt;

&lt;p&gt;At some point in time someone decided that it would be a good idea to have JavaScript run outside of the browser. &lt;a href="https://nodejs.org" rel="noopener noreferrer"&gt;Node.js&lt;/a&gt; was created. Node leverages the open-source &lt;a href="https://developers.google.com/v8/" rel="noopener noreferrer"&gt;V8 JavaScript engine&lt;/a&gt; created by Google. What's so appealing about Node is that you can create &lt;a href="https://nodejs.org/api/addons.html" rel="noopener noreferrer"&gt;C++ Addons&lt;/a&gt; that can be invoked through JavaScript running in Node, which basically means you don't have any of the limitations that you have running inside a browser (it is possible to access the filesystem, etc).&lt;/p&gt;

&lt;p&gt;A lot of tools started showing up that were created using Node. Specifically for doing &lt;em&gt;bundling&lt;/em&gt; the most popular ones were &lt;a href="https://gruntjs.com/" rel="noopener noreferrer"&gt;Grunt&lt;/a&gt; and &lt;a href="http://gulpjs.com/" rel="noopener noreferrer"&gt;Gulp&lt;/a&gt;. &lt;/p&gt;

&lt;p&gt;In reality Grunt and Gulp are task runners, meaning that they run tasks, and bundling is just one of those possible tasks. Another example that also goes hand in hand with bundling is minification (or "uglification" outside the .Net world). It's the process of making the JavaScript as small as possible by renaming the variable and function names to single letters, and also removing all whitespace and comments.&lt;/p&gt;

&lt;p&gt;Here's an example of how a gulp configuration file that creates a bundle looks like:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var gulp = require('gulp');
var concat = require('gulp-concat');

gulp.task('default', function(){
  gulp.src(['player.js', 'game.js'])
      .pipe(concat('bundle.js'))
      .pipe(gulp.dest("."));
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;When you run this task with gulp it creates a bundle with &lt;em&gt;player.js&lt;/em&gt; and &lt;em&gt;game.js&lt;/em&gt; (in that order) named &lt;em&gt;bundle.js&lt;/em&gt;. If you are interested in learning Gulp I recommend: &lt;a href="https://scotch.io/tutorials/automate-your-tasks-easily-with-gulp-js" rel="noopener noreferrer"&gt;Automate Your Tasks Easily with Gulp.js&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Modules
&lt;/h2&gt;

&lt;p&gt;Even though bundling solves the issue of the limited number of GET requests that browsers can perform simultaneously, it requires that the JavaScript files are added to the bundle in a particular order if they have dependencies on each other. It's also easy to end up in a situation where there is JavaScript code that never gets executed inside the bundle. Over time bundles become hard to manage.&lt;/p&gt;

&lt;p&gt;JavaScript modules solve this problem. The idea behind using modules is that it is possible to have dependencies stated explicitly. For example imagine you are creating a JavaScript game and you have a &lt;code&gt;game.js&lt;/code&gt; file. That file uses code from another file named &lt;code&gt;player.js&lt;/code&gt;. We can explicitly say that &lt;code&gt;game.js&lt;/code&gt; depends on &lt;code&gt;player.js&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;There are a few different module "formats". The most common ones are &lt;a href="http://wiki.commonjs.org/wiki/Modules/1.1.1" rel="noopener noreferrer"&gt;commonjs&lt;/a&gt; which is the one used in Node.js, there's also Asynchronous Module Definition (AMD)](&lt;a href="https://github.com/amdjs/amdjs-api/wiki/AMD" rel="noopener noreferrer"&gt;https://github.com/amdjs/amdjs-api/wiki/AMD&lt;/a&gt;), and &lt;a href="http://exploringjs.com/es6/ch_modules.html#sec_basics-of-es6-modules" rel="noopener noreferrer"&gt;ES6 modules&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Let's imagine a simple scenario with &lt;code&gt;game.js&lt;/code&gt; and &lt;code&gt;player.js&lt;/code&gt; and describe them with these three module formats. Game has a &lt;code&gt;start&lt;/code&gt; method that calls Player's &lt;code&gt;getName&lt;/code&gt; method.&lt;/p&gt;

&lt;p&gt;In all these module formats each JavaScript file is a module, so in this case we would have two modules, game and player.&lt;/p&gt;

&lt;h3&gt;
  
  
  CommonJS
&lt;/h3&gt;

&lt;p&gt;With &lt;em&gt;commonjs&lt;/em&gt; the &lt;em&gt;player.js&lt;/em&gt; file would look like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var privateVar; //if this is not "exported" it won't be available outside player.js

function getName() {
  //...
}

module.exports.getName = getName;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And &lt;em&gt;game.js&lt;/em&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var player = require('./player.js');

function start(){
  var playerName = player.getName();
  //...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;It's through &lt;code&gt;module.exports&lt;/code&gt; that we expose what's inside the module to whomever requests it. In this case the only thing that was "exported" was the &lt;code&gt;getName&lt;/code&gt; function.&lt;/p&gt;

&lt;p&gt;In &lt;em&gt;commonjs&lt;/em&gt; to get the exported parts of another module we use the &lt;em&gt;require&lt;/em&gt; function. You might have notice the &lt;code&gt;./&lt;/code&gt; in the require statement in &lt;code&gt;game.js&lt;/code&gt;. In this case it would mean that both files are in the same folder, however the way a module's file is found can become complicated. I'd recommend reading &lt;a href="https://nodejs.org/api/modules.html#modules_all_together" rel="noopener noreferrer"&gt;Node.js documentation on how to get to the exact filename when require is used&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Asynchronous Module Definition
&lt;/h3&gt;

&lt;p&gt;The AMD syntax is a little bit different, it consists in using a &lt;em&gt;define&lt;/em&gt; function where a module's dependencies are listed in an array, and then supplying a function where each of the arguments will be a dependency in the order they are listed in the array.&lt;/p&gt;

&lt;p&gt;With AMD the &lt;em&gt;player.js&lt;/em&gt; would look like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;define([], function(){
  var privateVar; //not accessible outside the module

  function getName() {
    //...
  }
  return {
    getName: getName
  };
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And &lt;em&gt;game.js&lt;/em&gt;:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;define(['./player'], function(player) {
  function start(){
    var playerName = player.getName();
    //...
  }
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here's a good resource to learn more about &lt;a href="http://requirejs.org/docs/whyamd.html" rel="noopener noreferrer"&gt;AMD&lt;/a&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  ES6 Modules
&lt;/h3&gt;

&lt;p&gt;The &lt;a href="https://github.com/lukehoban/es6features/blob/master/README.md" rel="noopener noreferrer"&gt;ECMAScript 6&lt;/a&gt; standard which is the new specification for JavaScript (the new version of JavaScript if you will) introduced modules.&lt;/p&gt;

&lt;p&gt;With ES6 modules the &lt;em&gt;player.js&lt;/em&gt; file would look like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var privateVar;

function getName(){
  //...
}

export { getName };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;And &lt;em&gt;game.js&lt;/em&gt; would look like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import * as player from './player.js'

function start() {
  var playerName = player.getName();
  //...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;
&lt;h2&gt;
  
  
  Module Loaders
&lt;/h2&gt;

&lt;p&gt;If you were to just load &lt;em&gt;game.js&lt;/em&gt; or &lt;em&gt;player.js&lt;/em&gt; as they are defined in the examples above they wouldn't work (you would get errors stating that require/define/import are not defined).&lt;/p&gt;

&lt;p&gt;For them to work they need to be loaded through a module loader. A module loader is a JavaScript library that runs in the browser and which is capable of interpreting one (or several) module formats.&lt;/p&gt;

&lt;p&gt;There are several popular module loaders. The most popular ones is probably &lt;a href="https://github.com/systemjs/systemjs" rel="noopener noreferrer"&gt;SystemJS&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;SystemJS supports &lt;a href="https://github.com/systemjs/systemjs/blob/master/docs/module-formats.md" rel="noopener noreferrer"&gt;several module formats&lt;/a&gt;. You can specify which one you are using through configuration options.&lt;/p&gt;

&lt;p&gt;To use them you need to specify which module is the "entry point". You can think of the entry point as the main module, in our example that would be game.&lt;/p&gt;

&lt;p&gt;Here's how we could use &lt;em&gt;SystemJS&lt;/em&gt; to load the &lt;em&gt;CommonJS&lt;/em&gt; example above:&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script src="system.js"&amp;gt;&amp;lt;/script&amp;gt;
&amp;lt;script&amp;gt;
  SystemJS.config({
    meta: {
      format: "cjs" //use commonjs module format
    }
  });

  SystemJS.import('game.js');
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;When you do this &lt;em&gt;SystemJS&lt;/em&gt; will load &lt;em&gt;game.js&lt;/em&gt; inspect it and realize that it needs to fetch &lt;em&gt;player.js&lt;/em&gt;. It will then load the JavaScript from &lt;em&gt;player.js&lt;/em&gt; and then &lt;em&gt;game.js&lt;/em&gt; in the browser.&lt;/p&gt;

&lt;p&gt;You can find a good introduction to JavaScript modules and module loaders in this pluralsight course: &lt;a href="https://www.pluralsight.com/courses/javascript-module-fundamentals" rel="noopener noreferrer"&gt;JavaScript Module Fundamentals&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  JavaScript build process
&lt;/h2&gt;

&lt;p&gt;Although client-side module loaders enable the use of modules, if there are a lot of them, we will again get into the issue of browsers having a limited number of GET request that can be performed simultaneously.&lt;/p&gt;

&lt;p&gt;There's no reason not to do the module's loader "work" beforehand as a build step, and as a result produce a bundle. An example of a tool that does this is &lt;a href="http://browserify.org/" rel="noopener noreferrer"&gt;browserify&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Browserify gets its name from the idea of enabling the use of modules in the browser the same way they are used in Node.js. It's a "browserification" of Node.js modules (which use the commonjs format).&lt;/p&gt;

&lt;p&gt;To create a bundle with browserify we just need to specify what is the main module. Browserify will figure out what other modules that module depends on, and which other modules those modules depend on and so on.&lt;/p&gt;

&lt;p&gt;In our example we could create a bundle simply by doing this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;$ browserify game.js --outfile bundle.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;We then just need to include our bundle in our web page and we are good to go.&lt;/p&gt;

&lt;h2&gt;
  
  
  Transpilation
&lt;/h2&gt;

&lt;p&gt;One thing that JavaScript is known for is being lax with regards to types. In JavaScript you don't need to specify which type a variable is, what is the return type of a function or what are the types of its parameters.&lt;/p&gt;

&lt;p&gt;This made creating tools to aid the developers difficult. Some IDE's would provide some intellisense information (e.g. &lt;a href="https://madskristensen.net/post/improved-javascript-intellisense-in-visual-studio" rel="noopener noreferrer"&gt;Visual Studio&lt;/a&gt;) but the experience was never perfect.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://www.typescriptlang.org/" rel="noopener noreferrer"&gt;TypeScript&lt;/a&gt; is a language that is a superset of JavaScript and that allows for type information to be added.&lt;/p&gt;

&lt;p&gt;To use TypeScript you need to compile it to JavaScript. This process of compiling a language to another language is what transpilation is.&lt;/p&gt;

&lt;p&gt;Here's how a function definition with TypeScript looks like:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function getPlayer(id: number) : IPlayer {
  //...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Here we are saying that the &lt;code&gt;getPlayer&lt;/code&gt; function expects a parameter named &lt;code&gt;id&lt;/code&gt; that is a number and returns an &lt;code&gt;IPlayer&lt;/code&gt;. In TypeScript you can define interfaces, for example &lt;code&gt;IPlayer&lt;/code&gt; could be:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface IPlayer {
  id: number;
  name: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;When you compile this TypeScript code, the interface has no effect on the output, but during development type you get intellisense when you have an instance of &lt;code&gt;IPlayer&lt;/code&gt;. Also, you will also get an error if you pass for example a string as an argument to &lt;code&gt;getPlayer&lt;/code&gt; (e.g. &lt;code&gt;getPlayer("abc")&lt;/code&gt;), you will also get intellisense in regards to the function parameters and their type, in this case you'd get intellisense for &lt;code&gt;id&lt;/code&gt; of type &lt;code&gt;number&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;TypeScript was by no means the first language to come by that transpiles to JavaScript. The first that became really popular for a while was &lt;a href="http://coffeescript.org/" rel="noopener noreferrer"&gt;CoffeeScript&lt;/a&gt;, however (at least from my perception) it seems to be fading away.&lt;/p&gt;

&lt;p&gt;Because it enables a better development experience, TypeScript is probably responsible for enabling ever more complex projects to be done in JavaScript. Also, because having build steps for JavaScript is so common now, having one more for transpilation adds very little friction.&lt;/p&gt;

&lt;p&gt;Although TypeScript is probably the most popular language that transpiles to JavaScript, it should be mentioned that just writing ES6 code, the new version of JavaScript, is also very popular. Since not all features from ES6 are supported by current browsers, ES6 code is also transpilled to the current version of JavaScript. The tool that enables this is &lt;a href="https://babeljs.io/" rel="noopener noreferrer"&gt;Babel&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;
  
  
  Build tools on steroids
&lt;/h2&gt;

&lt;p&gt;Imagine using JavaScript to load images or CSS instead of doing it in HTML. That's what build tools like &lt;a href="https://webpack.github.io/" rel="noopener noreferrer"&gt;Webpack&lt;/a&gt; enable.&lt;/p&gt;

&lt;p&gt;If this is the first time you've heard about this you might be thinking about how this can be a good idea. It turns out that it enables scenarios that solve some common problems in web development. The same way we now have modules in JavaScript, we can apply the same solution to CSS where if we import CSS through JavaScript, that CSS might be &lt;a href="https://vimeo.com/116209150" rel="noopener noreferrer"&gt;scoped so that it does not interact with any other CSS in the page&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Images in CSS can automatically be &lt;a href="https://github.com/webpack-contrib/url-loader" rel="noopener noreferrer"&gt;converted to base64 and embedded inside the CSS itself&lt;/a&gt; if they are below a certain threshold size.&lt;/p&gt;

&lt;p&gt;These are just some examples of what Webpack enables. If you spend some time becoming familiar with it you'll recognize that the new version of Angular relies heavily on this type of functionality.&lt;/p&gt;

&lt;h2&gt;
  
  
  Conclusion
&lt;/h2&gt;

&lt;p&gt;In this post I tried to describe how I perceived JavaScript to evolve into what it is today. At the beginning JavaScript was a simple language, it sill is, but it didn't had this buzzing ecosystem around it. Most of that ecosystem was enabled by addressing problems that were a consequence of how JavaScript was being used. With the amount of shareable work that was done in Node.js and with ways to use it in a similar fashion in the browser (Browserify) the JavaScript ecosystem grew immensely. It continues to evolve with tools like Webpack that facilitate scenarios and practices that enable ever more complexity in a manageable way.&lt;/p&gt;

</description>
      <category>javascript</category>
    </item>
    <item>
      <title>Rethinking email confirmation</title>
      <dc:creator>Rui Figueiredo</dc:creator>
      <pubDate>Tue, 08 Aug 2017 22:27:09 +0000</pubDate>
      <link>https://dev.to/ruidfigueiredo/rethinking-email-confirmation</link>
      <guid>https://dev.to/ruidfigueiredo/rethinking-email-confirmation</guid>
      <description>&lt;p&gt;We are very accustomed to how user registration works online. Enter your email, possibly pick a username, enter password, re-enter the password, get a confirmation email, click on a link in that email and voilÃ , account created.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fuh9t4k7ngpuvjst8x4t2.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fuh9t4k7ngpuvjst8x4t2.jpg" alt="Image of an envelope with a tick"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;However, there a are a few things that can go wrong. &lt;/p&gt;

&lt;p&gt;Imagine this scenario. You want to create a new account with an hypothetical website named TheWebsite. You go through all the normal process but you mistype your email. Instead of &lt;a href="mailto:john.smith@email.com"&gt;john.smith@email.com&lt;/a&gt; you type &lt;a href="mailto:jon.smith@email.com"&gt;jon.smith@email.com&lt;/a&gt;. But not all is bad, you typed your username correctly: johnsmith.&lt;/p&gt;

&lt;p&gt;You wait for the confirmation email, but it doesn't arrive. It's 6pm, time to go home. You'll check it tomorrow, surely it will have arrived by then.&lt;/p&gt;

&lt;p&gt;Tomorrow comes, and you forget that you didn't confirm your email, so you try to login, johnsmith + password. And it works, happy days.&lt;/p&gt;

&lt;p&gt;Years pass, and you've been using TheWebsite happily. All is well until one day try to log in and you get an invalid login error. You try again, and again you get an error.&lt;/p&gt;

&lt;p&gt;This can't be right you think. I always use johnsmith and the same password. You click the reset password link, but no reset email ever arrives.&lt;/p&gt;

&lt;p&gt;This is a tragedy, all those pictures, and other stuff you've uploaded to TheWebsite. You can't access them anymore.&lt;/p&gt;

&lt;p&gt;What happened?&lt;/p&gt;

&lt;p&gt;Well, turns out that the person that actually owned the &lt;a href="mailto:jon.smith@email.com"&gt;jon.smith@email.com&lt;/a&gt; was a kid that was curious and clicked the email from TheService asking him to verify his email address.&lt;/p&gt;

&lt;p&gt;He himself forgot about this until a couple of years later when he heard about TheWebsite from some friends, and decided to try it. He tried to create an account and got an "account already exists" error. He used the password reset functionality and that's that. He now owns the original John Smith's account.&lt;/p&gt;

&lt;p&gt;Although this story might seem convoluted it does happen. Brock Allen when talking about &lt;a href="https://vimeo.com/172009501" rel="noopener noreferrer"&gt;ASP.NET Identity Core in NDC&lt;/a&gt; described a situation where this had happened to someone from his family.&lt;/p&gt;

&lt;p&gt;So what can be done?&lt;/p&gt;

&lt;p&gt;A possible solution would be to ask for the password again when clicking the email confirmation link. This way Jon Smith wouldn't have been able to confirm John Smith's email, because he wouldn't know the password.&lt;/p&gt;

&lt;p&gt;This introduces a new problem though. What about if between choosing a password an receiving the confirmation email you forget the password?&lt;/p&gt;

&lt;p&gt;Well, then bye bye ability to create an account with that email. And goodbye cool username you managed to pick, won't be able to use those again.&lt;/p&gt;

&lt;p&gt;Is there no hope?&lt;/p&gt;

&lt;p&gt;There is. Here's a radical idea: don't let the user pick anything until s/he confirms the email address.&lt;/p&gt;

&lt;p&gt;The process would be:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Click Sign Up&lt;/li&gt;
&lt;li&gt;Enter email&lt;/li&gt;
&lt;li&gt;Tell user to check email and click on the email confirmation link&lt;/li&gt;
&lt;li&gt;User clicks on email confirmation link and is taken to a page where he enters

&lt;ul&gt;
&lt;li&gt;username (if required, some websites only require an email) &lt;/li&gt;
&lt;li&gt;password&lt;/li&gt;
&lt;li&gt;retype password&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;Done&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;It's like saying I'll only talk to you when you confirm you own that email address. After that you can tell me what you want.&lt;/p&gt;

&lt;h2&gt;
  
  
  Trying to create an actual implementation
&lt;/h2&gt;

&lt;p&gt;Last week I wrote a &lt;a href="http://www.blinkingcaret.com/2016/11/30/asp-net-identity-core-from-scratch/" rel="noopener noreferrer"&gt;step by step guide on how to create a web application from scratch that is able to deal with user registration using email confirmation&lt;/a&gt;.  &lt;/p&gt;

&lt;p&gt;It was while researching ASP.NET Identity Core that I saw that &lt;a href="https://vimeo.com/172009501" rel="noopener noreferrer"&gt;NDC video with Brock Allen&lt;/a&gt; and learned about this problem.&lt;/p&gt;

&lt;p&gt;I decided to try to implement this approach using ASP.NET Identity, but unfortunately couldn't get to a reliable implementation.&lt;/p&gt;

&lt;p&gt;A scenario where the user picks an invalid password or a username that is already taken will leave the account for the user's email in limbo.&lt;/p&gt;

&lt;p&gt;Here's a snippet that demonstrates the problem when using ASP.NET Identity:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;[HttpPost]
public async Task&amp;lt;IActionResult&amp;gt; VerifyEmail(string id, string token, string username, string password, string repassword)
{
    var user = await _userManager.FindByIdAsync(id);

    var confirmEmailResult = await _userManager.ConfirmEmailAsync(user, token);
    if (!confirmEmailResult.Succeeded)
        throw new InvalidOperationException("Invalid token");      

    var addPasswordResult = await _userManager.AddPasswordAsync(user, password);
    if (!addPasswordResult.Succeeded)
    {
        addPasswordResult.Errors.ToList().ForEach(error =&amp;gt; ModelState.AddModelError(string.Empty, error.Description));
        return View(); //goes back to the form where the user chooses the username and password
    } 
    //...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If the user mistypes the passwords the email gets confirmed but the user has no password set (it is possible to create users without password in ASP.NET Identity). The token for confirming the email cannot be used again, so the user won't ever be able to set the password.&lt;/p&gt;

&lt;p&gt;One could think that we should only confirm the email token after setting the user's password, unfortunately that does not work because the token becomes invalid (won't match the user) if you change any of the user's properties.&lt;/p&gt;

&lt;p&gt;Also, we can't validate the email and then redirect the user to another page to pick a username and password. That other page could be abused by another party to take over the account simply by navigating to it before the user did.&lt;/p&gt;

&lt;p&gt;So it seems there's no reliable way of doing this with ASP.NET Identity, at least without creating custom email confirmation tokens that are still valid if we set the user's password.&lt;/p&gt;

&lt;p&gt;The idea is still valid though, however it's hard not to feel that we are fighting the framework while trying to do it.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>security</category>
    </item>
    <item>
      <title>Brief(ish) explanation of how https works</title>
      <dc:creator>Rui Figueiredo</dc:creator>
      <pubDate>Mon, 03 Jul 2017 11:22:24 +0000</pubDate>
      <link>https://dev.to/ruidfigueiredo/briefish-explanation-of-how-https-works</link>
      <guid>https://dev.to/ruidfigueiredo/briefish-explanation-of-how-https-works</guid>
      <description>&lt;p&gt;When learning about how to use &lt;a href="https://www.openssl.org/" rel="noopener noreferrer"&gt;OpenSSL&lt;/a&gt; to create self-signed certs, it became clear to me that most of the information available online assumes you know what certificates are, and how they fit in HTTPS.&lt;/p&gt;

&lt;p&gt;I decided to have a go at explaining HTTPS by explaining how communications are made secure, namely how Diffie-Hellman key exchange and digital certificates work. Here's my take on it.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F9y0l15qkptogoo5zqn52.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2F9y0l15qkptogoo5zqn52.jpg" alt="https"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;HTTPS allows us to communicate securely over an insecure channel (for example over an open wifi network in an airport) where it is easy for someone to &lt;a href="https://wiki.wireshark.org/CaptureSetup/WLAN" rel="noopener noreferrer"&gt;listen to all network traffic&lt;/a&gt;. The communications with HTTPS are secure because they are encrypted.&lt;/p&gt;

&lt;p&gt;The communication is encrypted using &lt;a href="https://en.wikipedia.org/wiki/Symmetric-key_algorithm" rel="noopener noreferrer"&gt;symmetric key encryption&lt;/a&gt;. This particular type of encryption requires that both the sender and receiver have the same key (i.e. the same key is used to encrypt and decrypt the data).&lt;/p&gt;

&lt;p&gt;But if the sender and the receiver need to send the key to each other through the insecure channel, doesn't this make this whole exercise pointless? &lt;/p&gt;

&lt;p&gt;This can only work if the sender and receiver have a way of sending a secret key to each other even with someone listening to the communication (and without that someone being able to figure out what the secret key is).&lt;/p&gt;

&lt;p&gt;This is where the &lt;a href="https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange" rel="noopener noreferrer"&gt;Diffie Hellman key exchange&lt;/a&gt; comes into play. &lt;/p&gt;

&lt;h2&gt;
  
  
  Diffie-Hellman
&lt;/h2&gt;

&lt;p&gt;Diffie-Hellman allows two parties to create a shared secret key without revealing it, while doing it "in the open", i.e. even if someone has access to all the information that the two parties exchange, they still won't be able to discover what the secret key is.&lt;/p&gt;

&lt;p&gt;It sounds like magic, right? No, it's just math.&lt;/p&gt;

&lt;p&gt;Here's a simple example of how it works. First two numbers are picked, they are usually called &lt;em&gt;p&lt;/em&gt; and &lt;em&gt;g&lt;/em&gt;. &lt;em&gt;p&lt;/em&gt; is short for prime, &lt;em&gt;g&lt;/em&gt; is short for generator. &lt;/p&gt;

&lt;p&gt;A &lt;a href="https://en.wikipedia.org/wiki/Prime_number" rel="noopener noreferrer"&gt;prime is a natural number&lt;/a&gt; greater than 1 that has no divisors other than 1 and itself.&lt;/p&gt;

&lt;p&gt;A generator &lt;em&gt;g&lt;/em&gt; for prime number &lt;em&gt;p&lt;/em&gt; is a number such that g^x mod p for x between 1 and p-1 will "generate" all the numbers from 1 to p-1.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;mod&lt;/em&gt; (short for modulo) is a function that returns the remainder of an exact division, for example 5 mod 3 is 2, because the exact division of 5 by 3 is 1 and the remainder of that is 2 (3 * 1 + 2 = 5).&lt;/p&gt;

&lt;p&gt;Now that we know what &lt;em&gt;mod&lt;/em&gt; is, here's an example of a generator for a prime. 3 is a generator for 7 because: &lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;- 3^1 mod 7 = 3
- 3^2 mod 7 = 2
- 3^3 mod 7 = 6
- 3^4 mod 7 = 4
- 3^5 mod 7 = 5
- 3^6 mod 7 = 1
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;If we order the results we get: 1, 2, 3, 4, 5, 6, we can see that they are all the numbers from 1 to p-1, which makes &lt;em&gt;g&lt;/em&gt; = 3 a generator for &lt;em&gt;p&lt;/em&gt; = 7.&lt;/p&gt;

&lt;p&gt;We know have all the pieces to perform Diffie-Hellman "by hand". &lt;/p&gt;

&lt;p&gt;As an example, imagine Alice and Bob want to write letters to each other. Unfortunately someone is reading their correspondence, so they decide to use Diffie-Hellman to be able to communicate secretly.&lt;/p&gt;

&lt;p&gt;Alice picks &lt;em&gt;g&lt;/em&gt; and &lt;em&gt;p&lt;/em&gt;, for example g = 3, and p = 7 and sends a letter with them to Bob.&lt;br&gt;
Alice also picks a secret number less than &lt;em&gt;p&lt;/em&gt;, for example 2.&lt;br&gt;
Once Bob receives &lt;em&gt;p&lt;/em&gt; and &lt;em&gt;g&lt;/em&gt;, he picks a secret number less than &lt;em&gt;p&lt;/em&gt;, for example 5.&lt;/p&gt;

&lt;p&gt;Bob then computes this: g^secretBob mod p, in this case 3^5 mod 7 = 5. Bob sends this number to Alice, let's call this number &lt;em&gt;numberBobSent&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;At the same time Alice computes g^secretAlice mod p, in this case 3^2 mod 7 = 2 and sends it to Bob, let's call this number &lt;em&gt;numberAliceSent&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Alice receives Bob's letter with number 5. She then computes numberBobSent^secretAlice mod p, in this case 5^2 mod 7 = 4.&lt;/p&gt;

&lt;p&gt;Bob receives Alice's letter and does the same: numberAliceSent^secretBob mod p, in this case 2^5 mod 7 = 4.&lt;/p&gt;

&lt;p&gt;Their shared secret is 4. Whoever read the letters could read p, g, numberAliceSent and numberBobSent. However, they don't know neither Alice nor Bob's secret numbers nor their shared secret. Alice and Bob can now use their shared secret to encrypt and decrypt their correspondence.&lt;/p&gt;

&lt;p&gt;This works because for large primes it is prohibitively costly to figure out the shared secret with the information that an eavesdropper has access to (p, g, and numberBobSent and numberAliceSent). &lt;/p&gt;

&lt;h2&gt;
  
  
  Digital Certificates
&lt;/h2&gt;

&lt;p&gt;We now know that web servers and browser clients can make use of Diffie-Hellman to establish a secret key to encrypt communications even when someone has access to all information that is exchanged. &lt;/p&gt;

&lt;p&gt;This solves the problem of secure communications over an insecure medium, right? Well, not really.&lt;/p&gt;

&lt;p&gt;Going back to Alice and Bob's example, imagine that whoever is reading their correspondence, let's say Eve, takes a more proactive role. Eve will grab Alice's letters and replace them with her own, and will do the same with Bob's.&lt;/p&gt;

&lt;p&gt;She will be able to establish a secret key with both Alice and Bob. Alice will think she's corresponding with Bob, and Bob with Alice, while they are both corresponding with Eve.&lt;/p&gt;

&lt;p&gt;She then just has to receive Alice's letters, decrypt them with the key she established with Alice, read them, encrypt them with the key she established with Bob and send them to him.&lt;/p&gt;

&lt;p&gt;There's no way for Alice and Bob to know that their communication is not private.&lt;/p&gt;

&lt;p&gt;This is what is called "A man in the middle attack".&lt;/p&gt;

&lt;p&gt;So how can we solve this problem?&lt;/p&gt;

&lt;p&gt;That's where digital certificates come into play, but before we need to talk about asymmetric key encryption.&lt;/p&gt;

&lt;h3&gt;
  
  
  Asymmetric Key Encryption
&lt;/h3&gt;

&lt;p&gt;With asymmetric keys, there are two keys, a private and a public one. Both can encrypt and decrypt, but if you encrypt with one of them you can only decrypt with the other.&lt;/p&gt;

&lt;p&gt;The private key is never supposed to be sent, while the public key can be freely sent to anyone. Because anything encrypted by the private key can only be decrypted with the public key, if someone sends you something encrypted and you can decrypt it with a public key, you know that &lt;strong&gt;only&lt;/strong&gt; the holder of the private key could've encrypted what was sent.&lt;/p&gt;

&lt;p&gt;A certificate is just a public key bundled together with information about the holder of the private key (e.g. the subject name which usually contains the website domain, e.g. blinkingcaret.com).&lt;/p&gt;

&lt;p&gt;What makes a certificate trustworthy is that it is digitally signed by a certificate authority (an example would be &lt;a href="https://www.symantec.com/ssl-certificates/" rel="noopener noreferrer"&gt;Symantec&lt;/a&gt;, formerly Verisign). But first, what is a digital signature?&lt;/p&gt;

&lt;h3&gt;
  
  
  Digital Signature
&lt;/h3&gt;

&lt;p&gt;The goal of a digital signature is to prove the identity of the sender of the information and that the information was not changed along the way.&lt;/p&gt;

&lt;p&gt;A digital signature is performed in two steps. First a &lt;a href="https://en.wikipedia.org/wiki/Hash_function" rel="noopener noreferrer"&gt;hash&lt;/a&gt; of what is to be signed is created (a hash function transforms an arbitrary amount of data into a fixed amount). Then it is encrypted using a private key. The encrypted hash is bundled together with the information. The encrypted hash is the signature.&lt;/p&gt;

&lt;p&gt;When someone receives a piece of information with the encrypted hash they can create a hash of the information themselves (using the same type of hashing function, e.g. &lt;a href="https://en.wikipedia.org/wiki/MD5" rel="noopener noreferrer"&gt;md5&lt;/a&gt;), use the public key to decrypt the signature and compare the two hashes. If they match it means that the information not only was not changed, it was also created by whomever the private key belongs to.&lt;/p&gt;

&lt;p&gt;In case you are wondering why we don't just encrypt all the information instead of using a hash function, that's because the hash is much smaller and still has all the properties we need to guarantee that the information was not tampered with.&lt;/p&gt;

&lt;h3&gt;
  
  
  Certificate Authority
&lt;/h3&gt;

&lt;p&gt;A certificate authority is an entity that signs certificates. To sign a certificate, a certificate authority needs a private key, and with that a public key, which also comes in a certificate.&lt;/p&gt;

&lt;p&gt;The certificate authorities' certificates are special though. They are self-signed, which means they are signed with the private key that pairs with the public key in the certificate. Also, your computer's operating system came installed with a several certificate authorities' certificates.&lt;/p&gt;

&lt;p&gt;When someone gives us a certificate, if that certificate was signed by a certificate authority we trust (any of the certificate authorities for which we have a certificate installed in our computer) we trust the certificate (that's when you get the green address bar your browser).&lt;/p&gt;

&lt;p&gt;So, coming back to Alice and Bob's example, we should change the story here because the metaphor with the letters breaks a bit. &lt;/p&gt;

&lt;p&gt;Imagine that Bob and Alice would deliver the letters to each other by hand. &lt;/p&gt;

&lt;p&gt;Also, imagine that Alice and Bob had never met, they don't know how the other one looks like.&lt;/p&gt;

&lt;p&gt;Although more complicated, a man in the middle attack is still possible in this scenario. Imagine someone, let's say Joe would make himself pass by Bob and meet Alice, and then someone else, for example Jane, would pass herself by Alice and meet Bob. John and Jane could coordinate between themselves so that even if Alice and Bob tried to use Diffie-Hellman they would end up talking to Jane and John without knowing it.&lt;/p&gt;

&lt;p&gt;However, imagine now that Bob and Alice have id cards, issued by a government, and that are extremely difficult to forge. &lt;/p&gt;

&lt;p&gt;Alice can ask Bob for his id card. The card has Bob's name and his picture, and is issued by a government that Alice knows is trustworthy, Alice is satisfied that Bob is whom he says he is. Bob can do the same in regards to Alice.&lt;/p&gt;

&lt;p&gt;In HTTPS the id card is the certificate and the issuer is the certificate authority. Also, in HTTPS normally only the web server provides the certificate. However, although uncommon authentication of users with certificates is also possible.&lt;/p&gt;

&lt;p&gt;I hope this gives you a better idea of how all these pieces fit together to enable HTTPS. Be sure to check my &lt;a href="http://www.blinkingcaret.com" rel="noopener noreferrer"&gt;blog&lt;/a&gt; for more related content, for example &lt;a href="http://www.blinkingcaret.com/2017/02/01/using-openssl-to-create-certificates/" rel="noopener noreferrer"&gt;how to create your own certificate authority, install it and create signed certificates using OpenSSL&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>security</category>
    </item>
    <item>
      <title>ORMs, Lazy Loading and Web Applications</title>
      <dc:creator>Rui Figueiredo</dc:creator>
      <pubDate>Wed, 14 Jun 2017 16:30:41 +0000</pubDate>
      <link>https://dev.to/ruidfigueiredo/orms-lazy-loading-and-web-applications</link>
      <guid>https://dev.to/ruidfigueiredo/orms-lazy-loading-and-web-applications</guid>
      <description>&lt;p&gt;What do these three things have in common? &lt;/p&gt;

&lt;p&gt;They are frequently used together. Is that a good idea though? No, not at all, and that's what I'm going to convince you of in this blog post.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ff3mazbr3uecy0ype3er0.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Ff3mazbr3uecy0ype3er0.jpg" alt="Screen stuck on loading"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;But first lets talk little bit about what an ORM is, what it's for, and what is lazy loading in the context of ORMs.&lt;/p&gt;

&lt;p&gt;ORM is an acronym for "Object Relational Mapper". Two popular examples of ORMs are Entity Framework and Hibernate.&lt;/p&gt;

&lt;p&gt;In relational databases (like Sql Server, MySql, etc) the data is represented using tables, columns and rows. There is also the concept of a constraint like primary and foreign keys, indexes and many other things that have no direct equivalent in an object oriented programming language.&lt;/p&gt;

&lt;p&gt;Before ORMs were popular if you needed to read data from a database you would write a SQL query and that SQL code would live somewhere together with your source code.&lt;/p&gt;

&lt;p&gt;ORMs changed that by providing us with a way to declaratively specify how the data in a database maps to object oriented constructs. For example, how a table maps to a class and how a column maps to property.&lt;/p&gt;

&lt;p&gt;By having this intermediate layer it was now possible to write code that looks like it's only manipulating objects, but that under the covers, is converted to SQL queries that are transparently sent to the database.&lt;/p&gt;

&lt;p&gt;This is great because it simplifies how we interact with data. Previously we'd have to write SQL statements, which effectively were strings in our code. Concatenating SQL with user input was very common, and that is basically what enables SQL injection. SQL injection happens when a user writes SQL statements instead of normal input in a textbox that end up being executed in your database.&lt;/p&gt;

&lt;p&gt;So that is roughly what an ORM is about.&lt;/p&gt;

&lt;p&gt;What about lazy loading?&lt;/p&gt;

&lt;p&gt;To really understand lazy loading we need to talk a little bit more about a concept in ORMs called &lt;em&gt;Context&lt;/em&gt; (or &lt;em&gt;Session&lt;/em&gt;). Whenever data is loaded and converted to objects in memory by an ORM and these objects are stored in a &lt;em&gt;Context&lt;/em&gt;.&lt;/p&gt;

&lt;p&gt;Usually an interaction that involves fetching data from the database starts by creating a Context and then performing the operation that triggers the fetching of the data. Here's an example using Entity Framework that fetches all the Costumers from the database:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;myContext&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;MyContext&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;allCostumers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;myContext&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Customers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;ToList&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="c1"&gt;//...&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After accessing the Customers property in the context and calling &lt;em&gt;.ToList()&lt;/em&gt; on it (which is the operation that triggers the fetching of the data from the database), the customer data is stored in the context itself (for example in Entity Framework you would be able to access it in &lt;em&gt;myContext.Customers.Local&lt;/em&gt;). This is so that if you make changes to a customer the ORM can figure out what changed and generate the appropriate SQL statements.&lt;/p&gt;

&lt;p&gt;The context also has the ability to give you a slightly altered version of a Customer. And this is particularly relevant when &lt;em&gt;Lazy Loading&lt;/em&gt; is enabled. Imagine the Customer table is represented in the database as having many orders. The corresponding Customer class could look like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kd"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Customer&lt;/span&gt; 
&lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;int&lt;/span&gt; &lt;span class="nc"&gt;CustomerId&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt;&lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="n"&gt;set&lt;/span&gt;&lt;span class="o"&gt;;}&lt;/span&gt;   

    &lt;span class="c1"&gt;//...&lt;/span&gt;

    &lt;span class="kd"&gt;public&lt;/span&gt; &lt;span class="n"&gt;virtual&lt;/span&gt; &lt;span class="nc"&gt;ICollection&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nc"&gt;Orders&lt;/span&gt; &lt;span class="o"&gt;{&lt;/span&gt; &lt;span class="n"&gt;get&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="n"&gt;set&lt;/span&gt;&lt;span class="o"&gt;;&lt;/span&gt; &lt;span class="o"&gt;}&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Notice the &lt;em&gt;virtual&lt;/em&gt; keyword in the Orders' collection. It just means that you can create a subclass of customer and override what that property does. And that is precisely what the context will do if you enable lazy loading.&lt;/p&gt;

&lt;p&gt;With lazy loading enabled the context will keep track if that property was accessed or not. When it is accessed for the first time the context will transparently fetch the associated data (in this case the customer's orders).&lt;/p&gt;

&lt;p&gt;This allows us to write code like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;myContext&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;MyContext&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;johnDoe&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;myContext&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Customers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Single&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Name&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s"&gt;"John Doe"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

&lt;span class="n"&gt;foreach&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt; &lt;span class="n"&gt;in&lt;/span&gt; &lt;span class="n"&gt;johnDoe&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Orders&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;//do something with John Doe's order&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This all looks very well. It is easy to read and understand, however it could be made more efficient. However, it is not obvious why unless you are familiar with how the particular ORM that you are using works. &lt;/p&gt;

&lt;p&gt;In this case this is Entity Framework where the data will be fetched on calling &lt;em&gt;.Single(...)&lt;/em&gt; and when enumerating over the &lt;em&gt;Orders&lt;/em&gt;. So in this example there are two database calls.&lt;/p&gt;

&lt;p&gt;It is very easy to make this much worse and create what is called the N+1 problem. Here's an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;myContext&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;MyContext&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;thisYearCustomers&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;myContext&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Customers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Where&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;JoinYear&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="mi"&gt;2017&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

&lt;span class="n"&gt;foreach&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="n"&gt;in&lt;/span&gt; &lt;span class="n"&gt;thisYearsCustomers&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
&lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="n"&gt;foreach&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt; &lt;span class="n"&gt;in&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Orders&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt;
    &lt;span class="o"&gt;{&lt;/span&gt;
        &lt;span class="c1"&gt;//do something with the customer's order&lt;/span&gt;
    &lt;span class="o"&gt;}&lt;/span&gt;       
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will trigger a database request when the the customers are enumerated (foreach over customers) and then for each customer's orders. Hence the N+1, or 1+N if you prefer.&lt;/p&gt;

&lt;p&gt;In case you're thinking this that lazy loading is terrible and never makes sense, in this situation you're probably right. A situation that leads to a N+1 problem is likely always a mistake. However that doesn't mean that lazy loading is never useful.&lt;/p&gt;

&lt;p&gt;Imagine a desktop application where the context is created and lives through &lt;strong&gt;several&lt;/strong&gt; user interactions. For example the user opens a customer screen, looks at it and then decides to look at that customer's orders.&lt;/p&gt;

&lt;p&gt;In this scenario lazy loading is very convenient and makes sense.&lt;/p&gt;

&lt;p&gt;When it does not is in a web application. That's because the context will not exist during more than one user interaction. It's just not possible.&lt;/p&gt;

&lt;p&gt;In a web application the user's actions result in an HTTP request being sent from the user's browser to the server. The server then does all the required processing for that request and sends a response back to the user. And then this process repeats for every user action.&lt;/p&gt;

&lt;p&gt;Between requests the server forgets about the user, so if a context is created in response to a user's action it will be gone after the response is sent. That is just the stateless nature of the web.&lt;/p&gt;

&lt;p&gt;The only thing you can achieve using lazy loading in a web application is extra database calls you could avoid. That's because if user asks for the orders of a particular customer, the code that runs in the server will have to load the customer and the orders all during the handling of the user's request, it can either do it in a single database call or two. Lazy loading just makes it really easy to end up in the two database call scenario without realizing it.&lt;/p&gt;

&lt;p&gt;For completeness I'll just mention what happens if you have lazy loading disabled in most ORMs. In the example above the Orders property would be &lt;em&gt;null&lt;/em&gt;. You would have to instruct the ORM to fetch it together with the Customers all in one go. This is called eager loading:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;myContext&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;MyContext&lt;/span&gt;&lt;span class="o"&gt;();&lt;/span&gt;
&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;johnDoe&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;myContext&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Customers&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Include&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Orders&lt;/span&gt;&lt;span class="o"&gt;).&lt;/span&gt;&lt;span class="na"&gt;Single&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="n"&gt;customer&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;customer&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Name&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="s"&gt;"John Doe"&lt;/span&gt;&lt;span class="o"&gt;);&lt;/span&gt;

&lt;span class="n"&gt;foreach&lt;/span&gt;&lt;span class="o"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;var&lt;/span&gt; &lt;span class="n"&gt;order&lt;/span&gt; &lt;span class="n"&gt;in&lt;/span&gt; &lt;span class="n"&gt;johnDoe&lt;/span&gt;&lt;span class="o"&gt;.&lt;/span&gt;&lt;span class="na"&gt;Orders&lt;/span&gt;&lt;span class="o"&gt;)&lt;/span&gt; &lt;span class="c1"&gt;//no extra db access&lt;/span&gt;
&lt;span class="o"&gt;{&lt;/span&gt;
    &lt;span class="c1"&gt;//do something with John Doe's order&lt;/span&gt;
&lt;span class="o"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There's nothing to be gained by using lazy loading in web applications, however it's so much more common to see it being used in "the wild" than not. Even if we use the argument that it might be more convenient at times, the likelihood of having serious performance problems (like the N+1) offsets any possible benefits.&lt;/p&gt;

</description>
      <category>webdev</category>
    </item>
  </channel>
</rss>
