Saturday, October 12, 2013

A security capsule can save your program’s life (Part.2)

In the previous post we have created an application. But there was a little bug in our program. Let’s find the bug. How about we run the program once again? And this time we provide the TextBoxes with some information and uncheck the Private CheckBox to see the mobile number of the user and click submit. Oops!!! It is still “N/A” in the ListView’s mobile column but it was not what we expected, Right!!! Cause we unchecked the Private CheckBox in the form. So what was the problem? The problem was not with our UI but with the implementation of our code. Let me show you where we actually made a mistake. Recall that we explicitly set the Boolean value of HideMobileNo to true. Now go back to our code behind the Form. Look carefully from the top. See that in the Form constructor we have instantiated a user object and gave some values for the fields so that at runtime at least one item is placed in the ListView control. Now go to our code of the Submit button. See that we are again instantiating the user object but now we are sending the values for the object’s field from respective TextBoxes. At last when we go to our CheckBox’s checked changed event we can see that we are passing the current check state of our CheckBox to user.SetMobileAsPublic method. If you have got this far then you know what the problem really is. The problem occurs actually when we create an instance of user object in the submit button’s code but didn’t set the Boolean field HideMobileNo to false if someone unchecked the Private CheckBox. What we really did here is we completely rely on our CheckBox’s check changed event. But if we look carefully we will see that we are not setting the HideMobileNo field of our object created in the button code to a true value rather we have actually done it for the object we have just created in the Form constructor. So when we submit a new user object in our program we may or may not change the Private CheckBox state in the UI but we accidently change the HideMobileNo field value of previously created object. So we never get a mobile number when we unchecked the Private CheckBox rather we always get a “N/A” in the ListView’s Phone column.

Here we didn’t intended to face such a bug but at the end of the day we did have one in our program. That’s because programs always don’t run in the way that we want it to be. And we introduce bugs in program in the process of doing so without taking cautions.

To overcome such problems object oriented programming (OOP) introduces a concept called Encapsulation. As with the name goes, we simply encapsulate our field variables with the help of some methods. The methods are actually a way of setting/getting values of our field variables.  

So, in the next post I will show you how can we implement encapsulation in our code. Till then stay tuned. J

A security capsule can save your program’s life (Part.1)

We are now familiar with the definition of encapsulation but we yet don’t know how to implement it in our code to prevent any kind of Misuse and Bugs in our code. Let me give an example. I think everyone knows what Facebook is. In Facebook, when we create an account we provide different kind of information, so that another Facebook user can know a little bit about us before connecting with us. When a user successfully creates an account, Facebook community hides your phone number (one of additional information given at account creation) by default. This is for your security purpose only. If we go to the account contact section, we can easily set it back to public so that the phone number is visible when someone searches us.  So why don’t we build a new program with this scenario in our mind. Let’s start.
  • Open Visual Studio. (I’m using visual studio 2012. But other versions will be fine enough).
  • Open File -> New -> Project.
  • Select Windows from installed templates and select Windows Form Application.
  • Give a name to your project and press Ok.
  • IDE will create a form for you.
  • From the toolbox on the left drag and drop controls to create the UI given below.

Fig: The main UI

So, we have created a registration form where a user can give his name, email and phone number and click Submit button to enter his/her info in the ListView Control. We want our new user’s phone number to be private by default. So we create a CheckBox control with its checked property set to true. 

Now,
  • Select Project from menu bar and select add class or press (alt+shift+c ).
  • Add a new class named User.
  • Write the following code in the class.
class User
    {
 public string Name;
        public string Email;
        public string Mobile;
        public bool HideMobileNo = true;

        public void SetMobileNoAsPublic(bool isPublic)
        {
            HideMobileNo = isPublic;
        }

        public string GetMobileNo()
        {
            if (HideMobileNo == true)
            {
                return "N/A";
            }
            else
            {
                return Mobile;
            }

        }
    }

What we are really doing here is creating four public field variable (i.e. Name, Email, Mobile and HideMobileNo). HideMobileNo is a Boolean variable which initial value is true. Cause we want our phone number to be private by default. Right!
Again we have two public methods. The SetMobileNoAsPublic method sets the HideMobileNo variable’s value to the method’s parameter value isPublic. And the GetMobileNo method simply checks the HideMobileNo variable value and returns N/A (not available) if HideMobileNo value is true or returns the phone number stored in the Mobile variable.

Now let’s go to our main Form and write the following codes

    public partial class Form1 : Form
    {
        private User user;
        private ListViewItem item;

        public Form1()
        {
            InitializeComponent();
            user = new User();
            user.Name = "Fiyaz";
            user.Email = "fiyazhasan@yahoo.com";
            user.Mobile = "0171-XXXXXXX";

            //Tweak the listview design
            userListView.View = View.Details;
            userListView.LabelEdit = true;
            userListView.AllowColumnReorder = true;
            userListView.FullRowSelect = true;
            userListView.GridLines = true;
            userListView.Sorting = SortOrder.Ascending;

            //Creating a listview item
            item = new ListViewItem(user.Name);
            item.SubItems.Add(user.Email);
            item.SubItems.Add(user.GetMobileNo());

            //Adding the listview columns
            userListView.Columns.Add("Name", -2, HorizontalAlignment.Left);
            userListView.Columns.Add("Email", -2, HorizontalAlignment.Left);
            userListView.Columns.Add("Phone", -2, HorizontalAlignment.Left);

            //Add the items to the ListView.
            userListView.Items.AddRange(new ListViewItem[] { item });
        }

        private void ClearTextBoxes()
        {
            nameTextBox.Text = "";
            emailTextBox.Text = "";
            mobileTextBox.Text = "";
        }

        private void submitButton_Click(object sender, EventArgs e)
        {
            //Create a new user instance with new values
            user = new User();
            user.Name = nameTextBox.Text;
            user.Email = emailTextBox.Text;
            user.Mobile = mobileTextBox.Text;
           
            //Create a listview item
            item = new ListViewItem(user.Name);
            item.SubItems.Add(user.Email);
            item.SubItems.Add(user.GetMobileNo());

            //Add the newly created item
            userListView.Items.AddRange(new ListViewItem[] { item });
           
            //Clear the text from the textbox
            ClearTextBoxes();
        }

        private void setPrivateCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            user.SetMobileNoAsPublic(setPrivateCheckBox.Checked);
        }
       
        private void cancelButton_Click(object sender, EventArgs e)
        {
            ClearTextBoxes();
        }
    } 

At the top we are creating two objects. One is of our User class and the second one is a ListViewItem object of ListViewItem class (built-in class in .net framework). In the constructor of Form1 class, what we are doing is
  • Instantiating our user object.
  • Now we are setting default values for our newly instantiated user objects.
  • Next we are tweaking some deign for our ListView controls. Nothings special.
  • Next as like before we are instantiating item object.
  • Then we are adding user.Email as first sub item.
  • Again we are setting the next sub item to the returned value of user.GetMobileNo().
  • Recall that we already set a true value for our HideMobileNo variable.
  • So the return value will be of course “N/A”.
  • Then we set three column Titles for our Listview control
  • Then add our ListViewItem item to our ListView control with defined designs.
  • When we debug the program. We get the following result.
Fig: The first run

So we ended up with a ListView control with a default value at runtime.
Next we are doing the same thing as we have done before in the constructor. But instead we took values from relevant TextBoxes for our appropriate user object fields. Now if we press debug we will be able to type values in the TextBoxes and add the new item in the ListView by click on submit button. Like this


Fig: Entering values in TextBoxes


Fig: Newly added item in ListView

The last thing we have done is in our setPrivateCheckBox_CheckedChanged event we call our user.SetMobileNoAsPublic method with the user selected state of our CheckBox as parameter (i.e. user.SetMobileNoAsPublic(setPrivateCheckBox.Checked);).

So we have a great working application, Right!!! I’ll prove you wrong but in the next post. So stay tuned. J



Wednesday, October 9, 2013

Let’s eat some PIE…!!!

So we have reached to a point where you guys need to know the three principles of object oriented programming. These are Encapsulation, Polymorphism and Inheritance and also called (PIE). In this post I’m going to give some little description about these three principles. I’ll provide more details about them with coding examples in later posts.

Encapsulation: Using encapsulation in our code we can keep safe our code and data from outside interference and misuse. This is the most important principle of all. We can prevent ourselves from introducing a bug in our program by encapsulating our code.

Polymorphism: In short polymorphism means many forms of a single object. For very simple example, recall the fact that Carbon (a chemical element) has two well-known polymorphs - Diamond and Graphite. Both are Carbon but the behaviors are different due to the internal structures. C# and other Object oriented language supports polymorphism by changing the behavior of and object at run-time.

Inheritance: Inheritance is a process by which an object acquires the properties of another object. For example, Lamborghini and Bugatti are two car companies. Both are capable of designing and selling racing cars. But they didn't invent the definition of car. To be more precise, we all know that a car has 4 wheels, runs on fuel, has a steering wheel etc. We can tell with our eyes closed by listening to these properties that this thing is a car. So a racing car designed by Lamborghini and Bugatti to be a car, should inherit the property of a basic car (i.e. it should have 4 wheels, should run on fuel etc.).