WHAT'S NEW?
Loading...

MTA Microsoft Technical Associate (Exam 98-361) Understanding Databases

Index


  1. Introducing Relational Database Management Systems (RDMS)
  2. Understanding Query Methods
  3. Database Connections

1. Introducting RDMS

Database is a collection of related information, for instance, an mp3 player is a kind of database where you not only save just your favourint music tracks, you also save related information like the name of every song, the lenght, the artins. All this information is stored and is related to the same subject.


RDMS is a relational storage concept for data, where you can allocate the information in different tables and you can link those tables depending of how do you want to access the information. For instance if you want to create a new database to save all the music you have at home, first you can create a table to save all the songs, other table to save the info related with the artist, other table could store the different music styles you have...

Uses normalization, which tries to avoid fields repetition. For our music example, imagine you want to save the city of all the bands you have in your music collection. First you can probably think, ok! let's save the City in my Bands table directly. At first it has sense, but the problem comes when that table goes bigger and the amount of Cities is too big. Why we don't create another table just to save the cities with a number assigned to every city (Primary key) and link this table with our bands table. Using this process, you are not saving thousands of times the same city name. This way, we will just have a number in the band table (Foreign key) which means the city assigned to that band. You save it just one time in your cities table and link it with a number, which is less heavy than the text and very easy to link for an RDMS.

See in the following example how different tables are linked in a company database. You can see here below, table "Orders" used to save the different sales orders with a numeric primary key called "OrderID", this is linked with a third table called "LineItems" responsible of link orders and products saving the "OrderID's" and the "ProductID" numbers. This way save a lot of space and process time working with numbers instead of the Product text name.


RDMS consists of services and applications for managing data and it allows querying, updating, inserting and deleting of data. All these tools give you the ability to play with all the information you stored in your database in a very efficient and performed way.

You can find different providers for your database like: SQL Server, Oracle or MySql. All of them use their own language (TransactSQL, PL/SQL and ) to access the information throw different commands 

2. Understanding Query Methods

Queries, allow developers to get information from the database, insert, edit and delete either from a web application or a desktop application. With a few examples we will go throw all of these different queries, using the Microsoft AdventureWorks2012 (you can get it from here) database tables:

  • Selecting data: you will need to use the "Select" command from SQL, in our first example we will select all the columns throw the reserved word: *, after the SELECT word. Also we need to specify from which table we want to get the information with the FROM reserved word, in our case we are using the "Person.Address" table. Follow the following patter to get information: SELECT <column name/s> FROM <table name> WHERE (optional) <conditions>

USE AdventureWorks2012;

-- Get information from the address table for people

SELECT *
FROM Person.Address;

-- Get the state or province associated with the ID 79

SELECT *
FROM Person.Address
WHERE AddressID = 79;

  • Updating data: to update information in your tables you need to use the UPDATE statement first, followed by the table name, then you will need to specify the values that you want to save and optionally the rows where you want to apply those values. Follow the following patter: UPDATE <table name> SET <values to save> WHERE (optional) <conditions>. In the following example we are setting the middle name 'Angela' to someone called 'Gail Erickson'.

-- Update the middle name to an initial
UPDATE Person.Person
SET MiddleName = 'Angela'
WHERE FirstName = 'Gail' AND LastName = 'Erickson'

You will need to be very careful when you launch update queries to your database, because sometimes you think you are updating just the rows that you want to update but maybe there are more rows which fit with your query conditions and can apply those changes to them too. To avoid these kind of errors the best way to update fields is selecting them by using their primary key like the Id because these keys use to be unique in the tables instead of using text fields.
  • Inserting data: for this example we need to use the INSERT statement with the following query pattern: INSERT INTO <table name> VALUE <different values>. First take a look at that table to see how is built and which data contains. The idea is to add a new language for the people from Canada in the cultures table.

-- Return all information from the culture table
SELECT *
FROM Production.Culture;

-- Insert a new value into the culture table
INSERT INTO Production.Culture
VALUES ('ca-fr', 'Canadian French', GETDATE());

As you can see, one of the fields is populated with a special command called GETDATE(), this command gets the current date and time when the update statement is triggered.
  • Deleting data: you will need to be very careful with this command, rememberer you are applying changes directly in the database and there is no roll back. The following pattern explains how this command works: DELETE FROM <table name> WHERE (optional) <conditions>. See the WHERE optional parameter, if we don't specify this parameter in our delete query, we are actually saying to SQL Server that we want to delete all the rows within the table we have specified. In the following example we will delete our previous insert.

-- Delete an item from the culture table
DELETE FROM Production.Culture
WHERE CultureID = 'ca-fr';

I hope these examples help you to get a better understanding of how powerful is this language and all the things you are capable to do. For a better understanding you can get more info from W3.

3. Database Connections

In our future applications we'll need to specify how to connect to our database server, here is where we need to provide a database connection, which provides the different user credentials and server information that we need to be able to link our app with our RDMS. The connections can be pooled, which means, open a connection to a database and allow a different set of sockets that can be used by different clients to access the database. This is used because open a database connection takes a lot of time, so we just want to open it once by our connection handler and the user can ask him for a connection when it is available. See the image bellow to get a better understanding:


This way we have just one place to handle the connection with the database and we allow access to those we want.

Another important point is to open and close the connection. If a database connection is not closed could produce security issues in your applications specially if your applications is web.

Here below I include an example of a connection string with different parameters that are required to make our connection successful:

m_sConnStr = "Provider=SQLOLEDB;Data Source=MySqlServer;Initial Catalog=Northwind;Integrated Security=True".

Provider is the component responsible of the communication and information handling. DataSource is the name of the server where we want to connect. Initial catalog is the name of the database within that database server. Integrated security equals true means, if I am connected to windows with my domain user and password, use those credentials to login into the database server. This is just an example but you can find thousands of different connections strings to use in your applications.

That's all for now and I hope to see you in the next module!

MTA Microsoft Technical Associate (Exam 98-361) Desktop applications

Index


  1. GUI Apps
  2. Console Apps
  3. Windows Services Apps

1. GUI Apps

GUI or Graphical User Interface is the "tool" that allow developers to give permission to the user to use different functions implemented in code in a very straight forward method. You probably think that before GUI there was nothing, just darkness. True! Actually, the computers were able to show just some text in green with a black background and the functionality was very limited. But those times are over (thanks God) and now we can talk about GUI's and how they interact with our mouse throw different menus, buttons and windows in very different environments like desktop applications, webs, phone applications, in our tablets...

There are a lot of tutorials on how to create great GUI and good practices on what you don't have to do when facing a user interface creation, but I think there is just one rule that is really important for you, as developer, to keep in mind, is just thinking as if your grand mother were using your application, I mean, KEEP IT SIMPLE!

2. Console-Based Apps

From someone who wants to start coding and learning how to create your own applications, this is a great point to start. Creating console applications you avoid facing problems derived from desktop apps or web apps, which need a better understanding on how the development process is. This apps are driven by the command-line and no graphical components like windows or icons are required.

You probably think now what's the meaning of this kind of application, why we need them if we already have window applications with great user interfaces. The reason is because sometimes we need to get more speed in a particular process and it's there where the console apps get a great value. Imagine that you need to create thousands of new user for a particular web application, and you can do it one-by-one, filling the different fields that you have in the register user form and finally clicking on the create button. That can take you ages to finish but if you create a small console app which can reads from a text file and get all the users that would be faster definitely.

Many administrators and IT infrastructure guys find the windows console really useful and that's why Microsoft added PowerShell in his Windows OS to allow those admins to create scripts in a faster way to automate task and access to some parts of the OS quickly.


3. Windows Services Applications

This kind of applications are really useful if you need to keep something running in the background during a long term. They don't have any user interface and if you need to change any setting or configuration within them, you probably would need to use a console app or with another kind of GUI. 

As an example, try to open your windows task manager and go to the "Services" tab. You will see a long list of apps running like WSearch, which is the windows search service used every time you try to find something in your computers like an application or a document. Another example, if you have SQL Server Configuration Manager installed in your computer, there you are able to activate or deactivate all the services related with SQL databases like sql agent, reporting, browser,...

The task scheduler is another example of service running in the background of your computer. It tracks all the different tasks that you want to execute and it just executes them at some particular hour. The Event Viewer in Windows is another example of service which tracks everything happens in your computer (warnings, errors...), very useful if you face any problem and need to find our why is happening. 

I hope you enjoyed this module and see you next time!

MTA Microsoft Technical Associate (Exam 98-361) Web applications

Index


  1. Web Page construction
  2. Understanding ASP.NET
  3. Hosting Web sites
  4. Intro Web services

1. Web Page construction


The origin of web pages was to store documents and move from one to another easily. Over time, Internet has evolved and now you are able to find more functionalities and different services but all of these web pages are built with three main languages you should know:

  • uses HTML: Hypertext Markup Language, here the developer includes the structure of our documents. It defines the position of every element you can see in a web page.
  • uses CSS: responsible of the look of any page. Here we can talk about inheritance between the different groups defined in our html page that's why it takes the name of Cascade Style Sheet.
  • uses JavaScript (JS): gives functionality to our web page on the client side (because sometimes we don't want to go back to the server for "small things"), by creating links to other resources, user messages, data validation and a lot of new and real time functions if you are using frameworks like jQuery for instance.

All this information (HTML + CSS + JS) is interpreted by web browsers and served to the user but not all the browsers make the same interpretation of the same code. This is a problem and HTML5 is not an exception. There are some tools to make our life easier like modernizr, which allows you to know which functions are enable in the current user's browser. To see the code of any web page you just need to make right click in every web page and choose an option similar to "view source code" to get a new window with all this information

2. Understanding ASP.NET

This component is a part of our web site that it will be processed within the server before we send the web page to the user. You get more functionality in your web pages by using asp.net allow you to use your web as a normal application with: server-side web framework, provides dynamic content, uses HTML and code-behind, hosts (Internet Information Service IIS) web applications on a server and provides data connectivity (Microsoft SQL Server)

When use asp you can create your own classes in your web project like in a normal console/desktop application. Besides you can add code (VB/C#) directly within your web pages using asp syntax (aspx or razor syntax). This means you will be able to run loops, add variables, call methods and all within your HTML page, which gives great functionality to your future web projects.

3. Hosting Web sites

This is a very important point because when you finish your first web application you will need to host it (save&serve it) in a server that allows you to run asp web pages (if that was the engine you worked with). At this point, IIS takes a really important role due to is going to be en charged of running that application and serve it to the users. During your development you probably faced "IIS Express" running in your windows clock, that is a small version of a current IIS within a server.

4. Intro Web services

A web service is hosted in a web server ;) and typically it does not have any interface to interact with. A example of web service is one created by several weather forecast web pages, which allows developers to access some pieces of code where you can pull useful information like temperature, forecast and weather for a certain town/city. This web services could be interfaces that are implemented by some classes and we, as clients of that web service, we can use that functionality directly. There are a lot of services in the net like Google maps, coordinate, image recognition, even beer location!!!

Cheers!



MTA Microsoft Technical Associate (Exam 98-361) Object-Oriented Programming

Index


  1. Fundamentals of Classes
  2. Encapsulation
  3. Inheritance
  4. Polymorphism

1. Fundamentals of Classes


First is important to talk about, what is object oriented program? and what other types of programming types are? 
In the past was very common to create applications filled with methods that cover different functionalities and all the code was executed sequentially. At some point, the technology advanced and we are able to use object oriented programming in our apps, which allow us to model our applications in a more closer way to real life. Every class defines an object from the real world with methods and properties which define that object.

A class is like a blueprint for a house, a person, an animal... It's just the definition of the object we'd like to model in our application and for the animal example, it contains the type of animal, the weight, the colour, etc. But also the different behaviours derived from that object in the real life, for instance, our Animal class would contain methods to make noise, to move... At some point when you have finished writing your class, when you run your application, that class will be created within the computer's dynamic memory and it became an "object". We call that process: instantiate.


2. Encapsulation


By using encapsulation, the purpose is to create all the data and behaviours within our class, to provide that information to the user/developer who uses our class but in a way that user doesn't have access to all the components in the class just those ones we want to make visible. It'd look like a black box. For instance, the user can't set the values directly into our variables, the idea of encapsulation is to provide a bunch of properties where set that values if we want as owners of that class.

Let's take a look to one example. In this class we have created a set of properties (data) and methods (behaviour) related with any animal. 

class Animal
{
    // member variables (attributes)
    private string type;
    private double weight;
    private string color;

    // properties
    public string Type
    {
        get
        {
            return type;
        }
        set
        {
            type = value;
        }
    }

    public double Weight
    {
        get
        {
            return weight;
        }
        set
        {
            weight = value;
        }
    }
    public string Color
    {
        get
        {
            return color;
        }
        set
        {
            color = value;
        }
    }

    // instance methods
    public virtual void MakeNoise()
    {
        Console.WriteLine("Animal is making noise");
    }

    public void Move()
    {
        Console.WriteLine("Animal is moving");
    }
}

As you can see there are some variables like type, weight,... but they are set as private, that means, we can only change the value for those properties inside of the class, we cannot save a value from other class (encapsulation). In order to change the value of our variables, we've created some public properties and inside of them we've set-up a "set" and "get" method which allow us to have a unique place to work with this variables from outside of our class in order to get and set the value we want. When a set or get from a property is raised we are actually pointing to the private variables in the top of our class. We also can define this properties as "readonly" avoiding the possiblity of stablish the value for a certain property.

At the end of our class you can see some public methods related with a normal Animal. Don't worry too much about the syntax, just try to focus on the meaning of those methods. When some of then is raised the instanced object of our Animal class will print on the console some text to know the method was executed.

3. Inheritance


As we already mentioned before, the main purpose of object oriented programming is model objects from real life, and inheritance has a main role at this point. It allows us to define certain properties and methods just once and then, other classes can inherit from them. When we inherit from another class we are getting his data and behaviours. We call super to the class that plays the father role and sub to the son class. It provides base functionality for similar objects and it helps developers to reuse code.

In our example, "MakeNoise" and "Move" are methods quite abstract because they are shared by all the animals in the world. Imagine we create a Dog class which inherits (sub) from our Animal (super) class, then, we will be able to access all the information in our father (properties and methods) and even change it to align with the way a dog moves or makes noise. To do this you just need to add the name of the father class on the right of your class name like here: public class Dog : Animal


At this point we have an empty Dog class but just with specifying the father class we will be able to access all the methods and properties from the Dog class. In the following example you can see an empty Dog class but when we instantiate that class we can get some methods and properties. They are  still placed into the Animal class but throw inheritance we are able to bridge that info.

// Empty class inherits from Animal
class Dog : Animal { }

class Program
{
    static void Main(string[] args)
    {
        // Tobby is our object from the Dog class.
        Dog Tobby = new Dog();
        Tobby.Color = "black";
        Tobby.Weight = 45;
        Tobby.MakeNoise();
    }
}

4. Polymorphism


What this rare word means is: change the behaviour of our classes. Is very useful when you work with inheritance because it allows the developers to modify the methods from the base class. For instance you can define new properties within the Dog class which not exist within our Animal class like "breed". Breed is a feature for a dog but not for an animal. For our example, in the Dog class, we would be able to override the "MakeNoise" method from the Animal class into something more specific for a dog: Console.WriteLine("Bark!!!"); To be able to do that you need to define your method as virtual within the father class and override it in the sub class. Take a look at the code below and the output of our application:

class Dog : Animal 
{
    // attributes
    private string breed;

    // properties
    public string Breed 
    {
        get 
        {
            return breed;
        }
        set 
        {
            breed = value;
        }
    }

    // We add a new method for our Dog which cannot exist in the Animal class
    public void WagTail()
    {
        Console.WriteLine("Dog wags tail.");
    }

    // Here we are changing the functionality of our MakeNoise() method.
    public override void MakeNoise()
    {
        Console.WriteLine("Bark!!!");
    }

}

class Program
{
    static void Main(string[] args)
    {
        Dog Tobby = new Dog();
        Animal myAnimal = new Animal();
        Tobby.MakeNoise();
        myAnimal.MakeNoise();
        // OUTPUT
        // Bark!!!
        // Animal is making noise
    }
}

Maybe this example is not very useful for an enterprise environment but imagine you want to create a new ERP for your company and first thing you want to do is model the different employees that are working currently. 

You can create a first a class called Employee which contains the basic data for every employee like: name, surname, telephone, ... and also functionalities like getDOB, getName, getPhone, getSalary. Then you can create new classes which inherit from your Employee like HhrrMen, SalesMen, Manager ... and within this classes you can add more information related with a salesman, for example, like: bonus, objectives, more functionalities with new methods like: getOffer, getBudget and finally override some methods (polymorphism) from the base class if you want to change their behaviour, you can change the getSalary method to also print the bonuses of your salesman.

...and that's it, I hope you enjoy and don't hesitate to leave a comment with your thoughts, Cheers!

MTA Microsoft Technical Associate (Exam 98-361) Core Programming

Index

  1. Core Programming
    1. Computer Storage
    2. Data Structures
    3. Algorithms
    4. Decision Making
    5. Repetition

1 Computer Storage


The way computers storage the information internally is well known by all of you probably. The word binary pops in your mind probably at this stage. The origin of this word comes just because of there is an electricity signal or not (one or zero). With big chains of this binary data we are able to represent the different characters and symbols that we use when speaking. These chains of zeros and ones are saved in the dynamic memory of our computer (Random Access Memory RAM) because that is the place where the processor is able to execute the code of any application. Our processor is not able to execute the code against the hard disc for instance, which is a long term storage.

This does not mean the developers create their apps just writing ones and zeros. They use to work with, what we call: compilers. The developer use particular instructions and syntax (programming languages: ruby, c++, java,...) depending of the compiler they are using, and this is responsible of transforms those instructions into binary data.



Computers deal with memory addresses where they save some information relevant for them to work properly. In order to write code successfully, first you need to understand some keywords: variable, constant and data types.

Variables: is a container which has a memory connection. It has a name and help us to access some information saved in memory in an easy way. It can be used to save, edit and retrieve values. Here is an example:

string CustomerName = "Roberto";

Constant: is similar to a variable but we need to assign his value when the constant is created. During program execution we are not able to change his value. There are two different types: constants and literal constants (like letter 'c' or the number '1', they never change, one will always be one). Constants are useful to save values that for example, you need to use several times in your code and also to understand better the code in the application. Example of constant in C#:

const int MondthsInYear = 12;

Data types: are part of every programming language. They help us to say to our application which kind of value we want to store in our variable. If the value is a number (int, float), a date (datetime) or just text (string) we will chose one data type or another. This data types help our computer to find out how to work with each of the different variables in an application, some examples:

int myAge = 30;         // Age is a number, we use integer data type.
string myAge = "30";    // Age saved as text.
string myName = "Mike"; // The name is text so we use string as data type.
double myHeight = 1,86; // Height is decimal so we use double instead of integer.

2 Data Structures


Here are listed some of the main data structures used in most typical programming languages. I have enclosed some examples in c# with the "OUTPUT" you will get in case of you decide to execute the code.

Arrays: they are designed to store different values but all the same data type. Arrays are collections of objects... but always the same type (numbers, text,...). Arrays is a kind of sheet which contains two columns: an Index and a Value. The Index always starts with zero. So if we want to access the first value in the Array we need to point to the position zero instead of position one. Arrays look like this:
Index    Value
0            Item1
1            Item2
2            Item3
3            Item4


// Array sample. We've created an array of datatype = strings
string[] myArray = new string[] { "Item1", "Item2", "Item3", "Item4" };

Console.WriteLine("Item at index 2 is: " + myArray[2]);
// OUTPUT => Item at index 2 is: Item3

Console.WriteLine("This is the contents of the array.");
foreach (string value in myArray)
{
    Console.WriteLine(value);
}
// OUTPUT:
// This is the contents of the array.
// Item1
// Item2
// Item3
// Item4

Stacks: are a LIFO (Last Input First Output) collection. Compared with a stack of paper on a desk, it provides a powerful and simple data structure. You "put" papers on the top of the stack (push) and "take" them off of the top (pop). Remember you cannot go directly to the first element in the stack, you need to pop all the elements before:



It's also the way a computer works, it has a list of instructions and when we need to execute a particular command, we push that command on the top of the stack and then we also push in the stack all the information (data, variables) that the command needs to be executed. This way, when our processor gets that command, all the information and variables were being collected already.


// Stack sample
Stack myStack = new Stack();
myStack.Push("Item1");
myStack.Push("Item2");
myStack.Push("Item3");
myStack.Push("Item4");
myStack.Push("Item5");
myStack.Push("Item6");

Console.WriteLine("Initial stack count: " + myStack.Count);
// OUTPUT:
//Initial stack count: 6

while (myStack.Count > 0)
{
    Object item = myStack.Pop();
    Console.WriteLine("Popped" + item.ToString() + " off the stack");
    Console.WriteLine("Stack count: " + myStack.Count);
}
// OUTPUT:
// PoppedItem6 off the stack
// Stack count: 5
// PoppedItem5 off the stack
// Stack count: 4
// PoppedItem4 off the stack
// Stack count: 3
// PoppedItem3 off the stack
// Stack count: 2
// PoppedItem2 off the stack
// Stack count: 1
// PoppedItem1 off the stack
// Stack count: 0


Queues: a collection of objects, accessed by queuing and dequeuing. Similar to a line at the motor vehicle license branch. If you think about it, is the same as a stack but instead of LIFO it's FIFO (First input First Output), example in C#:


// Queue sample
Queue myQueue = new Queue();
myQueue.Enqueue("Item1");
myQueue.Enqueue("Item2");
myQueue.Enqueue("Item3");
myQueue.Enqueue("Item4");
myQueue.Enqueue("Item5");
myQueue.Enqueue("Item6");
myQueue.Enqueue("Item7");
myQueue.Enqueue("Item8");

// Gets the first item
Console.WriteLine(myQueue.Peek());
// OUTPUT:
// Item1

Console.WriteLine(myQueue.Count);
// OUTPUT:
// 8

Object qValue = myQueue.Dequeue();
Console.WriteLine(qValue.ToString());
Console.WriteLine("Queue count is: " + myQueue.Count);
Console.WriteLine(myQueue.Peek());
// OUTPUT:
// Item1
// Queue count is: 7
// Item2


Dictionaries: a collection of objects that are accessed by using a key. Is pretty similar to an Array with the only difference that the values are accessed by a Key instead of an Index like you use to work when use a normal dictionary. Example:


// Dictionary sample
Dictionary myDictionary = new Dictionary();

myDictionary.Add("key1", "First Item");
myDictionary.Add("key2", "Second Item");
myDictionary.Add("key3", "Third Item");
myDictionary.Add("key4", "Fourth Item");

Console.WriteLine("Item represented by the key 'key3': " + myDictionary["key3"]);
// OUTPUT:
// Item represented by the key 'key3': Third Item

myDictionary.Remove("key4");


3 Algorithms


Consider an algorithm as a solution to a problem. To make it easier I want to show you an example from real life. Imagine when you wake up in the morning and prepare your breakfast... Pancakes yeah!


What we have here is all the steps you need to complete your pancakes showed throw a flow chart diagram (this kind of graphs are really useful to explain how your algorithms work): add eggs, some flour, add water and mix. Then you check the consistency and if it's too thick then you put more water and mix and if not, you need to put more flour, then water and mix again. If then the consistency is ok, you fried your pancakes, serve and eat. Finished.

That is the way a developer thinks when he is making a algorithm in one application. Of course, the solutions a developer wants to achieve with his algorithms are not like this example. A typical algorithm for instance is the Bubble Sort, which tries to put in order a chain of numbers by going two by two putting always the smaller in from of the chain and starting from the beginning until it reaches the end, here is the flow chart:



4 Decision Making


To be able to follow the previous flow charts we will need decision structures. This pieces of code help the developer to move the execution to the lines they are interested in. We have several decision structures but by now let's focus on these ones:


  • if: this statement evaluates a condition and if it's true, then the execution goes into the if statement.


// if sample
int condition1 = 1;
if (condition1 == 1)
{
    Console.WriteLine("The condition is true!");
}
Console.WriteLine("This executes after the if, regardless the condition.");

//OUTPUT:
// The condition is true!
// This executes after the if, regardless the condition.


  • if / else: similar to the previous example with the only difference when the condition is false then the "else" statement is executed and we don't need to take care about the first bunch of instructions. In this example the condition is always true because the value of condition1 is one, but if you change that value by 3 then the condition will be false and the second bunch of instructions will be executed inside the else {}


// if-else sample
int condition1 = 1;
if (condition1 == 1)
{
    Console.WriteLine("condition TRUE");
}
else
{
    Console.WriteLine("condition FALSE");
}



  • if / else if / else: grouping the two previous examples we get to if/else/if. You can join as much if/else as you want. In this example, none of the conditions are true so the third bunch of instructions inside of the last "else" will be executed ("Neither condition is true.").


// if-else-if sample
int condition1 = 1;
int condition2 = 2;
if (condition1 == 2)
{
    Console.WriteLine("condition1 is TRUE");
}
else if (condition2 == 1)
{
    Console.WriteLine("condition1 is TRUE");
}
else
{
    Console.WriteLine("Neither condition is true.");
}



  • switch or select case: imagine you have to compare a variable with a lot of different numbers, not just two or three. Instead of create a bunch of if/else/if statements is a good practice use the select case statement. Here below I enclose an example. Take a look at the break reserved word, this is used to not continue evaluating the variable with the rest of condition, when it's true pop out the select case. Besides there is an optional (you can include it or not) parameter at the end called "default", this is executed just when none of the previous conditions are not true and in our example tries to print the real value of the variable:



// switch sample
int switchCondition = 3;

switch (switchCondition)
{
    case 1:
        Console.WriteLine("Value is 1");
        break;
    case 2:
        Console.WriteLine("Value is 2");
        break;
    case 3:
        Console.WriteLine("Value is 3");
        break;
    case 4:
        Console.WriteLine("Value is 4");
        break;
    default:
        Console.WriteLine("Value is " + switchCondition);
        break;
}

5 Repetition


This is a point where the computers are really good, executing something one time and another... The bubble sort is something where we need to repeat or loop over one data structure to get the numbers sorted and when this happens finish and not continue looping.


Here are some examples:


  • for loop: this repetition structure tries to run a certain lines of code while a condition is true. Whenever that conditions evaluates to false the loop is finished and the execution will pop out the loop. Look at the following example with his output:


// for loop sample
Console.WriteLine("for loop");

for (int forCounter = 0; forCounter < 4; forCounter++)
{
    Console.WriteLine("forcounter is at " + forCounter);
}
// OUTPUT:
// forcounter is at 0
// forcounter is at 1
// forcounter is at 2
// forcounter is at 3

This statement initializes the forCounter variable to 0, then evaluates it in the forCounter < 4 and if it is true, the code line between the curly braces will be executed, then forCounter increases in one with the forCounter++ statement, at some point the evaluation of the forCounter variable will be false and the execution will pop out of our for loop, but imagine a loop where this condition is always true and the loop never finishes, this could be very funny in terms of coding when it happens to other developer hehehe.


  • while: is similar to the for loop but with small structural differences. We need to initialize our counter before the loop starts and we also need to increase it inside of the loop, where the whileCounter++ appears. We just write the condition close to the "while" statement like in this example here:


// while sample
int whileCounter = 0;
while (whileCounter < 3)
{
    Console.WriteLine("whileCounter is at " + whileCounter);
    whileCounter++;
}
// OUTPUT
// whileCounter is at 0
// whileCounter is at 1
// whileCounter is at 2



  • do while: pretty similar to our previous example for the while loop. Just check the following code where I've adapted the while loop into the do/while loop:


// do while sample
int doCounter = 0;
do
{
    Console.WriteLine("doCounter is at " + doCounter);
    doCounter++;
} while (doCounter < 3);
// OUTPUT
// doCounter is at 0
// doCounter is at 1
// doCounter is at 2
// doCounter is at 3

You probably already realised about the difference between while and do/while and it is just the time when the evaluation of the loop condition is made. That is why we got a different output between these two examples.


  • recursion: this is a little bit more complicated but has the same root as our previous examples. Recursion tries to loop over a function for certain number of times. The point is that you need to design that function to be able to stop at some point because you will be calling that function in order to get a final result. For example let's create a function which calculates the factorial of a number. For those who are not familiar with this mathematical process, factorial tries to multiply a group of numbers just by telling him the top limit, this way, factorial of 4 will be 4! = 4 * 3 * 2 * 1 equals 24. See the example below with the code to achieve the factorial of a number:


// recursion sample
long value = Factorial(10);
Console.WriteLine(value);

static long Factorial(int n)
{
    if (n == 0)
    {
        return 1;
    }
    return n * Factorial(n - 1);
}

We are trying to get the factorial of ten which is 3.628.800 by sending first 10 into our Factorial function, there, ten is compared to 0 and because is false we give back 10 multiplied by the call to the same function, but this time we will send to that function 9 instead of 10.

At this point we have this return: 10 * Factorial(9); waiting for the answer of the Factorial function. With that 9 we go again into the function, evaluate 9 and we give back that 9 and the answer from the Factorial but by 8 this time.

So if we concatenate these two first calls we will have: return 10 * Factorial( 9 * Factorial (8) ) ... and so till we call Factorial(0), because that's when we will give back 1 but without calling our function again. At this point we are not assigning that 1 into our variable: value, because what we're going to do here is coming back throw all the different Factorial calls that we've made, something like this:

Factorial(10 * Factorial(9 * Factorial(8 ... * Factorial(2 * Factorial(1 * 1)

Which is nothing more and nothing less than: 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1. I know this example could be more complicated but it turns really useful when you need to work with mathematical algorithms, you also can get a better understanding on how recursion works debugging the example provided..

That's all folks! I hope you enjoy this post and don't hesitate to leave a comment, doubt or claim :)

Cheers!