<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Andrei Diaconu on Medium]]></title>
        <description><![CDATA[Stories by Andrei Diaconu on Medium]]></description>
        <link>https://medium.com/@andrei_diaconu?source=rss-17f67c48c1b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EeWsbFzqFutqlxokxqz4FQ.jpeg</url>
            <title>Stories by Andrei Diaconu on Medium</title>
            <link>https://medium.com/@andrei_diaconu?source=rss-17f67c48c1b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 18:12:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andrei_diaconu/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[IT Beginner Series: Javascript Introduction (1)]]></title>
            <link>https://medium.com/@andrei_diaconu/it-beginner-series-javascript-introduction-1-f77242717d86?source=rss-17f67c48c1b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f77242717d86</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[learn-to-code]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[beginner]]></category>
            <dc:creator><![CDATA[Andrei Diaconu]]></dc:creator>
            <pubDate>Fri, 01 Sep 2023 18:31:03 GMT</pubDate>
            <atom:updated>2023-09-01T18:31:03.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bwuEpV6HsDx2Bw_WwjaY3g.png" /></figure><h3>More in the IT Beginner Series</h3><ul><li><a href="https://medium.com/p/cfc5d65b6f94">JavaScript IF/ELSE Exercises</a></li><li><a href="https://medium.com/@andreidiaconu90/javascript-for-loop-exercises-4c6cbf570411">JavaScript FOR loop exercises</a></li><li><a href="https://medium.com/@andreidiaconu90/sql-beginner-exercises-2517a53d2461">SQL Exercises</a></li></ul><p>Welcome to the “IT Beginner Series,” your gateway to the captivating realm of JavaScript. Whether you’re taking your first steps in the world of coding or just brushing up on your skills, this series is designed to make JavaScript an approachable adventure.</p><h3>What is JavaScript?</h3><p>JavaScript is a powerful programming language that plays a pivotal role in web development. It empowers you to bring life to websites and build interactive web applications. Let’s dive into the fundamental aspects of JavaScript syntax and how it operates.</p><h3>What is programming / writing code anyways?</h3><p>Imagine computer programming is like giving instructions to a very smart robot. You can tell the robot what to do by writing down special codes that it understands. These codes are like secret words that only the robot knows.</p><p>Now, let’s say you want the robot to make a sandwich. You’d write a code that goes something like this:</p><ol><li>Take two slices of bread.</li><li>Put some peanut butter on one slice.</li><li>Put some jelly on the other slice.</li><li>Stick the two slices of bread together.</li><li>Ta-da! You have a peanut butter and jelly sandwich!</li></ol><p>Computer programming is like that, but instead of making sandwiches, you can make the computer do all sorts of cool things, like playing games, showing pictures, and helping people with their work. It’s like telling the robot how to do amazing tricks with words and numbers to make the computer do what you want. And the more you learn, the more amazing things you can make the computer do!</p><h3>JavaScript Syntax</h3><p>And those special codes that robots (computers) understand are called programming languages. Just as with human languages, each programming language has its own unique characteristics. To become proficient in the English language, you must familiarise yourself with its alphabet, sounds, and the words that constitute it. In the realm of programming languages, we refer to this as “syntax.”</p><p>To keep things super simple and just focus on the code, we’re gonna be using a tool like <a href="https://jsbin.com/?js,output">jsbin.com</a> which will let us write and execute JavaScript code right in our browser. Just make sure that the Javascript and Output tabs are selected as in the picture below and you’re ready to go. We write code in the Javascript window and, after pressing the <strong>Run with JS</strong> button, we’ll see the results of our code in the Output window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QHOBcUk_0BwGNJmaGjfvHA.png" /></figure><p><em>Note: You’ll find pieces of code in this article that i recommend you to actually </em><strong><em>write in </em></strong><a href="https://jsbin.com/?js,output"><em>jsbin.com</em></a><em> rather than copy pasting, as it makes for a much better learning experience. After all, you want to learn to write</em><strong><em> </em></strong><em>code, not copy paste, right?</em></p><p>In JavaScript, your code is made up of a series of instructions or statements. Each statement typically ends with a semicolon (;) although JavaScript allows for optional semicolons thanks to automatic semicolon insertion. Here’s a simple example:</p><pre>console.log(&quot;Hello, JavaScript!&quot;); // This is a statement</pre><p>In this example, we’re using the console.log() statement to display &quot;Hello, JavaScript!&quot; in the browser&#39;s console. Try it out!</p><h3>JavaScript Variables</h3><p>Imagine you have a lot of important documents like bills, contracts, and letters. Instead of scattering them all over your desk, you put them into labeled folders or file cabinets and give a meaningful name to each of the cabinet and folder so it’s easy to find.</p><p>These folders and cabinets are like variables in programming. They help you keep your important documents organized and make it easy to find and work with them when you need to.</p><p>By using variables, you’re giving the computer a way to remember and use these important documents, just like you do with your organized filing system. It’s like having an efficient and structured system that makes your tasks more manageable and adaptable because you can change the contents of the folders whenever necessary.</p><h3>JavaScript Data Types and Variables</h3><p>Data Types in Programming are like different types of documents in your filing system:</p><ol><li><strong>Strings</strong>: These are like your written letters and text documents. They contain words, sentences, and text. For example, a letter you wrote is a “string” of text.</li><li><strong>Numbers</strong>: Just as you have documents with numerical values like bills or invoices, in programming, you have numbers. These can be whole numbers (like page numbers) or decimal numbers (like money amounts).</li><li><strong>Booleans</strong>: Think of booleans as two categories, like “Important” or “Not Important.” In programming, booleans are either “true” or “false.” They help you make decisions, just like you decide whether a document is important or not.</li><li><strong>Arrays</strong>: Arrays are like folders with multiple documents inside them. Each document (or item) can be of any data type, like having folders for bills, contracts, and letters, and each folder can contain multiple documents.</li><li><strong>Objects</strong>: Objects are like organised sets of related documents. In programming, they group different pieces of data together. For instance, you could have an object called “Client Information” that contains details like name, address, and phone number.</li><li><strong>Undefined</strong> and <strong>Null</strong>: These are like empty folders or missing documents. “Undefined” means there’s no value assigned to a variable yet, while “null” is a way of saying that a variable has no value or is intentionally empty, just like an empty folder.</li></ol><p>Data types are like the categories you use to sort and make sense of the various documents in your filing system. They help the computer understand what kind of information is stored in a variable, just as you know what to expect when you see a folder labeled “Bills” or “Letters” in your filing cabinet.</p><p>Let’s put all this together and see how we code different type of variables.</p><p><em>Remember: Actually </em><strong><em>write </em></strong><em>your code in JSBin, then click the button to run it. You’ll make mistakes, forget to put a semicolon(;), make typos, use the wrong operators, but that’s okay! Making these mistakes helps you better grasp the syntax and improve your understanding. I really can’t stress the importance of this enough!</em></p><h4>Strings</h4><p>Strings are used for text, like words or sentences. They are enclosed in single or double quotes.</p><pre>let name = &quot;Alice&quot;; // A string variable<br>console.log(name); // Output: Alice</pre><p>Here, we have a variable called name that holds the string &quot;Alice.&quot;</p><h4>Numbers</h4><p>Numbers are used for numeric values, like whole numbers or decimals.</p><pre>let age = 10; // A number variable<br>console.log(age); // Output: 10</pre><p>In this example, we have a variable called age that stores the number 10.</p><h4>Booleans</h4><p>Booleans represent true or false values. They are often used for making decisions in your program.</p><pre>let isStudent = true; // A boolean variable<br>console.log(isStudent); // Output: true</pre><p>The variable isStudent is set to true, which means the statement is correct.</p><h4>Arrays</h4><p>Arrays are like lists that can hold multiple values.</p><pre>let colors = [&quot;red&quot;, &quot;green&quot;, &quot;blue&quot;]; // An array variable<br>console.log(colors[0]); // Output: red</pre><p>Here, colors is an array that contains three strings, and we can access them using indexes (starting from 0).</p><h4>Objects</h4><p>Objects are collections of key-value pairs, like a dictionary.</p><pre>let person = {<br>  name: &quot;Bob&quot;,<br>  age: 30,<br>}; // An object variable<br>console.log(person.name); // Output: Bob</pre><p>The person variable is an object with properties like name and age.</p><h4>Undefined and Null</h4><p>Undefined means a variable has been declared but hasn&#39;t been assigned a value yet. Null represents no value or absence of an object.</p><pre>let undefinedVariable;<br>let nullValue = null;<br>console.log(undefinedVariable); // Output: undefined<br>console.log(nullValue); // Output: null</pre><p>Here, undefinedVariable is declared but not assigned a value, so it&#39;s undefined. nullValue is explicitly set to null.</p><p>Understanding these data types and using variables to store and manipulate them is crucial in programming. They allow you to work with different kinds of information effectively and make your code more powerful and flexible. As you continue your programming journey, you’ll discover even more data types and learn how to use them to create amazing things with JavaScript!</p><h3>JavaScript Operators</h3><p>JavaScript operators are like special symbols or words that allow you to perform various operations on data, just like how you use math symbols like “+” for addition or “-” for subtraction. These operators enable you to work with numbers, text, and other types of data in your code. Here are some common types of JavaScript operators:</p><p><strong>Arithmetic Operators</strong>: These operators perform mathematical calculations, like addition (+), subtraction (-), multiplication (*), division (/), and modulus (%), which gives you the remainder after division. For example, 3 + 2 would result in 5.</p><pre>let x = 5;<br>let y = 3;<br><br>let sum = x + y; // Addition<br>let difference = x - y; // Subtraction<br>let product = x * y; // Multiplication<br>let quotient = x / y; // Division<br>let remainder = x % y; // Modulus (remainder)<br><br>console.log(sum); // Output: 8<br>console.log(difference); // Output: 2<br>console.log(product); // Output: 15<br>console.log(quotient); // Output: 1.6666666666666667<br>console.log(remainder); // Output: 2</pre><p><strong>Comparison Operators</strong>: These operators compare two values and return a Boolean (true or false) result. Common comparison operators include == (equal to), != (not equal to), &gt; (greater than), &lt; (less than), &gt;= (greater than or equal to), and &lt;= (less than or equal to).</p><pre>let p = 5;<br>let q = 8;<br><br>let isEqual = p === q; // Equal to (strict equality)<br>let isNotEqual = p !== q; // Not equal to (strict inequality)<br>let isGreater = p &gt; q; // Greater than<br>let isLess = p &lt; q; // Less than<br><br>console.log(isEqual); // Output: false<br>console.log(isNotEqual); // Output: true<br>console.log(isGreater); // Output: false<br>console.log(isLess); // Output: true</pre><p><strong>Logical Operators</strong>: Logical operators help you work with Boolean values. &amp;&amp; (AND) returns true if both conditions are true, || (OR) returns true if at least one condition is true, and ! (NOT) reverses the Boolean value.</p><pre>let sunny = true;<br>let warm = true;<br><br>let beachDay = sunny &amp;&amp; warm; // AND<br>let parkDay = sunny || warm; // OR<br>let notSunny = !sunny; // NOT<br><br>console.log(beachDay); // Output: true<br>console.log(parkDay); // Output: true<br>console.log(notSunny); // Output: false</pre><p><strong>Unary Operators</strong>: These operators work on a single operand, like ++ (increment by 1) or -- (decrement by 1). For example, x++ increases the value of x by 1.</p><pre>let x = 5;<br><br>x++; // Increment by 1<br>console.log(x); // Output: 6<br><br>x--; // Decrement by 1<br>console.log(x); // Output: 5</pre><p>Operators are essential in programming because they allow you to manipulate data, make decisions in your code, and control the flow of your program. By using operators effectively, you can create dynamic and functional JavaScript applications.</p><p>With these fundamental concepts in mind, you’re ready to embark on your JavaScript journey. In the upcoming articles of the “IT Beginner Series,” we’ll explore of what JavaScript has to offer, allowing you to grasp it’s intricacies step by step.</p><h3>More in the IT Beginner Series</h3><ul><li><a href="https://medium.com/p/cfc5d65b6f94">JavaScript IF/ELSE Exercises</a></li><li><a href="https://medium.com/@andreidiaconu90/javascript-for-loop-exercises-4c6cbf570411">JavaScript FOR loop exercises</a></li><li><a href="https://medium.com/@andreidiaconu90/sql-beginner-exercises-2517a53d2461">SQL Exercises</a></li></ul><p>Happy learning,<br>Andrei</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f77242717d86" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IT Beginner Series: JavaScript IF/ELSE Exercises]]></title>
            <link>https://medium.com/@andrei_diaconu/it-beginner-series-javascript-if-else-exercises-cfc5d65b6f94?source=rss-17f67c48c1b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfc5d65b6f94</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[learn-to-code]]></category>
            <category><![CDATA[code-newbie]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[learning-to-code]]></category>
            <dc:creator><![CDATA[Andrei Diaconu]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 11:16:28 GMT</pubDate>
            <atom:updated>2023-09-01T18:25:00.454Z</atom:updated>
            <content:encoded><![CDATA[<h3>IT Beginner Series: JavaScript IF/ELSE Exercises (2)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*5lxwGpIl8unD4EJr3_R2_w.png" /></figure><h4>More in the IT Beginner Series</h4><ul><li><a href="https://medium.com/@andreidiaconu90/javascript-for-loop-exercises-4c6cbf570411">JavaScript FOR loop exercises</a></li><li><a href="https://medium.com/@andreidiaconu90/sql-beginner-exercises-2517a53d2461">SQL Exercises</a></li></ul><p>As you embark on your journey to learn programming, understanding conditional statements is a fundamental step. These statements allow you to create decision-making structures in your code, directing its flow based on specific conditions. In this IT Beginner Series, we’ll delve into the world of JavaScript if/else statements – a cornerstone of programming logic – and provide you with a set of 10 simple exercises to grasp their usage effectively.</p><h3>Introduction</h3><p>In the realm of programming, control flow is essential. You need the ability to dictate which code should run under certain circumstances. This is where conditional statements come into play. JavaScript offers the if/else statement as a powerful tool to achieve precisely that. This statement empowers your code to make choices based on conditions, allowing you to execute specific blocks of code depending on whether those conditions are met.</p><h3>Syntax</h3><p>Before diving into our exercises, let’s familiarise ourselves with the syntax of the JavaScript if/else statement:</p><pre>if (condition) {<br>  // Code to execute if the condition is true<br>} else {<br>  // Code to execute if the condition is false<br>}</pre><p>The condition is a logical expression that evaluates to either true or false. If the condition is true, the code within the first block executes. If the condition is false, the code within the else block (if present) is executed.</p><h3>Exercises</h3><p>Now, let’s jump into the exercises to gain hands-on experience with if/else statements. We&#39;ll provide a scenario, the code solution, and the expected output for each exercise.</p><h3>Exercise list</h3><ol><li>Write a program that determines whether a given number is positive or negative.</li><li>Write a program that checks if a number is even or odd.</li><li>Write a program to determine the greater of two numbers.</li><li>Write a program that transforms a numerical grade to a letter grade (e.g grade 10 should display “A”).</li><li>Write a program that calculates the ticket price based on age with the following conditions: age below 12 pay a ticket price of 5, age below 18 pay a ticket price of 10, age below 60 pay a ticket price of 20, age over 60 play a ticket price of 15.</li><li>Write a program that determines if a year is a leap year.</li><li>Write a program that calculates a discount based on the purchase amount.Prices equal or over 100 discount have a discount of 20. Prices equal or over 50 have a discount of 10. Otherwise discount is 0</li><li>Write a program that greets the user based on the time of day. Display good morning, good afternnon or good evening based on the time of day when you run the code.</li><li>Write a program that calculates the Body Mass Index (BMI) and categorizes it. The formula for BMI is: weight / (height * height).</li><li>Write a simple number guessing game. Provide a secret number and a guess. Based on those numbers give players clues if their guess is higher, lower or correct.</li></ol><h3>Exercise solutions — spoiler alert, solutions below</h3><h4><strong>Exercise #1 — Determine If a Number Is Positive</strong></h4><p><strong>Scenario</strong>: Write a program that determines whether a given number is positive or not.</p><p><strong>Solution</strong>:</p><pre>var number = 5;<br><br>if (number &gt; 0) {<br>  console.log(&quot;The number is positive.&quot;);<br>} else {<br>  console.log(&quot;The number is not positive.&quot;);<br>}</pre><p><strong>Output</strong>:</p><pre>The number is positive.</pre><h4>Exercise #2 — Check Even or Odd</h4><p><strong>Scenario</strong>: Write a program that checks if a number is even or odd.</p><p><strong>Solution</strong>:</p><pre>var number = 7;<br>if (number % 2 === 0) {<br>  console.log(&quot;The number is even.&quot;);<br>} else {<br>  console.log(&quot;The number is odd.&quot;);<br>}</pre><p>Output:</p><pre>The number is odd.</pre><h4>Exercise #3 — Determine the Greater Number</h4><p><strong>Scenario</strong>: Write a program to determine the greater of two numbers.</p><p><strong>Solution</strong>:</p><pre>var num1 = 10;<br>var num2 = 15;<br><br>if (num1 &gt; num2) {<br>  console.log(&quot;num1 is greater.&quot;);<br>} else {<br>  console.log(&quot;num2 is greater.&quot;);<br>}</pre><p>Output:</p><pre>num2 is greater.</pre><h4>Exercise #4 — Grade Calculator</h4><p><strong>Scenario</strong>: Write a program that assigns a letter grade based on a numerical grade.</p><p><strong>Solution</strong>:</p><pre>var score = 85;<br>var grade;<br><br>if (score &gt;= 90) {<br>  grade = &quot;A&quot;;<br>} else if (score &gt;= 80) {<br>  grade = &quot;B&quot;;<br>} else if (score &gt;= 70) {<br>  grade = &quot;C&quot;;<br>} else if (score &gt;= 60) {<br>  grade = &quot;D&quot;;<br>} else {<br>  grade = &quot;F&quot;;<br>}<br>console.log(&quot;Grade: &quot; + grade);</pre><p><strong>Output</strong>:</p><pre>Grade: B</pre><h4>Exercise #5 — Ticket Pricing</h4><p><strong>Scenario</strong>: Write a program that calculates the ticket price based on age.</p><p><strong>Solution</strong>:</p><pre>var age = 25;<br>var ticketPrice;<br><br>if (age &lt; 12) {<br>  ticketPrice = 5;<br>} else if (age &gt;= 12 &amp;&amp; age &lt; 18) {<br>  ticketPrice = 10;<br>} else if (age &gt;= 18 &amp;&amp; age &lt; 60) {<br>  ticketPrice = 20;<br>} else {<br>  ticketPrice = 15; // Senior citizen discount<br>}<br>console.log(&quot;Ticket Price: $&quot; + ticketPrice);</pre><p><strong>Output</strong>:</p><pre>Ticket Price: $20</pre><h4>Exercise #6 — Determine Leap Year</h4><p><strong>Scenario</strong>: Write a program that determines if a year is a leap year.</p><p><strong>Solution</strong>:</p><pre>var year = 2024;<br><br>if (year % 4 === 0 &amp;&amp; (year % 100 !== 0 || year % 400 === 0)) {<br>  console.log(year + &quot; is a leap year.&quot;);<br>} else {<br>  console.log(year + &quot; is not a leap year.&quot;);<br>}</pre><p><strong>Output</strong>:</p><pre>2024 is a leap year.</pre><h4>Exercise #7 — Shopping Discount</h4><p><strong>Scenario</strong>: Write a program that calculates a discount based on the purchase amount.</p><p><strong>Solution</strong>:</p><pre>var purchaseAmount = 120;<br>var discount;<br><br>if (purchaseAmount &gt;= 100) {<br>  discount = 20;<br>} else if (purchaseAmount &gt;= 50) {<br>  discount = 10;<br>} else {<br>  discount = 0;<br>}<br>console.log(&quot;Discount: &quot; + discount + &quot;%&quot;);</pre><p><strong>Output</strong>:</p><pre>Discount: 20%</pre><h4>Exercise #8 — Time of Day Greeting</h4><p><strong>Scenario</strong>: Write a program that greets the user based on the time of day.</p><p><strong>Solution</strong>:</p><pre>var currentTime = new Date();<br>var currentHour = currentTime.getHours();<br>var greeting;<br><br>if (currentHour &lt; 12) {<br>  greeting = &quot;Good morning!&quot;;<br>} else if (currentHour &lt; 18) {<br>  greeting = &quot;Good afternoon!&quot;;<br>} else {<br>  greeting = &quot;Good evening!&quot;;<br>}<br>console.log(greeting);</pre><p><strong>Output</strong> (depending on the time of day you execute the code):</p><pre>Good afternoon!</pre><h4>Exercise #9 — BMI Calculator</h4><p><strong>Scenario</strong>: Write a program that calculates the Body Mass Index (BMI) and categorizes it.</p><p><strong>Solution</strong>:</p><pre>var weight = 70; // in kilograms<br>var height = 1.75; // in meters<br>var bmi = weight / (height * height);<br>var category;<br><br>if (bmi &lt; 18.5) {<br>  category = &quot;Underweight&quot;;<br>} else if (bmi &lt; 24.9) {<br>  category = &quot;Normal weight&quot;;<br>} else if (bmi &lt; 29.9) {<br>  category = &quot;Overweight&quot;;<br>} else {<br>  category = &quot;Obese&quot;;<br>}<br>console.log(&quot;BMI: &quot; + bmi.toFixed(2)); // .toFixed(2) limits the number of decimals to 2<br>console.log(&quot;Category: &quot; + category);</pre><p><strong>Output</strong>:</p><pre>BMI: 22.86<br>Category: Normal weight</pre><h4>Exercise #10 — Number Guessing Game</h4><p><strong>Scenario</strong>: Write a simple number guessing game.</p><p><strong>Solution</strong>:</p><pre>var secretNumber = 7;<br>var guess = 5; // The player&#39;s guess, change this to see that different code lines are executed based on the conditions<br>if (guess === secretNumber) {<br>  console.log(&quot;Congratulations! You guessed the correct number.&quot;);<br>} else if (guess &lt; secretNumber) {<br>  console.log(&quot;Try a higher number.&quot;);<br>} else {<br>  console.log(&quot;Try a lower number.&quot;);<br>}</pre><p>Output (depending on the player’s guess):</p><pre>Try a higher number.</pre><h3>Conclusion</h3><p>Congratulations! You’ve completed the JavaScript if/else exercises in the IT Beginner Series. You&#39;ve gained hands-on experience in using conditional statements to make decisions in your code. These exercises have provided you with a solid foundation for understanding how if/else statements work</p><p>Good luck, <br>Andrei</p><h4>More in the IT Beginner Series</h4><ul><li><a href="https://medium.com/@andreidiaconu90/javascript-for-loop-exercises-4c6cbf570411">JavaScript FOR loop exercises</a></li><li><a href="https://medium.com/@andreidiaconu90/sql-beginner-exercises-2517a53d2461">SQL Exercises</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfc5d65b6f94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# Mock different HttpClient calls in the same method]]></title>
            <link>https://medium.com/@andrei_diaconu/c-mock-different-httpclient-calls-in-the-same-method-ec5363ebeedd?source=rss-17f67c48c1b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec5363ebeedd</guid>
            <category><![CDATA[mocking]]></category>
            <category><![CDATA[http-client]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Andrei Diaconu]]></dc:creator>
            <pubDate>Wed, 06 Apr 2022 11:12:20 GMT</pubDate>
            <atom:updated>2022-04-06T11:12:20.589Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s say you want to unit test a method that does multiple http requests to different URLs. Maybe something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26b79a774d851bda2cc76085492fc94e/href">https://medium.com/media/26b79a774d851bda2cc76085492fc94e/href</a></iframe><p>As you may know, we can write unit tests for methods that use an injected HttpClientnot by mocking the HttpClientitself but by mocking the HttpMessageHandler which we can then pass to the HttpClient.</p><p>A simple httpClientmock using <a href="https://github.com/moq/moq4">Moq</a>would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6af5bc5da89316d98bcc6364c50c0a7/href">https://medium.com/media/f6af5bc5da89316d98bcc6364c50c0a7/href</a></iframe><p>With the above code in place any call going out from MyServicethrough the injected HttpClient will return whatever we’ve put in the mockedResponseMessage. This will suffice for most of our unit testing needs.</p><p>But what if we have a method inside MyServicethat does multiple http requests for which we would like to mock different responses?</p><p>We know that we can have multiple setups for the same mock, and the mock will respond based on that setup, so we just need a way to differentiate between those requests. In our GetStudentDatacase we can use the URL as a differentiator between requests so we could do something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25a01375e2916ee2c137799660840373/href">https://medium.com/media/25a01375e2916ee2c137799660840373/href</a></iframe><p>Now, whenever our code does a request to an URI which ends with /getStudentDetails/{identifier} , the mock will return the mockedStudentDetailsResponse . When the called URI ends with /getStudentGrades/{identifier} , the mock will respond, according to the second setup with mockStudentGradesResponse .</p><p>Happy coding,<br>Andrei</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec5363ebeedd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IT Beginner Series: SQL Exercises]]></title>
            <link>https://medium.com/@andrei_diaconu/sql-beginner-exercises-2517a53d2461?source=rss-17f67c48c1b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2517a53d2461</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[beginner]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Andrei Diaconu]]></dc:creator>
            <pubDate>Wed, 05 Jan 2022 10:09:32 GMT</pubDate>
            <atom:updated>2023-08-29T10:19:02.370Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/764/1*uVx917VDZnu32tuYpDlkXw.png" /></figure><h4>More in the IT Beginner Series</h4><ul><li><a href="https://medium.com/p/cfc5d65b6f94">JavaScript IF/ELSE Exercises</a></li><li><a href="https://medium.com/@andreidiaconu90/javascript-for-loop-exercises-4c6cbf570411">JavaScript FOR loop exercises</a></li></ul><p><strong>Introduction</strong></p><p><em>SQL is a domain-specific language used in programming and designed for managing data held in a relational database management system, or for stream processing in a relational data stream management system. It is particularly useful in handling structured data, i.e.</em><a href="https://en.wikipedia.org/wiki/SQL"><em>Wikipedia</em></a></p><p>In short, it’s the language we use to create a database, put data into it, read that data and so on.</p><p>Below you can find some exercises which should take you through all the basic SQL commands which you can use to get familiarized with the syntax and concepts.</p><p>You can use W3Schools SQL Editor to play around with SQL commands directly in your browser: <a href="https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all">https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all</a></p><p><strong>Anatomy of a database table</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*IrdD6R8JoMqTYrv8DoQk_Q.png" /><figcaption>Anatomy of an SQL table</figcaption></figure><p><strong>Syntax</strong></p><p><strong>Database entities</strong>​</p><ul><li><strong>Table</strong>: collection of rows​</li><li><strong>Row (or record)</strong>: actual data​</li><li><strong>Field (or cell)</strong>: data member​</li><li><strong>Column: </strong>name of the fields</li></ul><p><strong>Keywords for manipulating data:</strong></p><ul><li><strong>SELECT </strong>— query/select data in one or more tables</li><li><strong>INSERT </strong>— add values to a table</li><li><strong>UPDATE </strong>— edit/update values in a table</li><li><strong>DELETE </strong>— remove data from a table</li></ul><p><strong>Keywords for manipulating tables:</strong></p><ul><li><strong>CREATE</strong> — create a new table</li><li><strong>ALTER </strong>— edit/update the structure of a table(add/remove columns, change column datatype)</li><li><strong>DROP </strong>— remove a table</li></ul><p><strong>Exercises with solution</strong></p><p>#1 Create a table called ShopProducts with the following columns: ProductID, ProductName, Price, DateAdded</p><pre>--create table<br>CREATE TABLE ShopProducts(<br>ProductID INTEGER PRIMARY KEY AUTOINCREMENT,<br>ProductName varchar(50),<br>Price decimal,<br>DateAdded timestamp DEFAULT CURRENT_TIMESTAMP)</pre><p>#2 Insert a couple of values into the ShopProducts table</p><pre>--insert values into a table<br>INSERT INTO ShopProducts(ProductName,Price)<br>VALUES <br>(&#39;Iphone 13 Pro Max&#39;, 1800),<br>(&#39;S22 Ultra&#39;, 1500),<br>(&#39;3310&#39;, 9000),<br>(&#39;Xperia X&#39;, 500)</pre><p>#3 Select all columns from the Products table</p><pre>--select values from all(*) columns of a table<br>SELECT * FROM ShopProducts</pre><p>#4 Select only certain columns</p><pre>--select values from only certain columns<br>SELECT ProductName, Price FROM ShopProducts</pre><p>#5 Select ProductName and Price for products with the price lower than 10</p><pre>--select values that based on a condition<br>SELECT ProductName, PRICE FROM ShopProducts WHERE PRICE &lt; 1600</pre><p>#6 Select ProductName and Price for products with the Price between 1000 and 2000</p><pre>--select values that based on multiple conditions<br>SELECT ProductName, Price FROM ShopProducts WHERE Price &gt; 1000 AND Price &lt; 2000</pre><p>#7 Calculate the sum of all prices</p><pre>--select the sum of all values in a column<br>SELECT SUM(Price) FROM ShopProducts</pre><p>#8 Select the number of rows in the table</p><pre>--select the number of rows in a table<br>SELECT COUNT(*) FROM ShopProducts</pre><p>#9 Select the maximum value of a column</p><pre>--select the maximum values of a column<br>SELECT ProductName, MAX(Price) FROM ShopProducts</pre><p>#10 Order data by Price(run the queries one by one)</p><pre>--order data ascending<br>SELECT * FROM ShopProducts ORDER BY Price ASC</pre><pre>--order data descending<br>SELECT * FROM ShopProducts ORDER BY Price DESC</pre><p>#11 Update the price by 20% for product with ID 1</p><pre>--update product price<br>UPDATE ShopProducts SET Price = 1.2 * Price WHERE ProductID=1</pre><p># 12 Delete the product with product name “Nokia 3310”</p><pre>--delete product<br>DELETE FROM ShopProducts where ProductName = &#39;Xperia X&#39;</pre><p>#13 Add a new column named BrandID to the ShopProducts table</p><pre>--modify table structure<br>ALTER TABLE ShopProducts<br>ADD BrandID integer</pre><p>#14 Create a new Brands table</p><pre>CREATE TABLE Brands<br>(BrandID INTEGER PRIMARY KEY AUTOINCREMENT,<br>BrandName varchar(50),<br>BrandCountry varchar(50))</pre><p>#15 Add some brand details in the newly created Brands table</p><pre>INSERT INTO Brands (BrandName, BrandCountry)<br>VALUES (&#39;Samsung&#39;, &#39;Korea&#39;),<br>(&#39;Apple&#39;, &#39;US&#39;),<br>(&#39;Nokia&#39;, &#39;Finland&#39;)</pre><p>#16 Update the ShopProducts BrandID column with the correct BrandID from the Brands table(run commands one by one)</p><pre>UPDATE ShopProducts SET BrandID = 1 WHERE ProductName = &#39;Samsung S22 Ultra&#39;</pre><pre>UPDATE ShopProducts SET BrandID = 2 WHERE ProductName = &#39;Iphone 13 Pro Max&#39;</pre><p>#17 Show data from both ShopProducts and Brands tables by joining the tables</p><pre>--join data from two tables</pre><pre>SELECT ProductName, BrandName, Price<br>FROM ShopProducts<br>INNER JOIN Brands ON ShopProducts.BrandID =  Brands.BrandID</pre><p>Good luck, <br>Andrei</p><h4>More in the IT Beginner Series</h4><ul><li><a href="https://medium.com/p/cfc5d65b6f94">JavaScript IF/ELSE Exercises</a></li><li><a href="https://medium.com/@andreidiaconu90/javascript-for-loop-exercises-4c6cbf570411">JavaScript FOR loop exercises</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2517a53d2461" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[IT Beginner Series: JavaScript FOR Loop Exercises (3)]]></title>
            <link>https://medium.com/swlh/javascript-for-loop-exercises-4c6cbf570411?source=rss-17f67c48c1b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c6cbf570411</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[beginner-programmers]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrei Diaconu]]></dc:creator>
            <pubDate>Wed, 22 Dec 2021 19:50:18 GMT</pubDate>
            <atom:updated>2023-09-01T18:25:56.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*-oLYS0y56tan7vDNMFyCrg.png" /></figure><h4>More in the IT Beginner Series</h4><ul><li><a href="https://medium.com/p/cfc5d65b6f94">JavaScript IF/ELSE Exercises</a></li><li><a href="https://medium.com/@andreidiaconu90/sql-beginner-exercises-2517a53d2461">SQL Exercises</a></li></ul><p><strong>Introduction</strong></p><p>For loops are used to execute a piece of code a desired numbers of times. They are generally used to iterate over lists/collections of items. Think about iterating over a list of students and executing a piece of code that calculates the average grade for each student.</p><p>Loops and arrays are a great way to make you code adapt to change. Written correctly, a for loop will execute code no matter if you have one or 1 million students or if the number of students fluctuates over time(which will surely happen as they are students, right?:))</p><p><strong>Syntax</strong></p><pre>//A for loop that counts from 0 to 100 looks like this</pre><pre>for(var i = 0; i &lt;= 100; i++){<br>  //your code that will be executed 100 times here<br>}</pre><p>A for loop has 3 parts:</p><ul><li>a starting point: var i = 0</li><li>a stop/end point i ≤ 100</li><li>a “step” i++ (a short version of i = i+1)</li></ul><p>Starting from 0(var i=0), the for loop will increase the value of i with the specified “step” after each execution(i++). It will continue to do so until the expression i&lt;= 100 is false, thus finishing it’s execution.</p><p><strong>Exercises with solution</strong></p><p>#1 — Print the numbers from 0 to 15</p><p><strong>Solution</strong></p><pre>for (var i = 0; i &lt;= 15; i++) {<br>   console.log(&quot;Value of i is: &quot; + i);<br>}</pre><p>#2 — Print the numbers from 12 to 24</p><p><strong>Solution</strong></p><pre>for (var i = 12; i &lt;= 24; i++) {<br>        console.log(&quot;Value of i is: &quot; + i);<br>}</pre><p>#3 — Print the ODD numbers from 7 to 31</p><p><strong>Solution</strong></p><pre>for (var i = 7; i &lt;= 31; i++) {<br>  if (i % 2 != 0) {<br>    console.log(i);<br>  }<br>}</pre><p>#4 — Print the EVEN numbers from 10 to -20</p><p><strong>Solution</strong></p><pre>for (var i = 10; i &gt;= -20; i--) {<br>  if (i % 2 == 0) {<br>    console.log(i);<br>  }<br>}</pre><p>#5 — Iterate through all numbers from 1 to 45. Print the following:</p><ul><li>For multiples of 3 print “Fizz”</li><li>For multiples of 5 print “Buzz”</li><li>For multiples of 3 and 5 print “FizzBuzz”</li></ul><p><strong>Solution</strong></p><pre>for (var i = 1; i &lt;= 45; i++) {<br>  if (i % 3 == 0 &amp;&amp; i % 5 == 0) {<br>    console.log(&quot;FizzBuzz&quot;);<br>  } else if (i % 3 == 0) {<br>    console.log(&quot;Fizz&quot;);<br>  } else if (i % 5 == 0) {<br>    console.log(&quot;Buzz&quot;);<br>  }<br>}</pre><p>#6 — Print all the elements of the following array</p><pre>var thisIsAnArray = [&quot;element1&quot;, &quot;element2&quot;, &quot;element3&quot;, &quot;element4&quot;];</pre><p><strong>Solution</strong></p><pre>var thisIsAnArray = [&quot;element1&quot;, &quot;element2&quot;, &quot;element3&quot;, &quot;element4&quot;];</pre><pre>for (var i = 0; i &lt; thisIsAnArray.length; i++) {<br>  console.log(thisIsAnArray[i]);<br>}</pre><p>#7 — Calculate the sum of all the numbers in the following array</p><pre>var numbersArray = [1,13,22,123,49]</pre><p><strong>Solution</strong></p><pre>var numbersArray = [1, 13, 22, 123, 49];</pre><pre>var sum = 0;</pre><pre>for (var i = 0; i &lt; numbersArray.length; i++) {</pre><pre>  sum = sum + numbersArray[i];</pre><pre>}</pre><pre>console.log(&quot;The sum is: &quot; + sum);</pre><h4>More in the IT Beginner Series</h4><ul><li><a href="https://medium.com/p/cfc5d65b6f94">JavaScript IF/ELSE Exercises</a></li><li><a href="https://medium.com/@andreidiaconu90/sql-beginner-exercises-2517a53d2461">SQL Exercises</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c6cbf570411" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/javascript-for-loop-exercises-4c6cbf570411">IT Beginner Series: JavaScript FOR Loop Exercises (3)</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CodePipeline for Serverless Applications With CloudFormation Templates]]></title>
            <link>https://medium.com/swlh/codepipeline-for-serverless-applications-with-cloudformation-templates-f54b912add24?source=rss-17f67c48c1b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/f54b912add24</guid>
            <category><![CDATA[cloudformation]]></category>
            <category><![CDATA[the-serverless-framework]]></category>
            <category><![CDATA[aws-cloudformation]]></category>
            <category><![CDATA[aws-codepipeline]]></category>
            <category><![CDATA[codepipeline]]></category>
            <dc:creator><![CDATA[Andrei Diaconu]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 08:43:27 GMT</pubDate>
            <atom:updated>2020-10-02T18:36:37.903Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NFWEitUr6k1IBQY6D7uU3Q.png" /><figcaption>CodePipeline through CloudFormation with IAM Roles</figcaption></figure><h3>Introduction</h3><p>The CI/CD process of an application is crucial to its success and having an easy way to maintain said process can lead to an even healthier lifecycle for the application. Enter infrastructure as code: a reliable method of managing and provisioning pretty much anything you would need in a CI/CD pipeline to get it going, through the use of templates and definitions. Ever needed to keep the configurations of an AWS pipeline somewhere so you don’t need to remember the clicks from the Management Console by heart? Or maybe you wanted to give a working example to a colleague, so they can build their own pipeline. These problems and many more can be solved through infrastructure as code and CloudFormation, if we’re talking AWS.</p><p>In the following lines, we’ll go through everything you need to create your own pipeline, connect it with other pipelines and maintain them only by running a not that complicated bash script. And by the end, you’ll probably come to realize yourself how awesome infrastructure as code is (no need to thank us).</p><h4>Table of contents</h4><ol><li><a href="#eded">Simple Codepipeline using CloudFormation, The Serverless Framework, and IAM Roles</a></li><li><a href="#fc0e">Complex Codepipeline(s) with AWS Templates and Nested Stacks</a></li><li><a href="#fe5e">Automation through scripting</a></li></ol><h4>Just want to see the code? Here you go:</h4><ol><li><a href="https://gist.github.com/andreidiaconu90/178a74c4bba55406bd6f60106a8ad0d3">Simple pipeline CodeFormation template</a></li><li><a href="#3a64">The Serverless Framework catch</a></li><li><a href="https://gist.github.com/andreidiaconu90/af437237ce129aba1be88263e370e123">Template with nested stacks</a></li><li><a href="https://gist.github.com/andreidiaconu90/59dba3abc22928ce6cca4fa9364c2583">Automating template packaging/deployment through scripting</a></li></ol><h3>CodePipeline using Cloudformation</h3><p>Building a pipline in AWS’s CodePipeline is pretty simple and conceptually similar to other CI\CD tools out there, but it’s also quite verbose, requiring a considerable amount of code, especially if you want to build your pipeline in an infrastructure-as-code approach.</p><p>From a high level there’s 5 main types of resources we need in order for us to put together an AWS Codepipeline:</p><ol><li><strong>A S3 bucket </strong>resource<strong> </strong>— where our code artifact will be stored</li><li><strong>A CodePipeline</strong> resource— this will model what steps and actions our CodePipeline will include and execute</li><li><strong>IAM Roles</strong> — one role that CodePipeline will assume during its execution, in order to create/update/deploy the resources in our codebase. A second role used by a CodeCommit webhook(see #5).</li><li><strong>CodeBuild Project(s)</strong> — are used by the CodePipeline resource to execute the actual commands we want in our pipeline.</li><li><strong>An Event Rule</strong> — an AWS Event Rule that will act as a webhook triggering the pipeline on each master branch change(this is only required when working with CodeCommit. <a href="https://docs.aws.amazon.com/codepipeline/latest/userguide/action-reference-GitHub.html">If you use Github or other supported repo provider there are build-in webhooks</a>)</li></ol><p>Now we’ll go over each of the resource types and then we’ll put it all together in a complete CodePipeline.yml definition for a serverless application built on AWS Lambdas using the Serverless Framework(but not limited to these).</p><h4><strong>S3 bucket definition</strong></h4><p>You can consider this the code artifact store for our pipeline. This will be referenced and used later on by the pipline itself to first upload the artifact and then use it to deploy the resources.</p><p>The definition is pretty straight forward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8064351221d624f2255c4daa34cba15/href">https://medium.com/media/b8064351221d624f2255c4daa34cba15/href</a></iframe><h4><strong>CodePipeline definition</strong></h4><p>This will be the bulk of our pipeline definition code that will define what are the stages of our pipeline. <br>The top level properties of a CodePipeline resource definitions are:</p><ol><li><strong>ArtifactStore </strong>— this is where we’ll reference the S3 bucket that we’ve created earlier. We will do this by using AWS’s <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-ref.html">!Ref intrinsic function</a></li><li><strong>RoleArn </strong>— this is where we’ll reference the Role that the CodePipeline will assume during it’s run. We’ll do this by using the <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-getatt.html">!GetAtt intrinsic function</a></li><li><strong>Stages </strong>— a list of actions that our pipeline will do.</li></ol><p>A high level view over our CodePipeline definition will look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e9820a5b954daacc8320423cc494fd0/href">https://medium.com/media/8e9820a5b954daacc8320423cc494fd0/href</a></iframe><p>Notice that, for the sake of simplicity, we’ve left out the definition of the actual stages, which we’ll cover later on. But as you can see, in our case, for a serverless application, the stages of our pipeline will be:</p><ul><li><strong>Source </strong>— retrieving the sources from a supported git repo(CodeCommit, GitHub, Bitbucket) or an S3 bucket(this is useful if you’re not working with one of the supported git repos — but this implies having to upload your code to the bucket by your own means). We’ll stick to using a git repo since this is the most common scenario.</li><li><strong>Staging </strong>— reference to the Deploy-to-Staging CodeBuild project which will contain the actual deploy commands.</li><li><strong>Promote to Production</strong> manual approval gate — this will prevent an automatic deploy to Production each time the pipeline runs.</li><li><strong>Production Deploy</strong> to Production — reference to the Deploy-to-Production CodeBuild project which will contain the actual deploy commands.</li></ul><h4><strong>CodeBuild project</strong></h4><p>CodeBuild is the equivalent of build runners from other CI\CD tools. In our case we’ll use their ability to run CLI commands in order to deploy our application. The definition of a CodeBuild project that deploys our serverless + nodejs app to the staging environment/stack looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bfaff4e0c148720a2e5b879cc20942e/href">https://medium.com/media/5bfaff4e0c148720a2e5b879cc20942e/href</a></iframe><p>The most important part of a CodeBuild project is it’s buildspec.yml file which defines the actual CLI commands that the project will execute. You can see it being referenced in the Source property. The buildspec.yml file(located in the root of the project) looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0710c6e879e772f48a53717a6e1c0b29/href">https://medium.com/media/0710c6e879e772f48a53717a6e1c0b29/href</a></iframe><p>Putting all the pieces together here’s how the definition of the stages inside our CodePipeline definition will look like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ede4bce10cbe79279014caa9a0946d4/href">https://medium.com/media/6ede4bce10cbe79279014caa9a0946d4/href</a></iframe><h4><strong>IAM Roles</strong></h4><p>As mentioned earlier, we’ll create 2 IAM roles. One to be used by CodePipeline itself and one used by the CodeCommit webhook that we’ll create in a future step.</p><h4><strong>CodePipelineServiceRole</strong></h4><p>An IAM role is just a collection of policies or access rights that a certain resource is allowed to have. In our case this is the place where we define the access limits of the CodePipeline. This is important because, according to the AWS Well-Architected framework, a resource should be limited to accessing only the resources it’s supposed to access, as per the principle of least privilege. In other words we should avoid defining IAM policies that give unnecessary privileges, like the one bellow:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a40bc60ed1a1b192a95a5dd04176dc7c/href">https://medium.com/media/a40bc60ed1a1b192a95a5dd04176dc7c/href</a></iframe><p>and instead strive to limit the access boundries through policies that look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ddbb18073de1294d0e5ee77c54cc5a1b/href">https://medium.com/media/ddbb18073de1294d0e5ee77c54cc5a1b/href</a></iframe><p>There is no silver bullet when creating a CodePipeline IAM role, because the policies(access rights) of the role will differ based on the actual resources that you use in your project. There are some policies that will be required regardless of your setup as you can see below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eab45f9cd8d4562108bed8ef11a3a295/href">https://medium.com/media/eab45f9cd8d4562108bed8ef11a3a295/href</a></iframe><p>You can use the above definition as a starting point. Run your pipeline and add more permissions to the role based on the error messages received from AWS. Does your setup containing lamdas? Then probably you should add some lambda permissions. Dynamo db? Then add the necessary dynamo db permission. It’s a bit of a tedious process but it will add to the security of your environment. You can also use this to speed up the process: <a href="https://policysim.aws.amazon.com/home/index.jsp?#">https://policysim.aws.amazon.com/home/index.jsp?#</a></p><h4><strong>CodeCommit webhook(optional)</strong></h4><p>At this point, our CodePipeline is ready. The only thing missing is its ability to run on every change of the master branch. For this we need just two things: an Event Rule and a Role. The “webhook” we’re creating is actually an Event rule that listens for CloudWatch events emmited by CodeCommit and triggers our pipeline whenever there’s a change an the master branch(or any branch, for that matter). Fortunately, these are less verbose and look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c06c668da93ef5a0a81777c03255f0b5/href">https://medium.com/media/c06c668da93ef5a0a81777c03255f0b5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c87d108bb064ab764ab7069f388e6ef3/href">https://medium.com/media/c87d108bb064ab764ab7069f388e6ef3/href</a></iframe><h4><strong>Deploying the pipeline</strong></h4><p>At this point you should have everything ready and we can deploy the pipeline. This is pretty straightforward and can be done by running the following command:</p><pre>$ aws cloudformation deploy --template-file &lt;my-pipeline-template&gt;.yaml --stack-name &lt;my-stack-name&gt; --capabilities CAPABILITY_NAMED_IAM --region &lt;desired-region&gt;</pre><p>Note: the — capabilities CAPABILITY_NAMED_IAM is just an acknowledgment that you are aware that the template file will create named IAM roles.</p><h4><strong>The Serverless Framework catch</strong></h4><p>If you’re using The Serverless Framework there’s some changes that you have to do in the serverless.yml file. Normally, your serverless.yml file looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56867ab4784f2dd22af6d220a65e4124/href">https://medium.com/media/56867ab4784f2dd22af6d220a65e4124/href</a></iframe><p>Notice the profile:default property — this dictates which user/profile will be used by The Serverless Framework. The <em>default </em>profile is usually taken from the .aws/credentials file or environment variables. The default profile is usually an admin user with full privileges.</p><p>But once the pipeline tries to deploy the serverless framework stuff, the default profile means nothing, because there’s no credentials config file in our pipeline.</p><p>So we have to make use of the <strong>cfnRole </strong>property offered by The Serverless Framework. This property accepts an IAM role ARN as value, and uses it when deploying the AWS resources. So we just have to put the ARN of the role we’ve created earlier in the <strong>cfnRole </strong>property, remove the profile property and we should be set. (This means, that we’ll need to deploy our pipeline template in order to create the role, find its ARN, and update the serverless.yml file)</p><p>See below the cnfRole property working along with the profile property by using the <a href="https://www.npmjs.com/package/serverless-plugin-ifelse">serverless-plugin-ifelse</a>. This makes it work on staging/production environments/stacks(when CodePipeline does the deployment) as well as development stacks(when you want to deploy your stack from your development machine).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e4044e5fc97a08fc180c84b43484465/href">https://medium.com/media/4e4044e5fc97a08fc180c84b43484465/href</a></iframe><h3>Multiple CodePipelines using AWS Templates and Nested Stacks</h3><p>We have seen how we can declare various resources and tie them together into a fully functional, independent pipeline. But what if we want to build a much larger template through combining multiple smaller ones? Or we want to group similar resources, such as roles, lambda configurations or policies? AWS’s answer to these questions is simple: Nested Stacks.</p><p>Nested Stacks are stack resources part of bigger stacks. They are treated as any other AWS resource, thus helping us avoid reaching the 200 resources limit of a stack. Also, they offer functionalities such as input and output parameters, through which the stacks communicate between themselves. In addition, the use of Nested Stacks is considered a best practice, as it facilitates reusability of common template patterns and scale well with larger architectures (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html).</p><p>So how can we make use of these fancy, well-regarded, Nested Stacks? Simple! Treat each of the 3 pipelines as an independent nested stack. Since they don’t contain that many resources (now or in the near future, for that matter), segregating them by type doesn’t offer that big of an advantage and thus, the nested stacks won’t even require the use of input and output parameters, since they contain everything they need inside their own definition. The 3 nested stacks would reside under a parent one, used as a single point of access whenever changes are made to any of them.</p><p>What needs to be done, then? There are 3 steps we need to follow in order to build our template with the use of nested stacks:</p><h4>Define a root template</h4><p>This file will reference all the other templates using the physical path</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1aff869884e9ba4b9c6fabae890fa143/href">https://medium.com/media/1aff869884e9ba4b9c6fabae890fa143/href</a></iframe><p>This file is a simple collection of AWS::CloudFormation::Stack resources, referencing each template through their physical path. Here, you can also define the input/output parameters mentioned earlier, which are values passed between stacks when they need to communicate, but for us, it’s not the case.</p><h4>Package the template</h4><p>Once we’ve finished configuring our Nested Stacks setup, we can start combining them. Currently, Amazon only supports combining templates into larger ones using S3 buckets. The local files are uploaded to an existing bucket (passed as a parameter) and a new file is generated, this time containing not the physical path, but the S3 location URL</p><p>Running this command:</p><pre>$ aws cloudformation package --template-file /root-template-file.yml --s3-bucket bucket-name --output-template-file my-packaged-template.yml</pre><ul><li>— template-file — the root template file, containing the physical paths</li><li>— output-template — the name and location of the newly generated template, containing the S3 paths</li><li>-s3-bucket — the name of the bucket used for packaging the files</li></ul><p>will result in something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f9cb964c2eb74a19cf2a975bfa6bebf/href">https://medium.com/media/1f9cb964c2eb74a19cf2a975bfa6bebf/href</a></iframe><p><strong>Note</strong>: The S3 bucket used for holding these files <strong>needs to already be created</strong>, before the execution of the “package” command. Also, one needs to be careful not to include the definition of the deployment bucket inside any of the templates, since this would lead to a circular reference.</p><h4>Deploy the template</h4><p>Once the output template is generated, we can safely deploy it. CloudFormation will look for the specified files in the S3 bucket and create/update the root stack and, implicitly, the nested stacks. If the stacks already exist, they are evaluated based on change sets and if any differences are found, CloudFormation updates only the ones that were modified.</p><p>The deploy command goes like this:</p><pre>$ aws cloudformation deploy --template-file /my-packaged-template.yml --stack-name my-stack-name --capabilities CAPABILITY_NAMED_IAM --region my-region</pre><p>And that’s about it. You should now have 3 different piplines created by your template. Not the smoothest process, but pretty straightforward, nonetheless. A possible solution could be automating this whole endeavor through a script. In the following section, we will see exactly how we can achieve this.</p><h3>Automating the package/deploy process</h3><p>As we’ve seen earlier, there are a couple of steps which we need to do in order to get our nested stack template packaged and deployed. Unfortunately we have to go through all of the above process each time we modify our pipeline.</p><p>Besides being really cumbersome, doing all of these steps manually is not recommended as it is prone to errors. After all, you’re creating an automated CI/CD pipeline in order to reduce the amount of work you have to do, not add to it. If you’ve reached this point and you’re asking yourself “do I have to do all of that every time I want to deploy my pipeline?”, then don’t worry because the answer is no. But how can we avoid this hustle and automate the entire process? The solution? Bash scripts to the rescue!</p><p>Using a bash script we can achieve the same result as manually deploying the pipeline(s), without giving yourself a headache. Take a look bellow at an example of a simple script that does everything we need:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd3bccc726685368e1ca33d0e5a75dbb/href">https://medium.com/media/fd3bccc726685368e1ca33d0e5a75dbb/href</a></iframe><p>While this would probably work just fine (assuming the bucket exists and the template is valid), it’s a good idea to follow certain conventions regardless of the programming language you use. Let’s take a look at how we can improve our script a bit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eacc01d19621cd680421511f2ee4949/href">https://medium.com/media/1eacc01d19621cd680421511f2ee4949/href</a></iframe><p>The above bash script does a couple of things:</p><h4>Make sure the bucket exists</h4><p>Because of the way nested stacks work, we need to have an S3 deployment bucket where our templates will be stored to be later used by the root stack in the deployment process. Therefore the first thing we need to do is to ensure that the bucket exists. The head-bucket command (aws s3api head-bucket --bucket $bucketName ) is perfect for this because it determines whether the bucket exists and if we have permission to access it.</p><h4>Validate the template</h4><p>The next step is to make sure that the template that we’re going to deploy is valid. To do this we can use the validate-templatecommand (<em>aws cloudformation validate-template — template-body $pathToTemplate</em>) which, if the template is not valid, will return a error message detailing what is wrong with it. Once we confirmed that the template is good, we can move forward and deploy it.</p><h4>Package the template</h4><p>The <em>aws cloudformation package — template-file $pathToRootTemplate — output-template $pathToOutputTemplate — s3-bucket $bucketName</em> command returns a copy of the root template, replacing the references to the local template files with the S3 location where the command uploaded the artifacts. So basically, it sets us up for the next step, the actual deployment.</p><h4>Deploy the pipeline(s)</h4><p>After all this setup, we can finally deploy our pipeline(s). We do this with the deploycommand (<em>aws cloudformation deploy — template-file $pathToOutputTemplate — stack-name $stackName — capabilities CAPABILITY_NAMED_IAM — region $region</em>), which uses the template that was generated by the package command in the previous step to create our (pipeline) resources. If this step succeeds, the pipeline(s) resources will be created in the specified stack.</p><p>And that’s it. We now have a script that does all the heavy lifting for us. All that’s left is to add the script to your package.json’s scripts section and you’re all set.</p><h3>Conclusion</h3><p>Quite a ride, wasn’t it? We’ve seen how to write the definition of an AWS pipeline and all its components, we’ve rigged a bunch of them together using CloudFormation and Nested Stacks and finally we’ve automated the whole process through the use of a bash script. Hopefully all of this came in handy and helped you avoid too many of those pesky configuration item changes on AWS, when building your own pipeline (guess what gave us an unusually hefty bill at the end of the month).</p><p>If you have any feedback for the article or the code presented in it, please leave us a comment or send us an email, every thougt and idea is appreciated.</p><p>Thanks for reading and happy coding,<br><a href="https://medium.com/@andreiarhip_33421">Andrei Arhip</a><br><a href="https://medium.com/@ioneasa.tudor">Tudor Ioneasa</a><br><a href="https://medium.com/@andreidiaconu90">Andrei Diaconu</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f54b912add24" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/codepipeline-for-serverless-applications-with-cloudformation-templates-f54b912add24">CodePipeline for Serverless Applications With CloudFormation Templates</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>