Cloud Hosting

How to: Adding Ruby Gems and Gem Sources

Introduction

Programming often involves repetitive tasks. Most programming languages give you some way to package common code, making it reusable across multiple applications. In this article, we’ll look at how Ruby solves the problem of code reuse in a repeatable way with Ruby Gems. We’ll also take a look at managing gem sources, giving you more options to install additional functionality libraries from various third parties.

.

Prerequisites

  • Ruby version – 2.1.2 or newer

Expanding Your App’s Capabilities

As your software code base grows more complex, you may find that you have to write the same code multiple times. This repetition is obviously inefficient since now any changes to that code need to occur in multiple places when you introduce a new feature or a bug fix. You can mitigate this issue by encapsulating the code into separate classes–which solves the reuse problem–but this solution only scales to a certain point. Once you start trying to add complex functionality–such as HTTP communication between different applications–you will often find yourself working in well-defined problem domains that have well-known solutions. So while it might be a good learning exercise to write your own solution to one of these problems, ultimately your application would be best served by using one of these pre-existing solutions.

Read More


How to Install IonCube Loader on Fedora 23

Jose Velazquez November 6, 2015 by under Cloud Hosting 0 Comments
Verified and Tested 10/3/15

Introduction

In this How-To, we will walk you through the install and configuration of IonCube on Fedora 23. The IonCube Loader provides additional security to your PHP files or websites. It is a module that encrypts basic PHP language making it more secure and more reliable.

Prerequisites

– You need a Fedora 23 server configured with a static IP address. If you do not have a server already, you why not try our super fast cloud hosting and spin a new server up in under 30 seconds.

– You will also need to have a LAMP (Linux, Apache, MySQL, PHP) stack installed. If you need assistance with configuring LAMP, see our related article here.

Installing IonCube on Fedora 23

To get started, log in to your Fedora 23 server via SSH or Console. If you are using the Atlantic.Net cloud service, note that they are setup with minimal installations to avoid having unnecessary packages from being installed and never used. If some software packages that you’re used to using aren’t installed by default, feel free to install them as needed.

Before we get started, let’s download tar so we can simplify the walkthrough. tar is used to create, maintain, modify, and extract archived files.

dnf install tar

Once installed, make sure that your server is fully up-to-date.

dnf update

Downloading ionCube on Fedora 23

For this tutorial, we are using the 64-bit version of ionCube. Use the wget command to get the most recent ionCube file from their website:

wget http://downloads3.ioncube.com/loader_downloads/ioncube_loaders_lin_x86-64.tar.gz

Extract the ionCube file by using the following command:

tar xfz ioncube_loaders_lin_x86-64.tar.gz

Alternatively, if you have a 32-bit system you can download the 32-bit version from the site:

wget http://downloads3.ioncube.com/loader_downloads/ioncube_loaders_lin_x86.tar.gz

Extract the 32-bit ionCube file with the following command:

tar xfz ioncube_loaders_lin_x86.tar.gz

Configuring ionCube on Fedora 23

In order to configure ionCube correctly, we must select the correct version according to the PHP version that is currently installed on your server. So let us verify the version of PHP that is currently installed on your system with the following command:

php -v
PHP 5.6.14 (cli) (built: Sep 30 2015 12:53:57)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies

Now, we have the correct version of PHP (in our case 5.6) we can run the following command to find the location of the extension directory of your version of PHP because this is where we will move the IonCube files later on.

php -i | grep extension_dir
extension_dir => /usr/lib64/php/modules => /usr/lib64/php/modules
PHP Warning:  Unknown: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in Unknown on line 0
sqlite3.extension_dir => no value => no value

(Note:On the test system we’re working from, the extension directory location reads is extension_dir => /usr/lib64/php/modules => /usr/lib64/php/modules. However, every version may have a different directory name, use the one that your version displays).

Now that you know which version of PHP you are running, and the location of your PHP extension, we can proceed with selecting the ionCube files that we need for our system. Run the ls (list) command on the ioncube folder to get that information.

ls ioncube
ioncube_loader_lin_4.1.so     ioncube_loader_lin_5.1_ts.so  ioncube_loader_lin_5.6.so
ioncube_loader_lin_4.2.so     ioncube_loader_lin_5.2.so     ioncube_loader_lin_5.6_ts.so
ioncube_loader_lin_4.3.so     ioncube_loader_lin_5.2_ts.so  LICENSE.txt
ioncube_loader_lin_4.3_ts.so  ioncube_loader_lin_5.3.so     loader-wizard.php
ioncube_loader_lin_4.4.so     ioncube_loader_lin_5.3_ts.so  README.txt
ioncube_loader_lin_4.4_ts.so  ioncube_loader_lin_5.4.so     USER-GUIDE.md
ioncube_loader_lin_5.0.so     ioncube_loader_lin_5.4_ts.so  USER-GUIDE.txt
ioncube_loader_lin_5.0_ts.so  ioncube_loader_lin_5.5.so
ioncube_loader_lin_5.1.so     ioncube_loader_lin_5.5_ts.so

Since our installed version of PHP is 5.6, then I will need to locate the 5.6 version of the ionCube Loader and copy it to the Extensions Directory that we identified earlier. This can be accomplished with the following command:

cp ioncube/ioncube_loader_lin_5.6.so /usr/lib64/php/modules

Once done, we must configure the php.ini file so that it knows where to look for the newly moved ioncube_loader file. Using your favorite text editor, open the php.ini file:

nano /etc/php.ini

At the very top of the file, add the following line:

zend_extension = /usr/lib64/php/modules/ioncube_loader_lin_5.6.so

Restart Apache so that the web server accepts all the configuration changes that were made with the following command:

systemctl restart httpd.service

Testing ionCube on Fedora 23

Our last step is to make sure that ionCube is now loading. You can run the following php -v command and will notice that a message stating ionCube Loader is enabled:

php -v
PHP 5.6.14 (cli) (built: Sep 30 2015 12:53:57)
Copyright (c) 1997-2015 The PHP Group
Zend Engine v2.6.0, Copyright (c) 1998-2015 Zend Technologies
 with the ionCube PHP Loader (enabled) + Intrusion Protection from ioncube24.com (unconfigured) v5.0.19, Copyright (c) 2002-2015, by ionCube Ltd.

This is the Zend Engine confirmation that ionCube Loader is currently enabled.

What’s Next?

Congratulations! You now have successfully installed and configured ionCube Loader on Fedora 23.Thank you for following along and feel free to check back with us for further updates.


How to Install LAMP On Fedora 23 (Linux, Apache, MySQL And PHP)

Brendan Bonner November 5, 2015 by under Cloud Hosting 0 Comments
Verified and Tested 11/05/15
LAMP Magic In Your Hands created by Walker Cahall

LAMP Magic In Your Hands created by Walker Cahall

Introduction

In this How-To, we will walk you through installing LAMP stack on a Fedora 23 server.  LAMP is the most common web server configurations on the web. LAMP is the framework for a broad collection of web-based software, like WordPress, Drupal, Joomla and other web-hosting platforms. We will be using Fedora 23 for our Linux installation in this how-to. Apache is our web server; MariaDB is our database management system, and PHP is our scripting language.

Prerequisites

A server with Fedora 23 installed. If you do not have a Fedora 23 server, why not spin up a lighting-fast SSD Cloud server.

Installing Lamp on Fedora 23

We are going to start out by making sure that our system is up to date with the following command:

dnf update

Hit Y and then Enter to when it asks “Is this ok [y/N]” during the updates.

Also, let’s update our firewall to allow HTTP and HTTPS traffic to our server:

firewall-cmd --set-default-zone=public
firewall-cmd --permanent --zone=public --add-service=http
firewall-cmd --permanent --zone=public --add-service=https
firewall-cmd --reload

We are now ready to install Apache.

Install Apache on Fedora 23

Install Apache by running the following command:

dnf install httpd

Hit Y and then Enter to when it asks “Is this ok [y/N]” during the install.

Start Apache with the following command:

systemctl start httpd.service

You are probably going to want Apache to start on boot; you can do that by running the following command:

systemctl enable httpd.service

Verify Apache is installed by typing http:// and your IP or hostname on your browser.

Don’t know your IP address? Run the following command:

ip addr show eth0
An example of the command ip addr show eth0 showing the ip of 192.168.100.10

An example of the command ip addr show eth0 showing the ip of 192.168.100.10

An example of ip addr showing the IP of 192.168.100.10

In this example we would put http://192.168.100.10 in our browser’s address bar.

 

The default Apache page for Fedora 23

The default Apache page for Fedora 23

 

Install MariaDB on Fedora 23

Install MySQL with the following command for to begin the install:

dnf install mariadb-server

Hit Y and then Enter to when it asks “Is this ok [y/N]” during the install.

Start the service with the following command

systemctl start mariadb

To have MariaDB start on boot, run the following command:

systemctl enable mariadb

You can then check the status of MariaDB to ensure it is running by using the command:

systemctl status mariadb

Set the MariaDB root password and secure MariaDB with the following command:

mysql_secure_installation

You will be asked a series of questions. The first will ask you to enter the MariaDB root password, we just installed MariaDB so there is no password,  just hit Enter. You will then be asked if you would like to set the root password. Hit Y for yes and then create a strong password of your choosing. For the rest of the questions, you most likely would want to just hit enter for the defaults for the most security. However, if there is something you need feel free to customize:

Running mysql_secure_installation for MariaDB on Fedora 23

Running mysql_secure_installation for MariaDB on Fedora 23

 

Install PHP on Fedora 23

We are finishing up LAMP install by installing PHP with the following command:

dnf install php php-mysql

Hit Y and then Enter to when it asks “Is this ok [y/N]” during the install.

We can verify the PHP  installation by creating a test PHP file in the HTML directory below with the following command:

sudo nano /var/www/html/info.php

Insert the following PHP code in the space provided by the text editor. Once done save and exit:

<?php
phpinfo();
?>

Restart the Apache service so that our changes take effect.

sudo systemctl restart httpd.service

Verify that PHP is working correctly by typing the following on your browser.
http://youripaddress/info.php

You should get a page similar to the one below, which will show the PHP version installed among other things.

An example of the info.php web page on Fedora 23

An example of the info.php web page on Fedora 23

It is an excellent idea to remove the info.php file as hackers could use this information to set up an attack against you. Remove it with the following command:

sudo rm /var/www/html/info.php

You can now add your site to the /var/www/html directory

What’s Next?

Congratulations on installing LAMP on Fedora 23. Thank you for following this guide and feel free to check back with us for further updates.


PostGIS: Case Study of France’s Mapping Agency

Sam Guiliano November 4, 2015 by under Cloud Hosting 0 Comments

What is PostGIS, and how is it used? Let’s take a look at the basics of this tool, how it is used by a major mapping group, and how to seamlessly adopt it yourself.

  • PostGIS – What Exactly Is It?
  • Case study – Institut Géographique National
  • Fast Access to PostGIS

PostGIS – What Exactly Is It?

GIS stands for geographic information system. This type of software is used to organize a dataset via geographical components so you can see the information within space. Essentially, you can request data from a database and have the information presented as a map. This tool may initially sound like it’s only useful for special cases, but datasets often contain critical geographic components, explains Margaret Rouse in TechTarget. Sample applications include meteorology, understanding sales volume in various regions, population assessment, and land-use analysis.

Read More


How to: Introduction To Programming – Getting Started

Bjørn Furuknap October 28, 2015 by under Cloud Hosting 0 Comments
Programmer RPG by Walker Cahall

Programmer RPG by Walker Cahall

How-To Series

This is part 1 of a 5 part series for Introduction To Programming

  1. Introduction To Programming: Getting Started
  2. Introduction To Programming: Your First Program
  3. Introduction To Programming: Variables, Types, And Manipulating Data
  4. Introduction To Programming: Flow Control
  5. Introduction To Programming: Object Oriented Programming

Help! I Have To Become a Programmer!

Let me just quote the late Douglas Adams immediately, because if you are the target audience for this article series, you may just feel a bit nervous right now:

Don’t Panic!

.
You’re going to be fine! I’ll make sure you are well prepared for the tasks ahead. By the end of this series, I’ll have introduced you to programming from a very pragmatic point of view. You will be much better prepared to handle basic programming tasks and understand code when it is thrust in front of you. You’ll understand how programs work and how to build them. You will have seen, if not mastered, many of the concepts of programming so that if nothing else you will know the basics of how these concepts fit into the larger picture of building software.

And it won’t hurt a bit. I promise.

So how did you wind up in this situation? If you’ve read this far, you probably fit into one of several characteristics that make you the perfect audience for this series of beginner programming articles here on Atlantic.Net. For example, you may be sick and tired of doing repetitive tasks when there should be an easier way to do the same thing multiple times. You may want to show that programming dude or gal you know that what they do cannot be that hard, or maybe you really just want to understand how to improve the latest WordPress release. On the other hand, you may just want to learn a bit about how to make machines dance to your tune.

Whatever your background, in this series, I will introduce you to programming. I will do so with a chosen set of tools and languages, not because these tools and language are by any definition “best” or “right”, but because they are simple to use and because learning tools and languages isn’t important in programming at all. Besides, you’ll have plenty of time to develop nearly religious affection for whatever tools or languages you prefer later in life.

As such, I’ve chosen to go with a language called C# (pronounced “See Sharp”) and using Visual Studio for a development environment. To follow along, you’ll need to download a few things to get the same or a similar experience as I show you.
.

Getting Ready

First, you need Visual Studio. Any version will do, but note that they all run on Windows, so you’ll need that.   If you don’t have Windows, you can fire up an Atlantic.NET Windows cloud server and use this.

Now, I’m using Visual Studio 2013, but you can use any variety back to Visual Studio 2003, and they’ll behave more or less the same for our purposes. Most likely, you will want to get one of the newer versions. Unless Microsoft radically changes Visual Studio’s look, any version you get will probably be the close enough to what I’m showing.

Go… Download. Install. Make sure you include at least C#. Other languages are completely optional. I’ll wait right here for you to finish.

Done? Great! Now, you’ve got all the prerequisites for this entire beginner series. Really. Visual Studio contains everything you need to have to start building software, and because it’s all very neatly integrated, it is also very easy with almost zero need for additional setup.

In fact, let’s build a program right now. Three simple steps and you can, technically, put “programming experience” on your resume. Just don’t hope to land any advanced development jobs.

Step 1: Fire up Visual Studio

There’s a splash screen. It takes a few seconds. It may ask you what development setup you want, in which case you can pick any, since it’s likely you don’t have a preference yet.

Step 2: Create a Console Application

When Visual Studio opens, you should see a start page that has a “Start” heading and a “New Project” link, as shown below.

Figure 1: New Project Link in Visual Studio

Figure 1: New Project Link in Visual Studio

Click that link and then browse, search, or find Console Application. Its location differs depending on the version of Visual Studio, but in my version, it’s under Windows Desktop. Select it, leave everything else default, and then click “OK”.

Figure 2: Console Application

Figure 2: Console Application

Visual Studio will take a few seconds to create your project, after which you’ll see the code for your first program, ConsoleApplication1.

Don’t worry about any of the code for now, let’s just get this beast running.

Step 3: Start

Pay close attention to the screen because what happens next happens fast. Hit the Start button where indicated in the menu.

Figure 3: Starting the Program

Figure 3: Starting the Program

What happens next is that a black screen appears briefly and then disappears. That’s fine; we’ll fix that in a moment, but for now, pat yourself on the back and update your resume because you have built your first computer program!

Before we move on and get our program to do something even mildly interesting, let’s examine what you have actually done already, because, despite the way it looked, a lot happened.
.

Under the Hood

Inside your computer is a CPU (Central Processing Unit), which you probably know is the main processing part of your computer. That CPU comprises billions of transistors, which in turn are controlled solely by the flow of electricity. It is a massively complex piece of engineering that has taken thousands of the brightest brains on the planet decades to develop.

The CPU, however, is rather useless on its own. It needs to have the right currents added at the right conductors to be able to do anything. Your job, as a programmer, is to provide it with that current, in the right spot, at the right time.

What you just did was exactly that. The code you see on screen, as simple as it is, is written in a language that is somewhat human-readable. Visual Studio takes care of converting that language into instructions for your CPU by sending your code over to a separate program called a compiler.

The compiler works as a translator between you and the CPU. It can take commands like “Show this on screen” and turn it into operations your CPU understands. This process generates a program, a portable and self-contained piece of software, that you can run at any time.

You have made such a program right now. It is an .exe program, and you can find it by right-clicking on ConsoleApplication1 in the Solution Explorer panel and choosing “Open Folder in File Explorer”.

Figure 4: Locating Your .exe File

Figure 4: Locating Your .exe File

Then, browse into the “bin” (for binary) folder and then into the “debug” folder. You should see your ConsoleApplication1.exe there, proof that you have indeed created your very first computer program, capable of controlling a massively complex computer chip that is the result of millions of hours of work from hardware engineers across time and space.

Figure 5: File Location

Figure 5: File Location

Go ahead, double-click it, and it will act the same way as when you ran it through Visual Studio: up will pop a black window for a brief moment and then disappear. You can take that program file, move it to a different computer, too, and run it–and if you have a compatible system, the program will behave the same.

Before we make any further changes, however, I’d like to point out a couple of important ideas here. What you have created is a binary executable file. A binary executable is usually built to run only on a single type of system. You cannot, for example, take that program file and run it on a Macintosh or a Linux machine without special preparation.

To accomplish platform independence when building software, you need to utilize different methods for turning your program code into instructions for the machine.

In our basic example, we’re relying on Visual Studio to send out program code into a compiler to generate a particular type of executable code. That’s fine for the purposes of learning to program because the concepts are similar across most platforms, and the code we build doesn’t really change that much if we want to build platform-independent code or code that runs in different types of programs.

For example, if you are building web pages, you may build ASP.NET applications instead. The approach to writing the code is very similar but what Visual Studio does behind the scenes produces a different type of executable code. In return, the executable code can run on multiple platforms as long as these support running ASP.NET code. So, for example, you can build code on Windows and run it on Linux using a runtime called Mono.

We won’t go into platform independence in this series, but I wanted to point this out because the way you write code remains very similar, and the concepts you will learn in this series apply to all approaches.

In fact, even if you go outside the Windows and .NET world, you’ll recognize the approaches to programming are very similar. This similarity is why I mentioned earlier that language and tools aren’t really important to programming. If you learn programming, the ideas span not just language, but platform, toolset, runtimes, and devices.

With this understanding in place, we can wrap up this initial article by adding some additional code to our program to make it do something more than just disappear.
.

Why, Hello World!

It is a tradition when learning new programming languages to build a first program called “Hello World!”. The program should do nothing more than print “Hello World!” in whatever way the program outputs text, optionally pausing to wait for the user to acknowledge that they have seen the text. So let’s build that now.

Go back into Visual Studio and take a look at the “Program.cs” file in the left-side pane. Don’t worry about what the code already in place does, but notice that there are curly brackets in lines 12 and 13.

Many languages use such brackets to enclose different parts of a program, and they must always match each left curly bracket (in line 12) to a right curly bracket (line 13). We’ll look more into this later, but for now, just know that the program code we’re about to write goes inside the brackets in lines 12 and 13.

Figure 6: Where To Insert Code Within Program.cs

Figure 6: Where To Insert Code Within Program.cs

Place your cursor to the right of the left curly bracket (as I have done above) and add a couple of blank lines. You can add as many blank lines as you wish; the compiler will just remove any empty lines before building the machine code from it.

Where you added the blank lines, add the following two lines of code:

Console.WriteLine("Hello World!");
Console.ReadLine();

Computers are notoriously bad at inaccuracies so make sure you get it exactly as written above, with the double quotation marks, the parentheses, and the semicolon at the end of each line exactly the way it is. Luckily, if you make mistakes, Visual Studio will often warn you by placing red squiggly lines where you make mistakes and will even tell you what mistake you made.

Figure 7: Example of an Error and the Red Squiggly

Figure 7: Example of an Error and the Red Squiggly

Once you have everything entered correctly, go ahead and click the Start button again. This time, you should see the text “Hello World!” inside the black window. The program should stop when you hit the Enter key.

Figure 8: Your "Hello World!" Program

Figure 8: Your “Hello World!” Program

Congratulations! You have built your first interactive program! Go, you!
.

Introduction To Programming Wrap-Up

In this first article, you’ve already learned a lot about how programming works, not to mention having built your first program! In the next part of this series, we’ll explain more about what you just did and start understanding some of the concepts related to input and output from programs such as these.

Now, don’t forget to save the program before you go out to celebrate with your celebratory beverage of choice. You’ve earned it!

How-To Series

This is part 1 of a 5 part series for Introduction To Programming

  1. Introduction To Programming: Getting Started
  2. Introduction To Programming: Your First Program
  3. Introduction To Programming: Variables, Types, And Manipulating Data
  4. Introduction To Programming: Flow Control
  5. Introduction To Programming: Object Oriented Programming

How to: Introduction to Programming- Your First Program

Bjørn Furuknap October 28, 2015 by under Cloud Hosting 0 Comments

How-To Series

This is part 2 of a 5 part series for Introduction To Programming

  1. Introduction To Programming: Getting Started
  2. Introduction To Programming: Your First Program
  3. Introduction To Programming: Variables, Types, And Manipulating Data
  4. Introduction To Programming: Flow Control
  5. Introduction To Programming: Object Oriented Programming

You’re Back!

It’s great to see you again, and I hope you have celebrated profoundly after completing the first article in this series at Atlantic.NET in which you built your first program and executed it while learning about how what you build turns from human readable code to machine instructions.

Don’t worry, if you haven’t read that article yet, you can do so now. I’ll wait right here for you to return.

In this part of the series, we’re going to explore that first program more and focus on understanding more concepts of programming and software development. Specifically, we’ll look at input and output, introduce you to a concept called object orientation, and explore how and why we want to hide away complex code using abstraction.

Let’s get down to business, shall we?
.

Digging into “Hello World!”

In the previous article, we built a very basic “Hello World!” program consisting of two lines of code that we wrote ourselves. There were additional code lines, but Visual Studio generated them for us, and they are specific for the type of program we are building and the language we are using, so let us not spend more time on them for now.

The two lines we did add, however, focus specifically on output and input so let us examine them more closely.

Console.WriteLine("Hello World!");
Console.ReadLine();

Ignoring the Console. (read: “console dot”) part of the lines for now, you can see that there is an instruction to the machine to write a line and then to read a line. In a console program or application like the one we’re building now, these are two of the primary ways to interact with the user; we output something on the console screen with Console.WriteLine and get input from the user with Console.Readline. The result looks something like Figure 1 below.

Figure 1: Console output

Figure 1: Console output

This console application is just one of many types of applications we can build. Different application types require different approaches to input and output. If we are building a simple web page, for example, there is no console from and to which we can interact with the user. The web page is just a static piece of text and perhaps some pictures. Although a program may generate it, it is still not very interactive in the same way we build interactivity in a console application.

Note: In the early days of the web, there was a method called CGI (Common Gateway Interface) that allowed you to put console applications like these directly onto a web page and interact with them through the URL.

.

An Example of Web Page Code

A web page has a completely different method of interactive behavior. Look at the following web page code, for example–and don’t worry if this is completely foreign to you:

<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>

This web page simply presents the user with a headline saying “Hello world!” and not much else, as below.

Figure 2: Hello World web page

Figure 2: Hello World web page

On its own, this web page–or even any web page–cannot do much. To create interactivity, browsers can interpret command instructions through languages like JavaScript to manipulate the web page in various ways, including manipulating the web page layout, content, and structure.

For example, below in Figure 3, I’m using JavaScript on an HTML page to display a notification box to the user. Note that I am using Visual Studio to edit the HTML page and the JavaScript too.

Figure 3: JavaScript alert on Hello World page

Figure 3: JavaScript alert on Hello World page

One way that a web page can retrieve information from a user is through web page forms. These may not look like your typical paper forms, but that’s the beauty of the web; it doesn’t need to be boring and daft, it can look stunning and enticing (though the configuration necessary to achieve a stunning and enticing look is beyond our scope here!).

Regardless of appearances, forms can retrieve specific pieces of information from the user that a browser then can send somewhere. If we have, for example, a program somewhere that can read the input from a web page, we can have the browser send the contents of the forms to that program.
.

Event-Driven Programming

Another approach is to use the form data combined with JavaScript to have the web page itself handle the data from the user. Rather than having the JavaScript always display Hello World, for example, we can easily have it display the user’s input into a form.

Figure 4: Dynamic JavaScript alert

Figure 4: Dynamic JavaScript alert

Don’t worry too much about the code here, but note that unlike our console application where the flow of the program is generally line by line from start to finish, in this web page we are using what is known as event-driven programming, by having code respond to events that happen. In the example above, the event onblur happens when the attention shifts away from the input box, and we can write code to react to that event and display the alert.

Regardless, you’ll quickly recognize a certain pattern here that crosses boundaries of platforms, languages, and frameworks. The program starts by presenting the user with a piece of information, and then the user somehow sends instructions to the program. In a console application, this exchange happens through commands such as Console.WriteLine and Console.ReadLine. On the web, this exchange occurs by presenting an HTML page and asking the user to fill in a form.

As a programmer, you’ll learn quickly that what you do as a programmer is very similar across all languages, platforms, and tools. The syntax may differ between languages, and you may have different approaches to how you think in terms of program flow, but behind it all, the computer that you command is the same. It is subject to the same logic regardless of which language you use to manipulate it.

Once you realize that, you may have your Matrix moment, where you see beyond the code and into the machine and the logic behind it and suddenly understand fully how to command the machine in any way you like, using any language, any platform, and any tool.

Before then, though, there’s much to learn. Let’s hop back to our program for a bit because there are some additional things I want to show you.
.

Classes, Objects, and Methods–Oh, My!

We’ll start with the “Console dot” part of the two lines.

Console.WriteLine("Hello World!");

The Console part is a reference to a static class included as part of the System namespace and….

Oh, wait… That makes no sense yet. I need to talk a bit about classes and objects first. I should probably talk a lot about classes and objects, but for now, let’s focus on a basic understanding of what object orientation is because it is prevalent throughout programming languages.

Object orientation is a programming idea that you should build programmatic representations of real life objects and then interact with those objects as if they were the real thing. This definition isn’t terribly accurate, but it serves us well enough for now.

Primarily, we accomplish this interaction with objects through two component types called properties and methods. The good news? You’re already using one of them: the method. In our program here, the WriteLine and ReadLine commands are the methods. Properties, which we won’t really cover in this article, describe what an object is, whereas methods describe what an object can do.

Methods in object orientation are attached to objects or, in some cases, to classes. We will learn much more about methods later in this series, but for now, think of methods as actions that objects can perform.

Further, you can think of the difference between classes and objects as the difference between a cake recipe and a cake, with the recipe being the class and the cake being the object. The class defines how you make an object, just as a recipe defines how you make a cake.

It is somewhat useless to have a recipe but never make anything from it, though. A cake, on the other hand, cannot exist without a recipe. As such, classes and objects, like recipes and cakes, exist in unison.

Where this analogy becomes a bit more complex is when it comes to what we call static classes. These classes, or recipes, are static because they exist as actual things. In fact, you cannot even create objects from them; they exist as recipes only and have static methods only. To complicate matters even further, we can have static methods on regular classes! Confused yet? Well, remember Douglas Adams:

Don’t panic!

.
In our cake analogy, a static method for a recipe may be something that isn’t related to the cake itself but also not necessarily to the recipe. For example, you may attach to the recipe a static method called PointMeToTheKitchen that will–I’m sure you can guess–give you directions to the kitchen. The cake can be baked in any kitchen, and the recipe isn’t dependent on being turned into a cake in any particular kitchen.

To be fair, a better–and yet more complex–situation would be if you have a static class called Baking that handles all the necessary things related to baking with a bunch of static methods, and that the PointMeToTheKitchen method would probably better fit there. In fact, we have that same usage with our current program.

So, to reiterate:
* You use classes to create objects the way you use recipes to create cakes.
* Objects have methods and properties that define what they can do and what they are, respectively.
* Classes can have static methods that exist outside of any object.
* Static classes exist outside everything and exist on their own. You cannot use them to create objects.

We’ll be spending far more time with object orientation towards the end of the series. For now, when I repeat that the Console part of our two lines is a static class, you know that it is a class that exists independent of any object and that it contains static methods, too.
.

Abstrating the Details Away

Look at our lines again:

Console.WriteLine("Hello World!");
Console.ReadLine();

Console is a static class. Its main purpose is to give you access to what you need to deal with the console just like a Baking class would be used to give you access to baking tools.

When we write a dot in C# and many similar languages, we are calling into the method, signified by the following parentheses, or a property. Effectively, we’re saying, “Hey, Console class, let me execute your WriteLine method, please”.

Note: Some languages may use different notation for this. For example in C++, you may use -> instead of a dot in certain contexts, and Perl 5 uses -> consistently.

.
Behind the scenes, the Console class will then, using the parameters we provide (a literal text string “Hello World!”), call into the current console window, do some secret voodoo, and make that console window print the text we sent it, literally “Hello World!”.

In the next line, we call into the same static class Console again, and this time we ask it to call its ReadLine method. In return, the program will instruct the console to wait until we hit the Enter key before advancing in the program. In our case, this input will complete the program and just exit.

We can get into the intricate details of how the console works, but it’s not really relevant at this point. Remember, we’re not here to learn console programming any more than we’re here to learn C#; we’re learning programming concepts. As such, I call it “secret voodoo”–although it certainly isn’t–simply because it’s far enough advanced to us in this context that it might as well be magic.

What you should know, however, is that behind the scenes, these two simple commands actually perform a huge number of tasks. For example, just to interpret the parameters you pass into the WriteLine method, the computer needs to assign a certain memory position to the string, load those characters into that string, and point the execution of the current program to that particular memory location.

The CPU then needs to read out all those memory bits, figure out in what context it is running, call into the operating system (which, in turn, will need to call into the specific hardware you have) to turn on or off the signals that turn each pixel on your screen to its respective color value. And this little excursion isn’t even a fully accurate or complete representation of everything that goes on.

All of these things happen because you wrote a few characters into Visual Studio and hit a button. This peek behind the curtain illustrates another very important principle in programming called abstraction. In short, we want to hide away the intricate details of an operation and interact with it through an easy-to-use method. For outputting content to the console, we hide all the nitty-gritty details into a method called WriteLine.

Two main benefits of abstraction are that we can write a lot less code and that, by not having to repeat the same code every time to achieve the same results, we write better code, too. Behind the scenes, the results we achieve with our simple WriteLine and ReadLine code may take hundreds of lines of code. Having to write all that code greatly increases the chances of making mistakes.

To be accurate, in our example here, it is the .NET team at Microsoft that hides the details for us. In return, they give us a greatly simplified interface with which we can program our applications. Shuffle the words in that sentence around a bit and you might even call it an Application Programming Interface, or API.

Other frameworks have APIs, too. For example, jQuery is an API that abstracts a lot of nitty-gritty details of how JavaScript interacts with content in a web page, like animations, form validations, content manipulation, and so on. OpenGL is an API that abstracts away the interaction with graphics hardware.

There are literally thousands of APIs that give you a way to perform complicated activities. Atlantic.NET has an API for managing your cloud servers, too, so that once you become familiar with programming, you can create programs that start, list, create, or terminate the instances in your Atlantic.NET account.

Note: The Atlantic.NET APIs require working with something called a RESTful interface, which is a bit beyond the scope of these introductory articles.

.

Your First Program Wrap-Up

You’ve had a lot to learn in this article, but now it’s time to take a break. We have discussed in depth how input and output works and given you an introduction to object-oriented programming. You have also learned about the importance of abstraction and how it helps us to avoid mistakes and to simplify our code writing. You have seen how web pages and console applications use different but similar approaches to input and output and had at least a cursory glance at a completely different programming approach called event-driven programming.

In the next article, we’re going to expand on our program by introducing variables and data types, and you’ll start to build a very simple guessing game using these concepts along with what you have already learned.

 

How-To Series

This is part 2 of a 5 part series for Introduction To Programming

  1. Introduction To Programming: Getting Started
  2. Introduction To Programming: Your First Program
  3. Introduction To Programming: Variables, Types, And Manipulating Data
  4. Introduction To Programming: Flow Control
  5. Introduction To Programming: Object Oriented Programming

.


How to: Introduction to Programming – Object Oriented Programming

Bjørn Furuknap October 28, 2015 by under Cloud Hosting 0 Comments

How-To Series

This is part 5 of a 5 part series for Introduction To Programming

  1. Introduction To Programming: Getting Started
  2. Introduction To Programming: Your First Program
  3. Introduction To Programming: Variables, Types, And Manipulating Data
  4. Introduction To Programming: Flow Control
  5. Introduction To Programming: Object Oriented Programming

Return for the Final Lesson

Great to see you again! I’m happy that you came back for this final article in this Introduction to Programming series at Atlantic.NET. You’ve learned a lot so far, and this article will be no exception.

In this article, we’re going to explore object orientation, which is a programming methodology where you build out objects that represent the things you want to model and then have those objects perform various tasks.

Want to know the best thing? You’ve already been doing it. Now you just need to understand what you have been doing, and you’ll be good to go.

.

Random Objects

First, recall that in the previous article, I ended by giving you two lines of code that I didn’t yet explain. Here again are the two lines:

Random random = new Random(); // Object orientation stuff
int answer = random.Next(10) + 1; // Give me a random number less than 10 and add one

The first line is the most unfamiliar one to us at this point. We’ll start with the new keyword, which is, well, new. What new does is instantiate an object. Instantiating means creating an instance of something, and in this case, we are creating an instance of a class called Random().

So this first line creates a new object from the Random() class and then assigns it to a variable of type Random and whose name is random. That’s a lot of randomness for a computer that isn’t random at all! This breakdown may help if you find that explanation confusing.

First, you have the variable type. So far we have used int and string types, so here we are introducing a new type–or, really, a class type–called Random.
Second, we have the variable name. When working with variables in earlier articles, we have used variable names such as input and value. Note that in this case, we’re using a variable name of random (we have made it lowercase to try to help you distinguish it), though it could be nearly anything you like, such as number or hey_there_human_can_you_get_me_a_cookie_please_kthxbye.
Third–and this is literally the new part–is how we assign a value to the variable. In earlier articles, we have set this to the output from the Console.ReadLine() method or a fixed value such as 8 or “Hello world!”. Now, we are using a slightly different approach because we are creating a new object with the new keyword.

.

Before we get to the next line, let’s do a little review.
.

A Review of Classes, Objects, Properties, and Methods

In object orientation, the two most important concepts are classes and objects. You learned about this briefly in the second article of this series when I explained that you can think of classes as templates and objects as what you create from those templates, for example, a cake (object) from a recipe (class).

A class, being the template for objects, defines what the objects will be through properties and methods. When you create an object using the new keyword, you get a unique object that has properties and methods as defined by the class.

For example, you may want to create a new cake from a given recipe. By doing so, you can say that you instantiate the recipe and get a cake object. The cake is unique from all other cakes made from that recipe, so changes you make to one cake do not affect any other cakes; putting frosting on one cake does not put frosting on all cakes.

Properties are the values that define what an object is. It may be easier if you think of a property as a sort of variable that is attached to an object. For example, for a cake object, the type of frosting or filling may be a property.

Methods define what an object can do. For example, a car can drive. You don’t really need to know how an engine works; you can simply tell the car to start, and the car will take care of what it needs to do to spin up the engine and get you on your merry way. One of the beautiful things about object orientation is that we don’t really care about the underlying workings of the method, nor do we have to. This is the concept of abstraction that we also discussed earlier.

Because we have already been discussing cakes, we can imagine methods for the cake such as AddFilling and WrapInPaper that would add or adjust the filling property or designate a cake as being wrapped in paper, for example.

.

You can often recognize that you are dealing with objects and classes by the use of periods or “dots”. For example, in the output of our program, we use Console.ReadLine() (spoken as “Console dot ReadLine”). The first part before the dot determines the class or object and the second part after the dot determines the properties or methods we wish to invoke.

How do you tell the difference between properties and methods? Most of the time, methods will have parentheses whereas properties do not. You can tell, for example, that the command Console.ReadLine() asks the Console class or object to invoke the ReadLine() method because “ReadLine” is followed by parentheses.

For properties, you will find that you interact with them much the same way you do with normal variables. You can perform mathematical operations, assign values, read values, and so on, just like with int and string variables. In fact, if you wanted to change up our game code a bit, you could set the properties for the foreground and background colors of the console as such:

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;

The addition of these statements will cause the text to be written in white on a blue background the next time you output something in the program, as seen in Figure 1 below.

Figure 1: White on Blue Console Text

Figure 1: White on Blue Console Text

You might have expected the entire window to be blue, right? We get only the output lines blue because we haven’t told the console to clear out any black background that’s already there. We can accomplish this change by calling the Clear() method on the console:

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();

With this addition, we get something along the lines of Figure 2 below.

Figure 2: Blue Console Window

Figure 2: Blue Console Window

In this example, you use object orientation first to assign values to properties on the console and then to ask the console to do something. This pattern is common in object orientation.

There’s one more thing regarding methods that you need to learn and that is the use of parameters. Fortunately, you have already used a parameter when writing text to the console using the WriteLine() method.

Parameters allow you to configure how a method should execute. For example, when you want the console to write something, you need to tell it what to write. You do so by putting one or more parameters into the parentheses following the method name.

Console.WriteLine(“this is a parameter”);

So far, we have used only fixed text to output something, but we can also pass variables, properties, or even entire objects into methods. For example, the WriteLine() method, can receive an int variable to pass to the console display the value of that variable.

int i = 99;
Console.WriteLine(i);

Exactly what you can do with the various classes and objects vary greatly. You should refer to the API documentation for further reference on what the capabilities of different objects are. Some development tools, such as Visual Studio, can also help you immensely by suggesting values based on what the methods want, or suggest available properties and methods when you start typing an object or class name.

In Visual Studio, for example, you can see all the properties of the console by typing Console and “dot”. Wait for a fraction of a second, and you should see a list of properties and methods and even documentation regarding what the various properties and methods do, as shown in Figure 3 below.

Figure 3: Visual Studio Intellisense Prompt

Figure 3: Visual Studio Intellisense Prompt

In Visual Studio, this feature is called IntelliSense, and if you do your development in Visual Studio, it will be one of the most helpful features you can use. Other development tools offer similar functionality, too.

Finally, there’s one special type of method in object orientation called a constructor. A constructor is a method called when you create an object with the new keyword. This method allows you to perform tasks such as initializing values for the object and is always the first method called in an object lifespan.

.

Back to Our Guessing Game

When we write Random random = new Random(); the Random() part is the constructor. Like other methods, it may accept parameters, which the method can then use to initialize the object’s properties.

Now we can bring it back to the second line we added to create the random integer for our game.

int answer = random.Next(10) + 1;

You may have noticed that when you started typing the text (unless you simply copied it, which is fine, too; just take a look at Figure 4), Visual Studio’s IntelliSense popped up and told you what the Next() method does, as shown below.

Figure 4. Random.Next()

Figure 4. Random.Next()

This hint tells you that the Random.Next() method needs a parameter of type int with a maximum value of “maxValue”. Note that the name stated there is not a type but more of a descriptor–you do not need to call your integer values “maxValue”.

Next, we learn that when we call that method with an int parameter, the method will return to us a nonnegative random integer. In our game, we assign that in a variable name of answer so we can refer to it later.

However, the documentation states that the value returned is less than the maximum. So, when we pass in 10, we get a value that is less than that, so it can only be up to 9. Further, the number returned from Next() is non-negative, so that means it can be 0, and we need a number between 1 and 10, inclusive.

What we get, in other words, when we call random.Next(10) is any number from 0 to 9. Adding 1 to that number means that it will become a number between 1 and 10 before we assign it to answer.

If we now revisit those two lines, it should make more sense what happens:

Random random = new Random();  
int answer = random.Next(10) + 1; 

First, we create a new object based on the Random class, which we call random. Then, we ask that random invokes its Next() method and pass the value 10 into that method. Then, when that method has executed, we add 1 to the result, and then store the value in an int called answer.

That’s it! You’re done! Now, each time you run this program, your user will have to guess at a random value you instructed the computer to generate.

.

See How Far You’ve Come

You’ve built and understood–hopefully–all the aspects of a simple console game. Throughout this series, you have learned many aspects of programming, from how programs execute, how to build applications, how you write code, what code to write, variables, loops, branches, objects, classes.

What you should know, however, is that what you have learned now is merely the foundation of what you need to know as a programmer. Whether you want to start a path as a developer or you just want to learn enough to impress your friends, the lessons in these articles should be a good starting point.

I hope you have enjoyed this series and if you are interested in exploring more. Make sure you check out the other articles in the Atlantic community, too. Wherever this series takes you from here, enjoy your programming! Be sure to check out Atlantic.Net’s market-leading cloud hosting solutions.

 

How-To Series

This is part 5 of a 5 part series for Introduction To Programming

  1. Introduction To Programming: Getting Started
  2. Introduction To Programming: Your First Program
  3. Introduction To Programming: Variables, Types, And Manipulating Data
  4. Introduction To Programming: Flow Control
  5. Introduction To Programming: Object Oriented Programming

How to: Introduction to Programming – Flow Control

Bjørn Furuknap October 28, 2015 by under Cloud Hosting 0 Comments

How-To Series

This is part 4 of a 5 part series for Introduction To Programming

  1. Introduction To Programming: Getting Started
  2. Introduction To Programming: Your First Program
  3. Introduction To Programming: Variables, Types, And Manipulating Data
  4. Introduction To Programming: Flow Control
  5. Introduction To Programming: Object Oriented Programming

Welcome Back, Aspiring Programmers!

In this article, we’re going to explore control flow and how you can use conditions, branches, loops, and other mechanisms to determine what happens in your program.

If you have not read the previous articles in this series, I strongly suggest you do so. We’re building on top of previous knowledge in all these articles, so it is important for your understanding that you know what we have already covered.

We have a lot to cover in this article, so without further ceremony, let’s get down to business.
.

Handling Exceptions

When we last left our program, we had three lines of code and a problem. The code looks like this:

Console.WriteLine("Guess a number between 1 and 10:");
string text = Console.ReadLine();
int input = int.Parse(text);

However, if we run this program and enter anything except a number when prompted, the program crashes because the compiler doesn’t know how to turn non-numeric text into an integer.

If you recall from last time, we get what is called an exception, and it is one of the ways we can control the flow of a program in a very specific situation, namely when an exceptional situation occurs.

I wanted to start with exception handling because it is the most complex and possibly confusing topic in flow control, so if you can understand what we do here, you will likely find the remaining concepts much easier to understand.

For exception handling in programming, we have two important ideas you must understand. The first idea is that you can ask your program to try something. The second idea is that if the computer fails at what it is trying, you can catch the problem and handle it.

These two ideas together work a bit like a tightrope walker with a safety net. A tightrope walker (your program) can perform as normal along the tightrope, in most cases. But if something out-of-the-ordinary occurs, such as a misstep off the tightrope (an exception), there should be a safety net to prevent the performer from plummeting to the ground (a catch to handle the exception).

With an understanding of exception handling, we can now begin to see a solution to our problem. We can ask the computer to try to parse the text into an integer, and if it fails–rather than allowing the program to crash–we can catch the mistake, tell the user, and ask them to try again.

Let’s see what that might look like in our code.

Console.WriteLine("Guess a number between 1 and 10:");
string text = Console.ReadLine();
int input = 0;
try
{
    input = int.Parse(text);
}
catch
{
    Console.WriteLine("Whoops, you didn't enter a number");
}

Our first change is that we are initially setting the int input to zero before we try to set it to the result of the parsing of the text input from the user. There is a specific reason I first set the value to zero and then set it to something else later.

Note that after the try line, the code we want to try is surrounded by curly brackets like these:

{
}

In C# and many similar languages, we use curly brackets to encompass or limit the scope of certain actions, operations, or even variable life cycles. Generally, variables only survive inside these brackets. When our code execution exits a set of these brackets, any variables inside it go away (sometimes called going out-of-scope).

You see the same curly brackets after the catch line, too, which is an instruction that whatever is inside the curly brackets should be executed only if we catch a mistake or an exception. Code inside curly brackets is often called a code block.

What this means is that if we had created the int input inside the try code block, then the variable would just disappear once we had passed the try code block, and we could no longer access it to check if it matches our secret value. I’ll work up an example from our code to show you what I mean. Note in Figure 1 below how I do not define the int input until we are inside the curly brackets of our try statement.

Figure 1: Variable Scope

Figure 1: Variable Scope

Oh, and notice that I have one line that starts with //. In C#, the double slashes indicate that whatever comes after that and until the end of the line is a comment that is not part of the program. The compiler will simply ignore such lines.

.
To try our program out, we can put a breakpoint inside the catch brackets on the Console.WriteLine line, and then execute our program. Enter a non-numeric input to check that rather than crashing, the program now steps into the catch code block, and then eventually displays the error message to the user, as you can see in Figure 2.

Figure 2: Exception caught!

Figure 2: Exception caught!

.

Conditions

Now, this code is rather useless as currently written because we’re reading in a value, but–except for telling the user if they make a mistake–we are not using the value for anything. You can try this and see that if you enter a number, say 7, the breakpoint isn’t hit.

To make our code useful as a guessing game, we need to test whether we have guessed the correct number. Here, we need to introduce a new flow control concept called a condition.

A condition is a code block that executes only if a certain rule or set of rules are fulfilled. We start such conditions with the word if and follow it with the rule or set of rules we are checking in parentheses, which is then followed by the code block we want to execute.

if (condition is met) 
{
    // execute this code block
}

There are, of course, very strict syntax rules for how we can format these conditions, and they aren’t necessarily as intuitive as they could be. For example, to compare values, you need to use two equal signs in C# and sometimes three in JavaScript. (Remember that using one equal sign is how you assign a value.)

if (value == other_value) // example value comparison

You can use a wide range of comparison operators and the rest are a bit more intuitive. For example, like in normal math, you can use greater than (>) and less than (<) and combine these with equal signs to create a greater than or equal (>=) or less than or equal (<=) conditions.

You can also create negative conditions. In many programming languages, you indicate a negative operator with the exclamation point (!), which is also often called a “bang”. For example, if you want to create a condition that executes if two values are not equal, you can write:

if (value != other_value)

You can also create multiple conditions by separating the different conditions using either && (double ampersands) for “AND” conditions or || (double pipes) for “OR” conditions.

if (value1 == other_value && value2 == other_value) … 
//means both value1 and value2 must be equal to other_value

if (value1 == other_value || value2 == other_value) … 
//means either value1 or value2 must be equal to other_value

Using a condition, we can now create a test to see whether the player has guessed the right number. Add the following lines after the last curly bracket of the catch code block:

if (input == 3)
{
    Console.WriteLine("Congratulations! You guessed correctly!");
}

This condition tests whether input (the value the user has entered) equals 3. If this condition is met, the game will display a congratulatory note, as shown in Figure 3.

Figure 3: Condition Met, Congratulations Awarded

Figure 3: Condition Met, Congratulations Awarded

If the user doesn’t guess the number 3, our program displays nothing more, and the application quits.

Remember that you can put breakpoints anywhere in your code to stop execution and see the results of what you are doing. We’ll be doing just that to see the results of the changes we’ll be making to our code from here on out.

.
It would be nice, however, if we could display another message if the user did not guess the correct number. Fortunately, conditions also allow for this behavior through the else keyword.

The else keyword must come directly after an if code block and states what should happen if the condition in the parentheses of an if statement is not fulfilled. To try this out, add the following lines after the if block:

else
{
    Console.WriteLine("No, sorry, that wasn't it. Better luck next time!");
}

Your entire conditional code blocks should now look like Figure 4 below.

Figure 4: Guessing Game Program Code with Conditional Code Blocks

Figure 4: Guessing Game Program Code with Conditional Code Blocks

When you execute your program, depending on whether you guess 3, you will get either a congratulation or an encouragement to try again. We call this type of flow control conditional branching because the program goes into one or another branch depending on the conditions you put forth.

Let us increase the odds a bit for anyone who does not know that the magic number is always 3. We will allow multiple attempts at guessing if the player does not guess correctly.
.

Going For a Loop

To accomplish this new functionality, we need to implement something called a loop. In programming, a loop is a block of code that executes repeatedly. Two very common loop types are for loops and while loops.

The best use for for loops are when you have a specific number of times you want something to happen. Let us start with that in our code and see where it leads us.

In a for loop, you need the keyword for followed by a parenthetical block that contains three pieces of information.

First, we define the starting environment for our loop, which includes variables we want to use to keep track of how many times our code block has executed. Second, we want a condition that determines whether we should continue the loop. Finally, we have the changes that we want to make to the loop conditions each time we execute the loop. Let’s look at an example.

for (int i = 0; i < 3; i++)
{
    // This code block will execute three times.
}

The important bit here is the first line. Notice the semi-colons that separate the three parts I mentioned. Here’s how each part breaks down:

int i=0; // Initialization: Creates an integer variable called "i" and sets it to 0.
i<3; // Condition: Continue executing as long as "i" is less than 3.
i++ // Change happening during each loop: "i" increases by one each time the loop runs.

The i++ notation is shorthand for writing i=i+1, which sets i to the value of i plus one–in other words, it increases i by one. You could have written i=i+1 as well, but this particular pattern is very, very common in programming, so I show it as a useful example.

Whatever you put into the block that follows the for loop declaration will happen as long as the condition is fulfilled–in this case, three times. For example, you can add a Console.WriteLine() inside the code block, and it will repeat three times, as in Figure 5 below.

for (int i = 0; i < 3; i++)
{
    Console.WriteLine("I am in a loop!");
}
Figure 5: "I am in a loop!"

Figure 5: “I am in a loop!”

We want to use this sort of loop to allow the user to have multiple tries to guess the correct number. So, we can wrap the entire program we have already written inside a for loop as described above. The code should now look like Figure 6 below.

Figure 6: Guessing Loop

Figure 6: Guessing Loop

Of course, if you guess the correct number before you reach three tries, it makes no sense to keep guessing. As such, we’re about to do a very bad thing….

Remember that the condition for the continued execution is that i remains below 3. So, if we want to stop the loop, we can simply increase i to 3 or more to stop the loop. If you add i = 3 inside the block that executes if the user guesses correctly, as shown in Figure 7 below, the game will stop once the user guesses 3.

Figure 7: Short-Circuiting the For Loop

Figure 7: Short-Circuiting the For Loop

You may not understand why this is a bad idea, and really, it is more of a philosophical argument than a technical one. However, it is an important argument so let’s make it.

A for loop is designed to execute a specific number of times. If you do not know in advance how many times you are going to execute the loop, then a for loop is a poor choice. There are other loop forms that are better suited to this task so using a for loop is picking the wrong tool for the job.

This argument may seem insignificant and pedantic. The program works fine as it is and does exactly what you expect.

However, the programmer’s mind is one that should strive towards clarity, and this example certainly isn’t clear. Looking at the first line of our current code, you think this is a loop that runs three times, but then we “cheat” the loop in the middle so that the loop may run anywhere between one to three times; there is no way for us to know. We have broken the clarity of what will happen, and that’s a bad thing.

Even if you don’t care about anyone reading your code, remember that as programmers, we work with machines that are incapable of understanding intent. It understands exactly only what we say. If we are unclear, the chance that we get unexpected results increases. We risk creating problems for ourselves down the line when programs become more complex.

As such, we need to find a better approach, and that better approach is a while loop.
.

A While Loop

A while loop executes while a condition is true. It doesn’t matter how many times that is: as long as the condition is true, the loop continues.

A while loop is simpler in declaration than a for loop and comprises the keyword while followed by an open parenthesis, the conditions, and a closing parenthesis.

while (condition) 
{
    // Code to execute
}

This execution can be very dangerous if you do not have clear conditions. If you make a mistake or do not properly account for all conditions and events, your program can run amok and grind your machine to a halt.

The danger lies in making sure that you invalidate the condition inside the code block when you want execution to stop. Otherwise, the loop will run forever.

Let’s change our for loop to a while loop and let it run as long as the user has not guessed three times. We can create this condition by declaring an int i=0; before the loop starts and then setting the value of i inside the loop. Update your code as such:

static void Main(string[] args)
{
    int i=0;
    while(i < 3)
    {
        Console.WriteLine("Guess a number between 1 and 10:");
        string text = Console.ReadLine();
        int input = 0;
        try
        {
            input = int.Parse(text);
        }
        catch
        {
            Console.WriteLine("Whoops, you didn't enter a number");
        }
        if (input == 3)
        {
            Console.WriteLine("Congratulations! You guessed correctly!");
            i = 3;
        }
        else
        {
            Console.WriteLine("No, sorry, that wasn't it. Better luck next time!");
        }
    }
}

Note that there is a mistake in this code, which shows how easy it is to create infinite loops. We are not increasing i unless we guess correctly! In other words, the player gets infinite tries, but there’s no way to stop guessing if they do not guess correctly!

Luckily, if you start this program, you know the answer is fixed to 3 so you can guess that, but barring that, you might have a huge problem on your hand.

I am saying this not to scare you from using while loops but rather to instill a sense of respect for their power. While loops are very powerful and useful but can also be dangerous if you do not take care.

To fix your issue, add i++; as the first line inside the while code block, immediately preceding Console.WriteLine("Guess a number between 1 and 10:"). Your code should now work as expected, be very clear, and give you a very basic but boring guessing game.
.

A Preview of Object Orientation

So what can we do to make this game even remotely interesting? I know, let’s make the secret number random!

I held back doing this because we need to introduce some new ideas to create random numbers. These ideas will become clear in the next article that deals with object orientation. For now, let me just give you the code and I will explain in detail what it does in the last article of this series.

static void Main(string[] args)
{
    Random random = new Random(); // Object orientation stuff
    int answer = random.Next(10)+1; // Give me a random number less than 10 and add one
    int i = 0;
    while (i < 3)
    {
        i++;
        Console.WriteLine("Guess a number between 1 and 10:");
        string text = Console.ReadLine();
        int input = 0;
        try
        {
            input = int.Parse(text);
        }
        catch
        {
            Console.WriteLine("Whoops, you didn't enter a number");
        }
        if (input == answer)
        {
            Console.WriteLine("Congratulations! You guessed correctly!");
            i = 3;
        }
        else
        {
            Console.WriteLine("No, sorry, that wasn't it. Better luck next time!");
        }
    }
}

There are two new lines now and one changed line. The new lines create a random integer answer between 1 and 10, and in the changed line we compare what the user guesses with that random answer.

Don’t worry about the random generation for now, I’ll explain that in the next article. But for now, congratulations, you are hereby officially a game developer in addition to being a programmer! Feel free to play the game now and see how you fare. You should beat the game, on average, 3 out of 10 times.

As an added exercise for yourself, why don’t you add a message after the game ends that tells the player what the secret number was? For now, though, let’s wrap up and go over what we’ve covered.
.

Wrap-Up

In this article, you have learned about program flow and how you can control the flow of your program. You have learned about exceptions for handling mistakes. You have learned about code blocks and conditional branching with if and else. You have also learned about loops with for and while.

In the next article, we will spend a little time polishing the game up, and we’ll also look into object orientation in more detail.

 

How-To Series

This is part 4 of a 5 part series for Introduction To Programming

  1. Introduction To Programming: Getting Started
  2. Introduction To Programming: Your First Program
  3. Introduction To Programming: Variables, Types, And Manipulating Data
  4. Introduction To Programming: Flow Control
  5. Introduction To Programming: Object Oriented Programming

How to: Introduction to Programming – Variables, Types, and Manipulating Data

Bjørn Furuknap October 28, 2015 by under Cloud Hosting 0 Comments

How-To Series

This is part 3 of a 5 part series for Introduction To Programming

  1. Introduction To Programming: Getting Started
  2. Introduction To Programming: Your First Program
  3. Introduction To Programming: Variables, Types, And Manipulating Data
  4. Introduction To Programming: Flow Control
  5. Introduction To Programming: Object Oriented Programming

Returning to Our Program

In the previous two articles in this series, you have, on average, written one line of code per article. In this one, we’re adding another line, but we’re also going to modify the lines we already have because now we’re going to start talking about variables and data types.

The object of this article is to teach you about variables and types and how to manipulate these to create a program that does more than just print “Hello World!”

We have a lot to cover, so get your fingers ready, and let’s get to it.
.

Using Variables

Our current program remains exceptionally simple with just two lines of code:

Console.WriteLine("Hello World!");
Console.ReadLine();

The first line outputs a piece of text to the console, and the second reads a line from the user. But where does this line that we entered end up? Currently, it just drops out into nothingness because we do nothing to retrieve it, so let’s change that immediately.

Change the second line so that it looks like the following:

String input = Console.ReadLine();

What we are doing here is saying that “String input” (whatever that might be) should be assigned to whatever comes out of the method ReadLine called on the Console static class.

We use the equal sign to assign values in C# and many similar languages. Whatever is on the left side of the equal sign is assigned the value of whatever is on the right side.

The two words in String input have different meanings. String denotes the type of value and input is the name we use to represent the value. What we are doing here is creating a variable called “input” that has a type of “String”. I will explain types later in this article.

In programming, we use variables to hold data in memory so that we can manipulate it easily. You use this in your daily life, too, without actually calling it a variable. Think, for example, of “Your phone”, which is simply an easy way to remember the name for a particular electronic device that may change over time. Or, consider “the US dollar to Euro exchange rate”. You don’t go around remembering that rate all the time, and it changes rapidly, so you probably find it easier to refer to it by name rather than value.

Variables allow us to refer to any particular piece of data by name instead of value, regardless of what the value is or whether it changes. In our program, the data is whatever the user enters before hitting the Enter key. The name we give that particular piece of data, in this case, is “input”, but we can call it different things. In fact, there’s a whole range of patterns just for naming variables, and you’ll probably be very confused by it later on in your career.
.

Debugging with Breakpoints

You can try this out now, but before you do, I want to show you a Visual Studio trick called a breakpoint. A breakpoint allows you to stop the execution of a program and see which line of code is executing–it will even allow you to step through the code line by line from that point.

To create a breakpoint, either move your cursor to the first line of your code and hit F9 or click in the margin to the left of the line numbers on the line where you want to set your breakpoint. If done correctly, the whole line should turn red, and you should get a red circle in the margin.

Figure 1: Breakpoint Added

Figure 1: Breakpoint Added

Note that the breakpoint stops execution before the line at which you set it. Also, breakpoints only work when you run your application through a development tool such as Visual Studio, so if you don’t remove your breakpoints before distributing your application, that’s perfectly fine.

Now, hit F5 or that Start button in the menu and watch your application fire up. Right after it does, Visual Studio should pop back up and show you the next line to execute in yellow.

Figure 2: Breakpoint Hit

Figure 2: Breakpoint Hit

At this point, you can control the execution step by step and observe the results in the console window. To go one step ahead hit F10 in Visual Studio. Bring the console window to the front and observe that your code has now stepped one line ahead, and there’s now “Hello World!” shown in the window as expected.

Figure 3: Next Command Line Executed

Figure 3: Next Command Line Executed

Note: Programmers often refer to this process of hooking into your code as it is executing as “debugging”. This process is one example of the kind of debugging you might do to verify your code is working as expected.

.
Step forward through your code once more in Visual Studio. Notice that as you do, the console window appears automatically. This event happens because the console needs input from the user when executing the Console.ReadLine() method.

Enter any bit of text you like and hit Enter. When you do, Visual Studio will pop back up because now that you’ve provided the input, execution can continue, and we’re still just stepping through the code.

In this Visual Studio window, I’d like to draw your attention to the bottom part of the screen where you should see a tab called “Locals”. If you cannot find it, you can open it by going to the menu and selecting Debug->Windows->Locals or hitting CTRL+D and then L.

Once you open the Locals window, you should see that there is a variable there called “input” that has a value set to whatever you entered in the console window. In my case, I entered “Hi there!”.

Figure 4: Debug Locals

Figure 4: Debug Locals

The Locals tab shows variables that are available to you to use in the current scope. However, before we start manipulating and using this data, it is important to understand the concept of variable types.
.

Variable Types: Static and Dynamic

You see, there are two approaches to what programmers call “typing”, and neither has anything to do with pressing keys on a keyboard. Both approaches have strengths and weaknesses. And no, I’m not going to tell you which is best; you will have plenty of time to determine that yourself, and, perhaps, you may come to understand why some programmers develop an almost fanatical preference for one over the other.

The two approaches are static and dynamic typing. C#, the language you are using in these articles, is a statically typed language, whereas other popular languages like JavaScript are dynamically typed languages. Let me explain the difference.

You noticed earlier that when we created the variable “input”, we decided that it was a String variable. String is a term that serves to indicate what type of data can go into the variable. You cannot add incompatible data to a variable because Visual Studio–or technically the compiler that translates your programming code into machine code–will object and refuse to cooperate.

A String is just a piece of text and can hold almost anything, which makes sense when we’re asking the user to enter any piece of text. However, there’s a potential problem when we want to start working with our data.

Let’s say that we want to ask the user to enter their age and that we want to limit certain functionality if the user is below age 13, for example.

How do you determine whether “Hi there!” is smaller than 13? You cannot, because there’s no way to do arithmetic on a piece of text. “Tomato” plus 45 doesn’t make sense.

A situation such as this one is why statically typed languages have different variable types. We can know whether we can perform arithmetic or other operations on the data before we even send the program to the user.

In statically typed languages, such as C#, VisualBasic, and Java, you must define in advance what a variable can hold, and you cannot create or compile your program without adhering to these rules. In return, you are guaranteed that you won’t be comparing Apples to 3.42 or trying to figure out whether it is legal to sell alcohol to a person who is “none of your business” years old.

In dynamically typed languages, you get no such guarantees. Instead, you just work with variables that can hold any type of data. An example of dynamically typed languages is JavaScript. In JavaScript, programmers need to check that the data they get is of an expected value because their code may crash if they try to add or compare “yes” to 18.

Note: You can actually add “yes” to 18 in most languages, depending on how you do it. You will most likely end up with “yes18”, though, which probably isn’t what you expect.

.
In statically typed languages, you will also find that all methods return a specific type of data–or, in some cases, nothing at all. For example, the Console.ReadLine() method returns a string value, so it works great to set our String input variable to the output from that method just like we did.

However, what will happen if we want to ask the user to pick a number between 1 and 10 because we want to use that number for something later? Let’s start building a simple game and look, shall we?
.

A Guessing Game Program

The game we’re going to build is a guessing game. We pick a secret number between 1 and 10, and then we ask the user to guess which number it is. We’ll make this game more advanced later, so for now, the user just gets one guess and thus has a 10% chance of getting it right. In fact, we’re not even going to test whether they are correct in this article because doing so would involve conditions and flow control, which are concepts we’re not going to learn yet.

First, the variable type for a number that does not have decimals is called an integer, or int for short. An int can hold very large numbers, usually limited by the CPU architecture type, with a 32-bit CPU holding integers up to around 4.4 billion. Beyond that, we can use other variable types. However, for our simple examples, a regular int will work well.

For all types of variables, we can assign simple values directly. For example:

int value = 10; 
string name = “Frank”;

We can also perform operations on variables, as long as they “make sense”. For example, you can add two integer values together.

int value1 = 10;
int value2 = 3;
int value3 = value1+value2;

The integer stored in the variable “value3” is 13 after the portion of code containing these lines runs through this point.

We can also assign values from the return value of methods. Let’s try just assigning the result from the Console.ReadLine() method into an int, shall we? If you haven’t already, stop the execution of your program. We are now going to update our two lines of code as such:

Console.WriteLine("Guess a number between 1 and 10:");
int input = Console.ReadLine();

When you do, you will get a case of the red squigglies (as shown below in Figure 5) and an error message in the Error list stating “Cannot implicitly convert type ‘string’ to ‘int'”.

Figure 5: A Case of the Red Squigglies

We get this error because the value that comes out of the Console.ReadLine() is a string, and the compiler cannot guarantee that it can convert what a user may enter into a number. A user might enter “NO!” for example, and there is no way to turn that input into a number.

There are, of course, ways around this problem. We can force the compiler to accept whatever comes in as being of a specific type. In fact, we can do this with any types. It is a process called casting.

When we cast variable types, the compiler will do its best to convert from one variable type to another. This cast may, for example, work if you have a decimal number and want an integer.

decimal decimalvalue = 3.14M;
int integervalue = decimalvalue;

The first line assigns the value 3.14 to the decimal variable called decimalvalue. The second line tries to assign that decimal value to an integer.

Note: The M is there simply as a hint to the compiler that we are creating a decimal value because, to add even more confusion to this point, there are several types of decimal values, including double precision and floating point values. While useful to know, none of these points are things you’ll need to worry about in this article.

.
If you enter these lines in Visual Studio, you’ll notice that even now, we get a case of squigglies because a decimal value doesn’t fit into an int value. If we tried, we would lose the .14 and be left with just 3 as the value of integervalue.

This behavior may be exactly what we want. In this case, we can cast the decimal value to an int, effectively forcing the compiler to accept the explicit conversion of a decimal value to an integer value. We do so by preceding the value with the type we want in parentheses. Compare these lines of code to the ones from above.

decimal decimalvalue = 3.14M;
int integervalue = (int)decimalvalue;

Now our Visual Studio squigglies will go away, and the compiler is happy. We’re losing some details in the numbers, but you might be confident that this is what you want.

In C#, the compiler will demand that you cast values if there is a chance of data loss, such as is the case if you go from a decimal to an integer value. However, it will gladly accept a compatible conversion when there is no chance of data loss. If you tried to assign an int value to a decimal type, for example, you’d get no quarrel from the compiler.

So far, though, we’re not really getting close to a solution to our problem. We can try to cast the string value coming from Console.ReadLine() into an int, but the compiler will complain that it cannot convert a string value to an integer automatically (as shown below in Figure 6) because there is no way to guarantee in advance that it is possible to turn what comes from the user into a number.

Figure 6: Error with Casting String to Int

Figure 6: Error with Casting String to Int

Fear not, because there’s a better way to solve this! The solution is using a static method to parse the string value into an integer, and it’s located right in the int type itself. As such, we can call on the int.Parse method, send it whatever comes in from the Console.ReadLine() method, and get an integer back out.

So, let’s update your program code to first prompt the user to enter the data, then retrieve the data into a string variable called “text”, and finally to parse “text” into an integer.

Console.WriteLine("Guess a number between 1 and 10:");
string text = Console.ReadLine();
int input = int.Parse(text);

Once you do, all of your squigglies should go away, and your program should execute as expected. Feel free to set a breakpoint after the last line to stop execution and inspect your variables. See what happens when you enter a number during the execution.

Figure 7: Valid Execution

Figure 7: Valid Execution

You’ll see that “input” now shows that it has a value of 3 whereas “text”, in my case, has a value of “3” (notice the double quotes; double quotes signify a string value).

But what happens if we enter something other than a number? Well, if you enter something like “Hello” instead of a number, the program will crash. In Visual Studio, the execution will stop and tell you about an exception, as shown below in Figure 8.

Figure 8: Invalid Execution

Figure 8: Invalid Execution

As programmers, we don’t want our software to crash, so we need to handle this bug. However, we’re going to leave that for the next article because it involves manipulating the flow of the program, and we’ve already covered quite a bit to get to this point.
.

Variables, Types, and Manipulating Data Wrap-Up

For now, it’s time to wrap up this third article, and despite writing only one more line of code, we have covered a lot of new material. Don’t worry, when I started learning this many years ago, there were many confusing aspects for me, too.

In this article, we have covered the concept of variables and looked at data types and when and why data types are important. You’ve learned about how to create variables and even how to turn data from one type into another through casting. You have learned about step-by-step debugging, breakpoints, and how to inspect available variables in Visual Studio.

You should also note that the things you have learned now are very common across languages and platforms, and I have taken care to introduce and explain concepts that vary, such as static versus dynamic typing.

In the next article, we will look at flow control so that you can learn how to control the execution of your program and check various conditions to determine what the program should do next.

 

How-To Series

This is part 3 of a 5 part series for Introduction To Programming

  1. Introduction To Programming: Getting Started
  2. Introduction To Programming: Your First Program
  3. Introduction To Programming: Variables, Types, And Manipulating Data
  4. Introduction To Programming: Flow Control
  5. Introduction To Programming: Object Oriented Programming

Cloud hosting is an IT Skeleton Key for Developers

Adnan Raja September 4, 2015 by under Cloud Hosting 0 Comments
  • Developers Hold the Keys to the Kingdom
  • How Cloud Benefits Enterprise Developers
  • General Strengths for Development
  • Developer-Friendly Cloud

Developers Hold the Keys to the Kingdom

Since innovation is so fundamental to success in today’s rapidly evolving economy, developers have an incredibly important role, creating the digital roadways to be traversed by consumers, businesses, and the public sector.

Developers may seem to be a tiny population, but there are actually 18.5 million people who are employed in development, wrote Megan Swanson in Wired. “In a sign of the growing recognition of the value of developers,” she said, “President Obama recently became the first sitting president to write a line of computer code, as part of the Hour of Code Campaign during Computer Education Week.”

Read More


New York, NY

100 Delawanna Ave, Suite 1

Clifton, NJ 07014

United States

San Francisco, CA

2820 Northwestern Pkwy,

Santa Clara, CA 95051

United States

Dallas, TX

2323 Bryan Street,

Dallas, Texas 75201

United States

Ashburn, VA

1807 Michael Faraday Ct,

Reston, VA 20190

United States

Orlando, FL

440 W Kennedy Blvd, Suite 3

Orlando, FL 32810

United States

Toronto, Canada

20 Pullman Ct, Scarborough,

Ontario M1X 1E4

Canada

London, UK

14 Liverpool Road, Slough,

Berkshire SL1 4QZ

United Kingdom

Resources