3 Tips & tricks for Kickass Developers in 2019

0

Hi,

For those looking for new ways to kick off 2019 with a bang with your .NET skills, keep on reading ūüôā

1. Leverage more LINQ in your C# code

Lately, functional programming has been a really hot and trending topic. C# is becoming more of a functional programming language to stay on par with the industry trends and one of the feature that it provides to developers since .NET 3.5 (2007). It’s been then for over a decade and truly makes your code more readable.

With LINQ, you can express directly your intent when iterating through your collection instead of using a looping construct. When looking at a Where statement, immediately developers will understand that your statement is meant to filter data as opposed to writing the equivalent code in a loop, you need to look inside the loop to understand what’s going on.

2. Document your code as you type it

Something I’ve witness so much in 2018 was the lack of documentation in code. And let me tell you, 3 to 6 months after writing your own code, if you don’t maintain it for a while and it is poorly documented or even, not documented at all because you think you will remember, that’s wrong.

Writing documentation for your code shows deep understanding of your product and respect for next people in charge of maintaining the code and adding more features to it. When you need to do a knowledge transfer, it’ll be a breeze because the documentation is already there to back everything you have built from the ground up. More to the fact, if only you touch that code, you will be thankful for helpful documentation whenever a bug hits the system and you’re responsible to go through those lines and figure out where that nasty logical bug is hiding and finding a way to get rid of it.

3. Write your methods side-effects free when possible

Your code should not have the need to create side-effect. From a certain point of view, your code should strive to always generate the same output with the same input. What does that mean? It means that let’s say you create a method to increment a counter every time you click on a button in a user interface, you have in fact a mutable state that’s based on user input. So from the first time I click on button to the 100th time I click on it, I shall never have the same output since the state keeps being updated.

I’m not saying to never write mutable code. That’s not what I’m trying to share as a tip. Mutability is unavoidable, but it can be contained and isolated. Most of your code can be pure, as in stateless. You can make sure to have readonly fields and properties. You can also provide APIs that give you solely readonly collections that you can’t update. Instead of updating a meaningless field in your class that’s used only in a single method of said class, simply make it a local variable of a method and update it there. From the client’s perspective, if your method has within itself mutability, but the same input generates the same output, you’re golden ūüôā

 

Kevin out.

Hidden .NET Gems – ReactiveUI

0

Hi,

Today, I’m going to talk about an open source gem in .NET for developing WPF applications for people who are interested in reactive and functional programming. To understand the work behind ReactiveUI, one mst understand Rx, or rather Reactive Extensions for .NET.¬†The goal of the syntax of ReactiveUI for read-write properties is to notify Observers that a property has changed. Otherwise we would not be able to know when it was changed as it’s mentionned on their website.¬†This is super cool because it allows you to abstract mutable state away from your user interfaces and express the idea around a feature in one readable place whilst improving application testability.

To have a better understanding why you should take a look at reactive programming, take a look at the following Youtube videos:

Soon, I’ll be building a Xamarin application with ReactiveUI. I’ll also weight the pros and cons of implementing the business logic with Akka.NET and F#. Keep on reading and you’ll see it briefly.

 

Kevin

 

 

FastOrder: real-time pizza order placement – Part 0

0

Hi,

I’m picking web and mobile development lately as they are super trendy at the moment. But it’s more than that. I’m a firm believer that in this profession, software development, we can’t keep still. We ought to ourselves to move way outside our comfort bubbles and try new things even if it’s a small proof of concept. We usually get to pick up more more insight on our own to approach problems and trying new techs might force us to follow the mindset of it. Doing so, we can see things in a whole new light. More than simply seeing things in a new light, we are in a profession where can do so much with just a computer, it’d be sad to keep doing the exact same thing over and over again. This brings us then to FastOrder.

C# 7.0 came out, ASP.NET Core looks hot for server development and I find that React looks a great tool for front-end development because I’m fond of functional programming. I was also thinking of mobile development and last year at a conference called “DevTeach” I was introduced to a programming language called NativeScript. This language enables programmers to do cross-platform development for both Android & iOS. Being that NativeScript uses Angular, I’ll get to work on both React and Angular and figure out what approach I prefer for front-end development.
FastOrder is an idea that came up to me. I didn’t want the usual slideshow web app or e-commerce thing that can usually find for introductory project for web development. I was gazing at my pizza one day and the idea popped in my head. What I’d like would be to showcase my own approach to design a pizza shop where clients would be notify right when cooking procedures are being completed and know where the delivery guy/girl is with their order. Being real-time, the information would always be present for the client as they request it. ¬†This initial post is me introducing the idea on my blog. The next step will be to do the initial setup for the server and the mobile app that managers, clients and delivery people will use. I plan to use my DevSharper functional library so definitely be on the look up for progress on that project as well.

A fun thing I thought that could be done, even though it may not be realistic, ¬†was to deploy a system where users could bet on long it would actually for the delivery. If the delivery people couldn’t manage to beat that time, that amount off the usual time needed to delivered the pizza would be deduced from the bill. Otherwise, the client would have to pay that extra 5% for instance.¬†More than this, we can use data science on the data collected from the platform to see which pizza is the most popular or verify whenever people order pizza the most.

We’ll see what we can get out of FastOrder,

Kevin

Tech questions 1-3: Linq

0

Hey guys,

This is a new series I will try to maintain to the best of my capabilities. I’m this awesome blogger who happens to be also a Microsoft MVP called Iris Classon. After her first year of programming, she started to ask and get answers for what she’d call “stupid question”. Why would she consider them as stupid ? Well actually they’re not. They’re basically good questions that any developer, being a junior or an architect ( well less likely if you’re an architect), to ask and get answers too. Her series is really good and it got me thinking that I should start my own too. This begs the question to the why I would feel the need to do something like this for my blog ? We all want to get better in our field of expertise. Software engineering being extremely broad, it can¬†get a “bit” confusing sometimes. My tech questions will lead me, I hope, to better myself and have not only a better understanding of the .NET framework, but any kind of technology that interest me right now or will interest me in a near/far future. I hope those questions will be helpful for the readers and followers of the blog.

To start the series, I will start with questions I have had in the past. Why ? It’s going to help me to stay on track and deliver answers for the tech questions on a regular basis. So let’s get cracking with LINQ. Why should we use LINQ in our C# solutions ? That’s quite a question. I cannot simply answer by the “well because it’s better that way.” and be done with it.

1. What is LINQ ?

The acronym LINQ stands for Language INtegrated Query. It allows .NET developers to query IEnumerable implementation to retrieve data as you would do in a SQL database. For instance, a list of int, which is a data structure implementing the IList interface which extends both ICollection and IEnumerable interface, ¬†can be queried that list to see what’s the average of the values it contains. To be able to use LINQ, you’re going to add System.Linq directive in your source file (or have Resharper tell you exactly what references are missing from your code).

using System;
using System.Linq;
//Our very first linq call ! ūüôā
public class LinqSamples
{
    public int AverageInts(List<int> list)
    {
        return list == null || list.Count == 0 ? 0 : list.Average();
    }
}

2. What are some benefits of LINQ?

Well there are many. You can bet that when you go LINQ, you won’t go back. ¬†One of the first benefits of LINQ in your code is that makes it more declarative. This means that it can almost be read as plain English (as far as code goes).

using System;
using System.Linq;
public class LinqSamples
{
    //Worst name for a method I agree haha
    public List<string> OrderStringStartingByA_AndByLength(List<string> list)
    {
         return list.Where(str => str != null)
                    .Where(str => str.Contains("a"))
                    .OrderBy(strElement => strElement.Length);
    }
}

So basically, the method goes through the List to first manipulate only not null strings. Then it filters out of the list strings not starting by the letter ‘a’ and finally,¬†orders the list by string length, from the smallest to the biggest string.

It can also reduce the complexity and the length code written using either a for or a ¬† ¬† ¬† foreach loop. In order to write the equivalent of what I’ve just wrote using only foreach loops, ¬†it would end up being something like :

using System;
using System.Linq;
public class LinqSamples
{
    //Worst name for a method I agree haha
    public List<string> OrderByA_AndLength(List<string> list)
    {
        var orderedList = new Lis<string>();
        foreach(var str in list)
        {
           if(str == null) break;
           if(!str.Contains("a")) break;
           orderedList.Add(str);
        }
        orderedList.Sort();
        return orderedList;
    }
    // See here : 9 lines vs 3 lines in the other example!
}

See here, we’ve been only using the type of LINQ called Linq to Object. The architecture was well thought; doing so, it lets pick up quite easily other types of LINQ such as LINQ to XML or LINQ to SQL.

3. What is a method group ?

In a few words, a method group is a set of overload methods resulting from a member lookup. This comes directly from the C# 3.0 Section 7.1.¬†EventHandler handler = MyMethod; then “MyMethod” refers to a method group. There could be multiple methods with the same name, but different signatures. The method group conversion creates a delegate calling the appropriate actual method. In short, a method group is the name of a set method. There might just be one. Using proper conversions, the compiler¬†will

A method group is the name for a set of methods (that might be just one).
The ToString function has many overloads – the method group would be the group consisting of all the different overloads for that function. It is a compiler term for “I know what the method name is, but I don’t know the signature”; it has no existence at runtime, where it is converted in the correct overload. Also, if you are using LINQ, you can apparently do something like myList.Select(methodGroup) so you can replace this code:

A method group is the name for a set of methods (that might be just one) – i.e. in theory the ToStringmethod may have multiple overloads (plus any extension methods): ToString(), ToString(string format), etc – hence ToString by itself is a “method group”. It can usually convert a method group to a (typed) delegate by using overload resolution – but not to a string etc; it doesn’t make sense. Once you add parentheses, again; overload resolution kicks in and you have unambiguously identified a method call.

Hope you have enjoy this!
Kevin

GSOC 2015 : From NRefactory 6 to RefactoringEssentials

0

Hey guys,

In spirit of my withdraw from the Google Summer of Code program this summer, I thought I’d do a piece of the project I successfully completed last summer. So what brought me to the program last year ? I spent a few weeks on working on a new thing in .NET called Roslyn. For my internship, I had to develop design semantic rules that my senior programmer was giving me. The first one I had to do was detect when developers were using “synchronization primitives” such Mutex, Monitor or Semaphore. Internally, they had developed something else to help better avoid dead/live locks. Acting this way, they could refactor previous projects and make sure to use their internal structures.

That one took me a while because there weren’t any useful (in my opinion) links that I could find on the subject (Winter 2015). The one I am most fond of was one where my senior found out that they were many times developers were making syntactically and orthographic errors. My job was to develop an algorithm which could pinpoint those mistakes in either variables/members/parameter/method names or even in comments. Part of my algorithm to match the errors was to used a dictionary having all the possible errors for a word as values and the correct word as the key. Doing so, I had part of the solution to develop the refactoring in case my code analyzer picked up anything.

So, back to the GSoC 2015 program. I saw the Mono Project project, NRefactory. The NRefactory library defined code issues and code actions which are basically code analyzer and code fix providers in Roslyn. The library was implemented using FxCop. But there were more traction at the time towards Roslyn. The idea behind the project was to port NRefactory 5 to version 6 using the Roslyn API. Code issues were define and the task was to reimplement them in code analyzers and define a proper code fix provider. Here’s below a non-exhaustive list of what I’ve implemented over the course the summer.

  • Rewrite if return to a simple return
  • Remove redundant code : invoking ToCharArray on a string
  • Remove redundant code : empty finally blocks
  • Remove redundant code : useless parameters in a method declaration
  • Making a member static once I’ve seen that value is never changed

So here’s a link to my GitHub¬†repo.

Kevin out.

 

 

Interesting project : Render stereoscopic 3D images using Kinect 2.0

0

Hi guys,

Last summer, I got into an interesting course entitled “Emerging topics in information technologies”. During the first part of the course, we focused more on¬†3D computer vision techniques and how to manipulate 3D images.Issues such as depth-image-based rendering were obscure and captivating enough to get me motivated throughout the summer semester.

In order to go even deeper in our discussions concerning 3D images, we were given Kinect 2.0 for half the semester to do a small project in WPF. The goal of the project was to produce a 3D image in real-time on the 3D glasses free TV Dimenco screen using the Kinect 2.0. Achieving this goal would let to have an hands-on experience with analyzing 3D images and their rendering using a given technology stack.

So this was the workflow.

  1. Connect on the Kinect
  2. Connect on both the depth and color sensors from the Kinect
  3. Acquire a frame from each of the sensors
  4. Process the information coming from the color frame
  5. Process the information coming from the depth frame
  6. Map the depth of the environment with the color to ensure to render 3D environment properly
  7. Correct physical differences between the two cameras in the Kinect 2.0
  8. Insert an image header on the top left corner of the Dimenco screen
  9. Render mapped result of the cameras on the 4K screen

And voila!

As easy as all this can sound, this was not a trivial student project. Having some experience with C# and .NET made the work a bit easier for me than for my classmates who didn’t have the chance to get some experience with the MSFT stack. Although, it still took me the whole four weeks and 25 hours of development, mostly doing some trials and errors to find the optimal solution that would show the perfect 3D image in real-time on the 4K screen. My last problem by the time I hand in the project was that I thought, personally that the rendering could had been sped up and optimize. All things consider, the project was a success !

You can learn more of my project and use the source code here

Kevin out.

 

Polymorphism: Empowering your objects

0

Hi there readers, So, we’re finally getting into the final pilar of object oriented programming, polymorphism. It’s a strange word at first, but we get use to it pretty fast.

What does the word polymorphism mean?

The root of polymorphism is traced back to the greeks. Poly means many and morphism mean forms. Basically, polymorphism gives an object the ability of having multiple forms. The fact that an object can have multiple forms means that while using inheritance of dependency injection (an advance topic which will be mentioned later), we don’t have to care what kind of object we’re calling during runtime. Having multiple forms means that while calling a certain function, in the hierarchy of objects, custom or not, it won’t matter which objects is being called. A real world example of polymorphism

Example

Everyone is a person, but each one as his own waking up routine at a specific time of the day:

  • As a waiter
  • As¬†a lawyer
  • As a student taking classes at nights

Method overriding? Virtual methods? What are those ??

Basically, virtual methods are found in the parent class. Virtual methods are behaviors in parent objects which can be overridden by their children. To make sure a method can be use by the children and be overridden, not only it must have the virtual keyword in its signature, but it should also have the protected keyword to make sure that only children can use it. This is a key concept in oriented object programming.

Easily, it’s possible to see why such a feature can be attractive for programmers. We love code reuse and we hate rewriting the same piece of code. Some readers might wonder why we hate rewriting code, right ? Well, it’s pretty simple in fact. It’s a bad programming behavior, YOU SHOULD NOT DO THAT ! Having to rewrite code will double or even triple or X factor time the amount of time you need to invest into maintaining the software.

Back to virtual methods. Having a basic foundation for most of the component in your system simplifies the work that must be completed. More than just this, when you’re overriding behaviors, it’s because you have a darn god reason to do this. in fact, while you’re testing your code or going over your software a few months after writing it, you’ll understand exactly why you did why you did. We usually do this because we have a good reason why.

public abstract class Human
{
   protected virtual void Greetings(string name)
   {
       Console.WriteLine("Hi, my name is {0}:", name);
   }
}

public class Doctor : Human
{
   public void GreetingPatient(string patientName,string doctorName)
   {
     Console.WriteLine("Hello {0}",patientName);
     Greetins(doctorName);
   }
   protected override void Greetings(string name)
   {
     Console.WriteLine("Hi, I'm doctor {0}. It's nice to meet you.",name);
   }
 }

Inheritance: More than just titles or money

0

Hi there readers,

We have talked about the first principle of object oriented programming in an earlier post. Now, it would be time to talk about the second one, inheritance. In the normal world, we talk about inheritance when one is about to receive some piece of land or a title from a loved one in his/her family. In the programming realm, it is more than this. In OOP, inheritance happens when a class is based on another class . This relation is special because they share the same implementation. Doing so, the class (B), who inherits from the other (A), share the same behavior that A has. But why would programmers act like this? Why not simply copy-paste the code from the class A to the class B? Those are actually good questions you might have had.

I don’t know if you remember from earlier posts, but I had mentioned that having a software which had a lot of code was not the goal you should think of while writing code. Sometimes, there won’t be any other way than having a software which has 10,000.0 lines of code and it is okay. But what we aimed for is having a software that is as maintainable as it can be. When I say maintainable, what I mean is that simply finishing a project won’t mean that it won’t change in one day or one month or five years. A query from a client can make your project change over time,and while you’re going through those changes, you don’t want to change all the code that was written before. Having maintainable code can be achieved through different methods, and by this I don’t mean the methods we usually write in order to complete operations. One of them is code reuse.

Like it was said earlier, class B inherits from class A. Inheritance is a mechanism for code reuse. Not only B gets all the same behavior that A has,¬† but B has accessed to all the attributes from the class A. Has much as inheritance is a good principle to follow while doing OOP, there is something that we must keep in mind while using inheritance. When a class inherits from another, what we’re trying to achieve is to specialize a concept by adding new behaviors to the class. Basically, we have what we call the superclass which has some states and behaviors that can be common for many situations. Then, we have the subclasses which inherits those traits but add new ones. For example, we could have the superclass Person which has a Weight, Name and Age. Now, we have the classes Student, Manager and Employee.

The Student objects, since inheriting from Person, already have Name,Weight and Age. But a student has more than simply that like a grade point average (GPA) or a student id (ID). Employee is also inheriting from Person but has the properties Salary and  Bonus. Finally, we have Manager which inherits from Employee but only overrides behaviors from Employee.

That’s a benefit from inheritance. Even though we inherits from a superclass, if we like the behaviors from the previous class but there is some things that need to be change, then we can override those behaviors in order to achieve what we truly wish to do. Down below, we’ll see in code exactly what I said we can do with inheritance.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
      static void Main(string[] args)
      {
         Person aPerson = new Person("Bob", 70.45, 23);// creating a person
         aPerson.SayingHello("Sarah");

         Student aStudent = new Student("Bobby", 1023453235, 3.98, 83.67, 22); //creating a student
         aStudent.PrintStudentAverage(); //Printing the student's average

        Employee anEmployee = new Employee("Tom", 5, 25.50, 23); //creating an employee
        anEmployee.SayingHello(aStudent.Name); //The employee says hi to the student
        anEmployee.PrintEmployeeSalary(); // Printing the salary of the employee

        Manager aManager = new Manager("Kevin", 43.45, 23, 4);
        aManager.SayingHello(anEmployee.Name);
        aManager.PrintEmployeeSalary();

        Console.ReadLine();//Press Enter to quit this application
     }
   }

   public class Person
   {
     private double _weight; //we define the fields by starting with the underscore (_)

     public double Weight
     {
        get { return _weight; }
       set { _weight = value; } //We'll let the weight like this because over time, it can change
     }

     private String _name;

     public String Name
     {
        get { return _name; }
        set { _name = value; }
        //Usually, the name of a person does not change, so we'll make it private.
       //This means that no one who can access an object of Person will be able to modify the name
     }

     private int _age;

     public int Age
     {
       get { return _age; }
       set { _age = value; }
     }
     //Constructor
     public Person(String aName,double aWeight, int anAge)
     {
       Name = aName;
       Weight = aWeight;
       Age = anAge;
     }

     public Person() { }

     public void SayingHello(String personName)
     {
        Console.WriteLine("Hi, my name his : {0}. It his a pleasure to make your acquantaince {1} !", Name, personName);
     }
  }

     public class Student : Person
     {
        private int _studentID;

       public int StudentID
       {
          get { return _studentID; }
          set { _studentID = value; }
       }

       private double _gpa;

       public double GPA
       {
          get { return _gpa; }
          set { _gpa = value; }
       }

       private int _numberOfClasses;

       public int NumberClassesForTheSemester
       {
          get { return _numberOfClasses; }
          set { _numberOfClasses = value; }
       }

       private int _numberOfCredits;

       public int NumberOfCredits
       {
         get { return _numberOfCredits; }
         set { _numberOfCredits = value; }
       }

        public Student(String name, int id, double gpa,double weight, int anAge)
        {
           this.Name = name;
           this.StudentID = id;
           this.GPA = gpa;
           this.Weight = weight;
           this.Age = anAge;
        }

        public void PrintStudentAverage()
        {
            Console.WriteLine("The average of {0} is {1}", this.Name, GPA);
        }

        private void ComputeStudentGPA()
        {
           //not how we actually do it, it is more as a behaviour to add to this class
           GPA = NumberClassesForTheSemester / NumberOfCredits;
        }
     }

    public class Employee : Person
    {
      private double _hourlyWage;

      public double Salary
      {
         get { return _hourlyWage; }
         set { _hourlyWage = value; }
      }

       private int _bonus;

       public int EndOfyearBonus
       {
          get { return _bonus; }
          set { _bonus = value; }
       }

       private int _yearInCompany;

       public int YearsInCompany
       {
          get { return _yearInCompany; }
          set { _yearInCompany = value; }
       }

       public Employee(String name, int yearsOfLoyalty,double salary, int age)
       {
          this.Name = name;
          this.YearsInCompany = yearsOfLoyalty;
          this.Salary = salary;
          this.Age = age;
       }

        public Employee() { }

        public virtual void ReceiveBonus(int bonus)
        {
            EndOfyearBonus = YearsInCompany * 2 * bonus;
        }

        public void PrintEmployeeSalary()
        {
           Console.WriteLine("This is the salary : {0} $/h of {1}", this.Salary, this.Name);
        }
     }
     public class Manager : Employee
     {
        public Manager(String name, double salary, int age, int numberOfYears)
        {
           this.Name = name;
           this.Salary = salary;
           this.Age = age;
           this.YearsInCompany = numberOfYears;
        }

        public override void ReceiveBonus(int bonus)
        {
           EndOfyearBonus = 3 * YearsInCompany * bonus;
        }
     }
  }

Kevin

Console Application: Managing a bank account

0

Hi readers,

We’ve seen quite a few things in the last few days. Now, it’s time to put all the fundamentals to good use. Today, we’ll create a console application in which a user can access the menu of its bank account. ¬†At first, the user will need to set up his password to get inside his account. Then in order to withdraw money, a user will need to make sure he had deposit money earlier before. In a situation in which he tries to withdraws more than he previously had, the bank will print an error message to tell him that the operation is impossible. If he tries to withdraw money that he owns, the console application will print the amount of money that was withdrawn and how much he has left. After each operation, the console application will always ask the user if he wants to quit, if so, he will only have to press the ‘q’ letter.

In this console application, we’ll mostly use methods to reduce the code that has to be in the main method. For the purpose of just looking how something like would work, we’ll start with a bank account with 2000$. This our first real console application, so we won’t go too deep. We won’t manage, for now, what happens if we were to withdraw more than what we have in our bank account, the console application will show a negative balance.


class Program{
  static void Main(){

       String confirmedPassword=null; //The first password of our user
       String userPassword=null; //The password we'll try to confirm with confirmedPassword
       char selectedAnswerFromUser='n'; //Selected answer from user after each operation
       char selectedOperationFromUser='0';
       int numberOfTimesTypingWrongPassword=0; //we'll verify if the user types the wrong password
       confirmedPassword=CreatePassword();
       while(selectedAnswerFromUser != 'q' ||                  numberOfTimesTypingWrongPassword &amp;amp;gt;=3 ||                selectedOperationFromUser != 'q')
             {
                Console.WriteLine(&amp;amp;quot;Please, enter your password&amp;amp;quot;);
                userPassword=Console.ReadLine();
                 if(ConfirmPasswordBankAccount(userPassword,confirmedPassword) == false)
             {
         while(ConfirmPasswordBankAccount(userPassword,confirmedPassword) ==false &amp;amp;amp;&amp;amp;amp; numberOfTimesTtpingWrongPassword &amp;amp;lt;3)
          {
             Console.WriteLine(&amp;amp;quot;Please enter the good password to access your account&amp;amp;quot;);
             userPassword = Console.ReadLine();
             numberOfTimesTypingWrongPassword++;
              AlertUser(numberOfTimesTypingWrongPassword); //won't do anything until we reach the value of 3
           }
          }else{
             selectedAnswerFromUser =         ConfirmOperation();
             if(selectedAnswerFromUser!='q')
             {
                decimal accountBalance=2000;
                decimal withdraw;
                decimal deposit;
                switch(selectedAnswerFromUser)
                {
                  case p:
                      PrintAccountBalance(accountBalance);
                      break;
                  case d:
                        Console.WriteLine(&amp;amp;quot;Please insert money to deposit&amp;amp;quot;);
                        String input = Console.ReadLine();
                        if(Decimal.TryParse(input,out deposit)
                        {
DepositMoney(balance,deposit);
                        }
                        else
                        {
                          deposit=0.0m;
                                   DepositMoney(balance,deposit);
                          Console.WriteLine(&amp;amp;quot;The balance did not change because you did not type numerical values&amp;amp;quot;);
                        }
                        break;
                       case w:
                           Console.WriteLine(&amp;amp;quot;Please inser the amount you wish to withdraw from your account&amp;amp;quot;);
                           String input=Console.ReadLine();
                           if(Decimal.TryParse(input, out withdraw)
                           {
                             WithdrawMoney(balance, withdraw);
                           }
                           else
                           {
                             withdraw=0.0m;
                             WithdrawMoney(balance,withdraw);
                             Console.WriteLine(&amp;amp;quot;The balance did not change because you did not insert a correct amount&amp;amp;quot;);
                            }
                           break;
                   }
                }
              }
            }
          }
        }
     }
   } 

 //Creates the password for the bank account
 static String CreatePassword()
 {
   String aPassword= null; //initialize the string to null, it has to value for the moment
   Console.WriteLine(&amp;amp;quot;Please, insert a password for your bank account&amp;amp;quot;);
   aPassword = Console.ReadLine();
   return aPassword;
 }

 //Will make sure that we enter the good password
 static bool ConfirmPasswordBankAccount(String firstPassword, String secondPassword)
 {
 return secondPassword.Equals(firstPassword); //Verifies if the two password are a match, if yes, return true. Otherwise false
 }

//Alerts a user after 3 type he types the wrong password
 static void AlertUser(int numberOfErrors)
 {
    if(numberOfErrors &amp;amp;gt;=3)
    {
      Console.WriteLine(&amp;amp;quot;There is something wrong with your bank account. You cannot access your bank account today.&amp;amp;quot;);
     }
 }

//Method which will confirm what operation the user wants to achieve
static char ConfirmOperation()
{
   char answer;
   Console.WriteLine(&amp;amp;quot;If you wish to continue, please press c. Otherwise, press q&amp;amp;quot;);
   answer = Console.ReadLine();
   if(answer != 'q' || answer != 'c')
   {
     while(answer != 'q' || answer != 'c')
     {
         Console.WriteLine(&amp;amp;quot;Please press either c or q to pursue with this software&amp;amp;quot;);
         answer= Console.ReadLine();
      }
     }
   else{
        Console.WriteLine(&amp;amp;quot;To print the current balance of the account, press p. To deposit money in the acocunt, press d. To withdraw money from the account, press w. To quit, press q&amp;amp;quot;);
        if(answer!='p' || answer!= 'd' || answer !='w' || answer !='q')
        {
           while(answer != 'p' || answer !='d' || answer!='w' || answer !='q')
           {
              Console.WriteLine(&amp;amp;quot;Please enter either of the following : q, c,p or w&amp;amp;quot;);
              answer=Console.ReadLine();
           }
        }
     }
 return answer;
}

static decimal DepositMoney(decimal balance, decimal moneyToDeposit)
 {
   balance+=moneyToDeposit; // The += operator is equal to say              balance= balance+moneyToDeposit;
   PrintDepositMoney(moneyToDeposit); // Prints what we've deposited

   PrintAccountBalance(balance); //Prints the new balance

   return balance;
 }

 static decimal WithdrawMoney(decimal balance, decimal moneyToWithdraw)
 {
   balance -= moneyToWithdraw; //Substracts money from the account balance

   PrintWithdrawMoney(moneyToWithdraw); //Prints the money we wanted to take from our account

   PrintAccountBalance(balance); //Prints the account new balance
 return balance;
 }

static void PrintAccountBalance(decimal balance)
 {

   Console.WriteLine(&amp;amp;quot;This is the current balance : {0}&amp;amp;quot;,balance); //Prints the accounts current balance

 }

 static void PrintDepositMoney(decimal deposit)
 {

   Console.WriteLine(&amp;amp;quot;You have deposit this in your account : {0}&amp;amp;quot;,deposit); //Prints the money we wished to insert in our account

 }

 static void PrintWithdrawMoney(decimal withdraw)
 {

    Console.WriteLine(&amp;amp;quot;You have withdraw this from your account : {0}&amp;amp;quot;, withdraw); //Prints the money we wished to take from our account

 }

Kevin

Programming basics : Methods

0

Welcome reader,

We’ve gone through a lot of the core fundamentals of programming with C#. We’ve seen how to evaluate conditions in our program flow and different ways to repeat a block of code with the help of loops. We’ve seen different notions that can help us to really understand how a software program works with the basics.

At first, when we create a console application, we dwell in the fact that the software application has X lines of code. Sure, having a lot of code seems fun, we look like we know what we’re doing. As fun as it may look, a lot of code is really hard to maintain. While we may think that as soon we’re doing writing a software that it’s done, we may have to come back in a few days or months to improve its functionality.

But that’s not the topic of this post. What we’ll learn today is to create methods. Using methods can reduce the code we need to have in the main method, which was seen in a previous example. A software program runs from the main method which will do exactly what our program needs to do. Sounds weird huh ? Code can exist outside the main method, but to be used, the code must be called in the main method.

Basically, a method helps us to not have to repeat code, and that’s something we should always try to achieve while we are developing something. Why would we want to do that ? Because if a piece of code has a bunch of errors, if we¬†duplicate it in several places, we’ll have to look for all those pieces and correct what was wrong. That is not a good practice, we¬†should aim to not do that.

Methods can be simple, we could only need something which would take the name of a person as an input and print a welcome message. Like this


static void PrintWelcomeMessage(String personName)

{

    Console.WriteLine(&quot;Welcome in this software application, {0}&quot;, personName);

}

With methods, the naming convention changes. The first letter is upper-case. Moreover, the first word of the method has to be a verb, it shows exactly what the method is trying to achieve. In the previous example, the method is “PrintWelcomeMessage”. It’s easy to understand that the method is printing a welcome message and takes a parameter, a string data type. For now, we’ll won’t focus on the static keyword.

More than just the naming convention, methods, as it was mentioned earlier, can take, what we call, parameters. Sometimes, they don’t. Parameters are values that are placed inside the parenthesis. We have to define the type of the parameter and give a name to the variable, like we always have done before.


static void PrintWelcomeMessage(String personName, int ageOfPerson)

{

    Console.WriteLine(&quot;Welcome in this software application, {0}&quot;, personName);
    if(ageOfPerson&gt;18)
    {
       Console.WriteLine(&quot;You are a minor&quot;);
    }else{
         Console.WriteLine(&quot;You are not a minor&quot;);
    }

}

We haven’t discussed another keyword that has appeared in this post, “void”. Void means that the method won’t return any value after it has reach its end. When we’re using methods, we can decide if we want a method to return something, like the result of a computation. We’ll try out a class(classes will be discussed at length in a later post) which is given by the .NET framework, Math. Thanks to this previous class, we can use different math skills which we could have learned before such as square root, sinus or power.


static double[]  ComputeDifferentValues(int a, double b, double c)

{

     double[] myMathComputedArray =  new double[5];

     for(int i=0;i&lt;5;i++){

        switch(i){

          case 0:

                myMathComputedArray[i]= Math.sqrt(a+b+c);  //This will compute the square root of(a+b+c)

                break;

          case 1:

                myMathComputedArray[i]=Math.pow(a,b); //This will compute a power b

                break;

          case 2:

                myMathComputedArray[i]=Math.Abs(a-b-c);//returns the absolute value of a double floating-point number

                break;

          case 3:

                 myMathComputedArray[i]=Math.Ceiling(b);//returns the smallest int (integer) value that is greater than or equal to the double value that was passed as a parameter

                break;

          case 4 :

                myMathComputedArray[i]=Math.Sin(a); //returns the sine of the given angle

                break;

        }

     return myMathComputedArray;

}

As we could have seen in the last code sample, when we perform any kind of operation and we want to have it later, we have to return what we which to have. In this case, we used a switch to store different values in an array. When we were done, we used the return keyword, which return the variable we which to return we need it.

We have covered basics to some point. There is a lot we need to know before we can get better. But now, with what we know at the moment, a lot can be achieved. ¬†We’ll see how to create console applications in order to resolve issues with all we’ve seen so far in later post such as creating a menu for a user who wishes to withdraw money from his bank account or how to manage an inventory.

Motion tracking : Leap motion

0

Hi,

Yesterday, I’ve just acquired some tech device which I’ve been looking forward for quite some time. It is a motion tracking device, called Leap motion.

.

download (4)

This device is quite powerful. By hooking up the device with your computer, you’ll be able to control your computer without the need of a mouse. It’s a tiny device with huge possibilities. The device can track both of your hands at an incredible speed. There are application in the app store for leap motion, with which you can can truly explore the device without needing to touch anything. You’ll see an example of an application in Airstore below :

tech_leap_motion

What really attracts me with the device is that I can develop my own application with it. There are several languages that are supported, but I focus on C# for the time being. But trying other technologies is part of our life as developers, so I’ll try to use other languages if possible.

When I’ll get more experienced with the device, I’ll start a mini series in which I’ll show you how to create your own first application with Leap motion. Just remember, the code won’t work without acquiring a device for yourself !

Kevin

Programming basics: what are strings ?

0

Welcome reader,

When we first talk about, it was mentioned that the String data type were to be discussed in a later post. So what exactly are String ? If you remember, we have the char data type, which is used to store a single character inside a char variable. Sometimes, we need to manipulate more than just one character. What previous programmers did to get around this issue was to use Arrays.

Arrays can really simply your work when you have to store a lot of information into your program. You have to look at arrays like entities in which you can store multiple variables of the same data type in a single structure.

In programming,  an array type is use to describe a collection of elements of the same data type like it was said before.  Each element in the array can be access with identifying keys (indices). Usually, when we have a ten values that we want to store, we start counting from value 1 to value 10. In computer science, we start counting starting from 0.  A quick trick to know the last identifying key of your array would be to take its length and reduce it by one. The length of an array is defined as how many elements it can possibly store.

This is how arrays works :

Array in Java Comparision

Something must be kept in mind while we’re using arrays : they are static. STATIC. Usually, when we use variables, the value that is stored in the variable can be modified at any time. When we initialize an array, we either directly store the values it will hold or we give the maximal length of the array. If ever we were simply initialize the array with its maximal length, every value in the array will either be undefined (null) or 0. Null values will be aborted in a later post.¬†We’ll see below how to do such things.

arrays


//this is how to initialize an array of int

//With a maximal length of 10

int[] anIntArray = new int[10];

//the new operator can be omitted if an initializer is provided

int[] arrayOfNumber = {1,3,5,7,9,11,13,15,17,19};

//once we initialize an array, its maximal length can't be CHANGE !

//but the values that are stored can be modified.

//Storing values in an array can be achieved with the help of their indices

anIntArray[0]=1;

anIntArray[1]=2;

//so on and so on until we reach the last indice

//Storing values can be achieved with the help of loop

//Example with a for loop and using the size (maximal length) of the array

for(int i=0; i<anIntArray.size();i++)

{

anIntArray[i]=(i*2)+3;

//Accessing the indices of the array to store a value, one at a time

}

Arrays have a lot of potential when we are developing a software application. In fact, as it was mentioned before, the programmers of the old had to use char array to store what have become String value. We’ll see an example how to create a char array and showing the values of the array for the user.

4

char chABC[26]= {'a','b','c','d','e','f','g','h',i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

for(int i=0;chABC.size();i++){

Console.Write(chABC[i]);

}

Now, we can directly manipulate the String class ( more on classes and null later). ¬†Doing so, we can directly store input from the end-user like a name ¬†or an address. We can also have information which will never change to present to the end-user such as “warning, you are entering a dangerous zone, please make sure you know what you’re doing or get out of here.”

What’s particular with the string data type is the following : it is immutable. That’s kind of big word for beginners and it is somehow kind of hard to understand at first. Like arrays, strings cannot be modified. But not in the same way as arrays. When a string data type is initialized, it holds a certain value. If along the way, a programmer was to modify the same string variable, it would not cause any problems. But, it would be as if the programmer created a new string. A string only points to certain memory at a time, if the value is modify, it will never be the same string even though it is the same variable. ¬†After a while, what is called extension methods are used to modify data type that are immutable such as string. This is a more advanced topic and will be discussed at length in a later post. We’ll see below an example how of to initialize a string variable


string ourFirstString="This is a string variable. We'll be able to show text with it to end-users of our software application";

Console.WriteLine(ourFirstString);

Kevin

Programming basics : Using loops

0

Welcome reader,

This blog post will cover the use of loops. Loops are used to repeat the same operation(s) at least once. Usually, most programs you can think of will need this kind of functionnality. We can use loops to go through data or let a program start from the start, they can even be use when we need to compute data. In order to execute a loop, a condition must be validate, which was why we had to know how to manage the program flow of a software application.

The first loop we’re going to see is the while loop. In order to know what is happening in a loop, we must first know how to write a loop. When using a while loop, we’re telling the computer the following statement: while the following condition is true, please perform all the stuff that is inside the loop. It is thanks to this condition that the loop will know when it has to stop the looping operation. While this must sound like an easy task to do, this is a well known issue for beginners: infinite loops. For example, like we saw earlier with the comparison operators, if we were to tell while the value of 1, ¬†the while loop will never know when to stop because the value, in the condition, does not change. We’ll see below how to write a while loop with an example :


char selectedAnswerFromUser='Y';

while(selectedAnswerFromUser== 'Y') //We are evaluating the condition the the    equality operator and not the assign operator !

{

Console.WriteLine("Would you like to stop this loop? Please press y for yes or n for no");

selectedAnswerFromUser =Console.ReadLine();

if(selectedAnswerFromUser== 'n')

{

Console.WriteLine("GoodBye ! ");

}

if(selectedAnswerFromUser !='y' || selectedAnswerFromUser != 'n')
{
   Console.WriteLine("Please, you can either press the y or the n letter!");

}

To continue, there is a similar loop to the while loop; it is called the do while loop. The single difference is that the do while will be performed at least once even if the condition is not true. That is the difference between the while and do while loop. We’ll see below an example of the do while loop :


int a=2;

int b=5;

do{ //We start the loop without giving a condition, it will be given below

a++; //The ++ operator tells the computer to increment the value of the a variable by one

Console.WriteLine(a); //This will print the value of a while we are performing the loop

}while(a<b); //in the do while loop, after giving your condition, finish your statement with the ';'

While we are using loops, you can also use variables to count the number of times the loop will perform. We saw the ++ operator earlier, which is meant to increment the value of a variable by one after the line has been read. We have an equal operator in case we want to decrease the value of a variable; the — operator. Here where it gets tricky: depending on which side you put the operators, the have different effects :

  1. variable++ :  The value we use is the value before the incrementation (Postfix incrementation)
  2. ++variable:The value of the variable we’re using is the value after the incrementation (Prefix incrementation)
  3. variable–: The value we use is the value before the variable decreases by 1(Postfix decrementation)
  4. –variable: The value we use is the value after the variable decreases by 1 (Prefix decrementation)

Thanks to those, we’ll now see how to create a condition in a while loop.


int a=5;

while(a<20) { ++a; Console.WriteLine("This the value of the a variable : {0}",a); //This the modulo operator. //It divide the variable a by 2 and looks for remainders //if there are none ->the value will be 0

// else -> We'll see the remainder

if( a%2 == 0 )

{

Console.WriteLine("The value of a will be diminish by 2. This is the value of a now: {0},a);

a=a-2;

}else{

int remainderFromModulo=a%2;

Console.WriteLine("This is the remainder of the modulo : {0}",remainderFromModulo);

}

a=a+3;

}

The last loop we’re going to see in this post is called the for loop. This loop is different from the previous ones that we first saw. This kind of a loop is used when we¬†know exactly the number of times we are going to repeat the block of code until the condition becomes false. The structure is a bit different as we can see below :


for(int i=0;i<5;i++)

{

//do stuff

//when the i variable has the value of 5, then the for loop will stop its iteration

}

In the for loop, we first have to initialize¬†which variable is used to iterate, but it does not have to hold the value of 0. Then, after the semi-colon, we have to give a condition to the loop, which, like we know, use to know how long we have to iterate. And finally, we have to specify if the value of this variable is going to increase or to decrease. Also, we don’t have to increase/decrease by the value of 1. It was used to serve as an example.

Kevin

Programming basics : manage program flow final part

0

Welcome reader,

This will be the final part in the programming basics mini series in how to manage the program flow of your software application. We’re going to see how to manage the flow of your program when we’re using a switch. It is a structure that is mostly use when we have predefined conditions.When this happen, knowing exactly those condition, we’ll have the correct operation to perform if it is met. For example, when someone is doing an exam, we could have three states

  1. He didn’t know what to do, so he had a 0
  2. The knowledge on the topic was not mastered he managed to get 11 out of 25
  3. The student mastered the topic and had 25 out of 25

If conditions like these we found in our application, it would be better to use a switch instead of the if-else if – else structure because we’ll have less to write. We’ll see below the structure of a switch statement :


/*

Everything in this code will not work

it is used to demonstrate how a switch statement is written

*/

switch (aVariable)
{
 case /*ValueOfAVariable*/:
        /*Operation*/;
 break; //tells the computer to stop the operation in this case
 default: //Represent what to do if no condition is met
        /*Operation*/;
}

In a swich statement, a case represents the value of the variable we’re evaluating in the switch. If a case is met, then all the operations for this case will be perform until the machine find the line with a break statement. Moreover, the cases can be link altogether. Like it was said before, until the computer find the statement “break;”, the switch will continue to operate. Below, we’ll see an example of such a switch:

switch(value)
{
   case 1:
   case 2:
   case 3:
   case 4:
     //do some stuff
     break;
  case 5:
  case 6:
    //do other stuff
    break;
  default:
      //do some default stuff
      break;
}

Also, we have the ternary operator, which embeds the way the if-else structure work. We’ll¬†be able to find the structure of the ternary operator below for when you want to assign a value to a variable:

  • dataType variable = ( aCondition) ? (firstValue) : (secondValue) ;

The ternary operator evaluates the given condition. If it is true, firstValue will be assign to variable. If the condition was to be false in our program, then secondValue would be assigned to variable. We’ll try out a code sample to see how it could be useful:


int minValue=15;

int midValue=30;

int maxValue=45;

int aMaxValue=(midValue&gt;maxValue) ? midValue : maxValue;

All of this covers how to manage the program flow in your software application. If for the moment this does not look useful, in the next posts,  it will get more clear as we get deeper into programming as our knowledge of the basics gets better.

Kevin

Programming basics: manage program flow part two

0

Welcome reader,

We’ll pick up where we left with how to manage the program flow of a software application. We saw how to use the if-else if-else structure. To evaluate a condition, we need comparaison operators. Those are use evaluate a boolean expression, which will either result a true or false. Below, you’ll be able to find them.

Operator

Description

==

Equality

!=

Inequality

>

Greater than

<

Less than

>=

Greater or equal

<=

Less or equal

&&

Called Logical AND operator. If both the operands are true, then condition becomes true.

||

Called the logical OR operator. If any the operands is true, then the condition become true.

!

Called the logical NOT operator. It uses the reverse logical state of a an operand. Which means that if an operand was initially at true, the NOT operator makes it false during the evaluation

Thanks to these operators, ¬†there is a lot that can be achieved to evaluation an expression. We’ll use them in samples to try to understand how they work. You can use more than just one to evaluate a given condition in your program flow.

Here, we can see how to evaluate operand(values on each side of the operator) with the greater than and less than.
float bankAccount=2500;
if(bankAccount&gt;3000){
  Console.WriteLine("You have quite a big account");
}else if(bankAccount<1000 && bankAccount>2000){
Console.WriteLine("You have more than 1000 $ and less than 2000 $ in your account");
}else{
    Console.WriteLine("We can't evaluate the value in your account, here's how much you have now : {0} $",bankAccount);
}
This sample will show how to use the NOT opeator.
bool aBoolValue=true;
if(!aBoolValue){
    Console.WriteLine("That's not right ! Is it ?"); //You should see this as false
}
if(aBoolValue){
  Console.WriteLine("That is true! If you have guess that the ouput, good job!");
}
Finally, we’re going to see how to use the equality operator. Beware, because this is a general known issue for beginners; the “=” is use to assign values and the “==” is used to evaluate is two values are equals. Because if you use the “=” operator, it will be a true expression. Why? Because you are assigning a value to a variable; doing so you’re asking the computer, for example, is it true that this variable as the value of 8?
int ageOfPerson=18;
if(ageOfPerson == 18)&lt;/div&gt;
{
   Console.WriteLine(&quot;You are consider as an adult in Canada&quot;);
}
//next example is a bad example. Please be sure not to reproduce code likethis one
if(ageOfPerson=21)
{
    Console.WriteLine("You can vote in any country that you want, or I think ?");
}
We will learn how to use switches and the ternary operator in the last part of how to manage the program flow.
Kevin

Programming basics: My first console application

0

Welcome reader,

We haven’t create an application since the start of the programming basics. It is sort of a ritual that the first program that a programmer writes will print of the screen the following : “Hello World!”. So, we are actually going to write this as our first console application.

Open your IDE and select Console application. Copy paste the follow code below and hit the run button in your IDE :

public static void Main()
   {
      System.Console.WriteLine(&quot;Hello, World!&quot;);
   }

There, you have the most basic application you can create. You are actually using a method called “WriteLine” and putting information inside the parenthesis. This information that was passed as a parameter (they will be discussed at length during the method post) was then written on your screen.

There you go ! It wasn’t so bad, you can now call yourself a “developer” or a “programmer”. As we’ll progress, you’ll see that programming isn’t so hard as long as you put your time in it and really want to learn. Being passionate about what you’re trying to achieve will help you to master a lot of subjects. Don’t beat yourself down if there was ever a subject that eluded you even if it was the 100th that you tried to do it. Take some time off and come back, make sure you understand the core fundamentals before moving foward !

Kevin

Programming basics: naming convention, indent and white spaces

0

Welcome reader,

We’ll follow where we left off when we’ve talked about variables. When you are behind you screen, there is a lot more going on then just writing lines in the IDE to make you computer do something. ¬†There are a set of rules that you should always stick to make your code clearer. Before, we talked about commenting your code. ¬†Comments are meant to explain the purposes of your program. As an example, ¬†when you’re creating variables, placing comments can help explain what you’re trying to do with those variables. When you’re programming, your instructions will be read by the IDE. Comments will be ignore by the IDE.

There are different ways to comment code. You can place comment on one line. You can also you what I call paragraph commenting. These will come handy when we’ll describe the behavior of methods. You’ll find some commenting examples.


//This is a single line comment

/*

This a paragraph comment. While I'm inside the /**/

all that will be written will be ignored by the IDE

*/

int myIntVariable; //Explain the usefulness of your variable with this comment 

More than just comments, there are other ways to make sure that other programmers who might read your code will appreciate reading it. As you could have seen, when I’m writting my variables, I follow a set of rules which I strongly suggest that you should also follow. This is called the “camelCase” convention. When you’re creating something like a variable or a method (more on methods later), these are the rules that you’ll have to follow.

  • The name of your variable cannot start with a number such as “123MyVariable”
  • The name of the variable should always start with a lower case letter such as “myVariable”
  • When you’re trying to write a composed name, you can either do this : “thisIsTheNameOfTheVariable” or use the underscore to separate either word of the variable’s name like this : ¬†“this_Is_The_Name_Of_The_Variable”
  • Never forget to give a meaningful name to your variable

Finally, even following those set of rules is not quite enough. A good programmer should always indent his code a have a moderate use of white spaces. Well, I’ve just blurred some words that won’t really mean something to you so I’ll explain what I’m trying to tell you. Indenting code is a convention where you place tabs in the blocks of code. As for white spaces, there just meant to make code easier to read. It could all be close together, but that wouldn’t do any good if one must spend some time, trying to decrypt what you’ve wrote.

You’ll find below an example :

/*
The following block of code won't work
It will serve as an example to make sure
that you understand indentation
*/
//indentation
int variable_1=10;
{
   int variable_2=13; //See? There was a tab after the curly brace
}

//white spaces(none)
int variable_3=15;
double variable_4=20.0;
decimal variable_5=0.05m;
short variable_6=56;

//white spaces
/*
Putting white before and after operators(more on them later)
is helpful. Your code does not have to be too cramped
More than just that, separate your variables makes it also easier to read

What I suggest is if you have a set of variables that have a relation
altogether, let them be in a group but after create an empty line and then
resume your coding activity
*/
int variable_7 = 123;

double variable_8 = 234.98;

decimal variable_9 = 0.45m;

First real life project : Managing orders

2

Welcome reader,

This post is a small break from the programming basics serie. I’m going to talk about a real life project I will talk about in this blog. It will be an open source project, which will be accessible from my GitHub account profile. ¬†Before going talking more about the basics, I thought it would be a good idea to talk about what could be achieved when we will put everything that was learned and mastered here in this blog.

You have to create a software application which will store a large number of clients. These clients will make orders and they have to save in a database which must be available a least 95% of the time. Sometimes, special orders takes more time than usual before they come in, when this happens, you can either make it so that when it happens, you automatically send emails to users or u make a query in the database to select users and then send the email. For emails in this situation, you should have templates which would just receive dynamic data so the user of the software has less manipulation to do.

For users, the fun would be to have a self-contained mobile application . What I mean is this:

  • sign in into the app with all our information.
  • Be able to see whats going on in our account.

Moreover, while using a mobile device, such as a phone or a tablet, users would have notification of what going on. Even if emails are sent to the email account, it would even better to select what kind of feedback from the company a customer would like to receive.

In this example, we have a software application which must use a database. The information must be available at least 95 % of the time, so the fail rate has to be really low. The information on the orders must be available online so the users can access it from his mobile device with their app.

In our dev world, there are many ways to complete a task. What I recommend is usually go with what you know so you’ll know what you’re doing while you are doing it. But, in a realm in which things move faster than when oneself blinks his eyes, I think it would be a¬†benefit to try out new technologies in order to gain experience.

For this kind of problem, I have chosen to use:

  1. C# with the object oriented paradigm
  2. Windows Phone (Universal App)
  3. The Android Operating System
  4. Reactive Extension (Rx)
  5. LINQ
  6. The Firebase database

Honestly, I haven’t really experimented the technologies #2, 4 and 6. But I’m not going into this series before we’re ready to do it. So during that time, I’ll get my hands dirty. In the developers community, when someone says getting their hands dirty, it is meant as programming. In order to understand something, we really need to experiment by ourselves, even if the code makes sense to you, I strongly suggest that you at least copy paste it into your IDE and run the application to see how it works on your machine. What would be best is to modify the code, play with it until you truly understand what’s going on.

On the topic of the open source project, I’m going to take you step by step in my solution. This is going a more advanced serie, but bear no fear, if there things that you don’t understand, post comments and I’ll answer you to the best of my knowledge. At first, we will¬†setup our database before going into coding. Then, we’ll design our software application for the company. Then design our mobile app. Afterwards, when the designs are completed, I’ll explain the more complex¬†parts of my implementation, but not all of it. You’ll be able to find the project on my GitHub. Don’t worry, it’ll be commented!

Kevin

Programming basics : variables

0

Welcome reader,

This is the first part of a mini-serie to introduce the basics of programming with C#. Don’t forget to look at my GitHub account. I haven’t decide yet, but surely I will create a project which will resume every topic that I’ve talked about during the Programming basics serie.

So, we’re finally there, will start talking about the programming at last! In this serie, I assume that you’ll have already downloaded your IDE( if you don’t know what’s an IDE, please go read my blog post about IDEs) on your machine. Like I have mentionned before, I’ll be using the Visual Studio Community Edition IDE in this blog.

The introduction to programming start with a fundemental topic : variables. When you are programming, you are telling your machine exactly what you want it to achieve. In order to do so, you have to manipulate data directly on your machine, and when you’ll be running your software application(more of running later), the code that you’ve given will look like this:

0101010 0101 010101 01010

For the untrained eyes, it’s only 0s and 1s. But that is called binary code. This is what your machine use to achieve an operation that you have order it to do. ¬†Even when you are on your user interface of you operating system, you are telling your computer what to achieve for you such as

Opening a folder

Save a file

With the IDEs, ¬†our life is easier, we don’t need to actually manipulate data on the computer with binary code, we use variables. What this means is this: variables points to different parts of the computer memory. In short, variables have a name and a value.They hold different kind of data which can be manipulate and consume by a programmer¬†in order to achieve his goal. Below, you’ll be able to see all the variables that are accessible in most programming languages:

  • byte – 8 bits
  • short – 16 bits
  • int – 32 bits
  • long -64 bits
  • float – single precision 32 bit floating numbers
  • double – double precision 64 bits floating numbers
  • decimal – 16 bits
  • bool – boolean value (true/false)
  • char – holds a character
  • String (it will be discussed in a later post)

From byte to long, these represent integer values such as 0, 100, 200. We have access to different kind of integer values, and when you are programming, you have to choose carefully the exact type you need because each type has its own weight in bit. The more you use, the bigger the software application will be. To understand the difference between the type of integer you can choose, you will find below the range of values each one has:

  • byte [0,255]
  • short [-32768,32767]
  • int [-2147483648,2147483647]
  • long [-9223372036854775808,9223372036854775807]

For example, if you create a software application which will only hold employees ages, using long variables because of their weight. Rapidly, in an application with around a million employees, the software would be heavy to process because you’re using the wrong type of data. In this case, knowing that the human’s span life is around 80 years, using the byte type would be much better. While using variables, you should always use your judgement in order to be memory efficient. Lower, you’ll be able to find an example of a byte variable containing the age of an employee:


byte employeeAge=30;

As you can see, when using a variable, the variable’s name is on the left and the value,which will be assigned, is on the right. ¬†To continue, the float,double and decimal types should be use only when you to consume data which contained the full value of number like 1.25.


int firstValue=1.25; //firstValue will only be 1 because it is an integer
float secondValue=1.25; //secondValue will be 1.25

Console.WriteLine(firstValue);//Will display the value of 1
Console.WriteLine(secondValue); //Will display the value of 1.25

Upward, you can see some code sample showing the use of two variables and C# function(more on functions later) in order to display data to the screen. There’s quite a lot going on in this sample, the part with the double slash is called comments. Comment will be discussed in the next part of this serie. Moreover, as you can see, the names of the variable don’t really represent anything. When using variables, the names you use should always be meaningful. By always doing so, you’ll be able to understand the code you’ve written a while back faster without, or almost, need of comments.

To finish, the char type can only hold a character as a value. A character can be anything such as a alpha or numerical character. The char data is assigned with single quotes. You can see an example below.


byte charVariable='1';

To wrap up, variables have a meaningful name and a value. When using variables in your software application, you should make sure to always use the right type in order to be memory efficient.

Kevin

First post

1

Hi everyone,

This is my first post in wordpress. I’ve created this website in order to help developers to dive into the great world of .NET! Thing is, it is so vast that it can be bothersome to try to find exactly what you want to achieve with .NET.

About everything can be achieved with .NET: you can create desktop application, web applications and services, mobile applications and so on. This blog will focus on helping you to get a better understanding of .NET.

At first, I will show you the core fundamentals of programming with C# and VB.NET. In order to achieve projects,it is my belief that people should have a good foundation of the basics before they can try to get into the different current hypes like voice enabled mobile apps or create a web-based video game.

I’d like to introduce myself. My name is Kevin Avignon, I’m a Java and C# developer. I started my path in the tech world about two years ago. I started programming with C# but I’m currently doing my IT engineering bachelor with Java.¬†I’ve been in love with the .NET world since I first wrote my C# console application. I’ll do my best to make sure that in time, you’ll love it as much I do.

I have topics that I’ll want to mention in this blog because either I consider them really important or because I have an interest in them. ¬†If ever there was a topic that was not on this website and you’d like me to talk about it, please make sure to let me know by commenting on my posts or posting your question in the Ask Kevin tab.

Let’s dive in into the world of .NET together and ¬†I hope you’ll enjoy the ride !

Kevin