Sunday, January 5, 2014

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

So, let me show how easy it is to implement encapsulation in C#. I will start from the very old fashion to create a encapsulated field then will show the easiest way. Basically to encapsulate a field level variable we would simply declare a setter and  a getter method. With the help of the setter method we would set a value for our field level variable and with the getter method we would extract the value from our field level variable set by the setter method. So open the project we have been working on so far and do the followings
  • Open the User class.
  • We have four field level variables. i.e. 
        public string Name;
        public string Email;
        public string Mobile;
        public bool HideMobileNo = true;
  • Lets make a setter and getter method for the Name variable first.
  • The setter and getter methods look like this
 public void SetName(string name)
        {
            this.Name = name;
        }
        public string GetName()
        {
            return this.Name;
        }
  • And also same for the rest like this
 public void SetEmail(string email)
        {
            this.Email = email;
        }

        public string GetEmail()
        {
            return this.Email;
        }

        public void SetMobile(string mobile)
        {
            this.Mobile = mobile;
        }

        public string GetMobile()
        {
            return this.Mobile;
        }

        public void SetHideMobileNo(bool hideMobileNo)
        {
            this.HideMobileNo = hideMobileNo;
        }

        public bool GetHideMobileNo()
        {
            return this.HideMobileNo;
        }

So what we have done here is simply removed any kind of hard coded value in the field level variable and declare a setter and a getter method for each and every fields. By doing that we have omitted the possibility of any kind of mistakes. By mistakes I mean, forget to set a value for a field level variable or getting a wrong value from the field level variable. So this is the very old fashioned way to encapsulate fields.

In C# we can easily encapsulate a field with the help of Property. Means that we can declare our variables like Property in C#. We have been working with these property from the start of our project. For example, We set the Name property for one of our textBox to nameTextBox. Each property has a get and set method internally. So we don't have to go through the headache of declaring two methods for each fields. Rather we can do as followings.

              private string _name;
        public string _email;
        public string _mobile;
        public bool _hideMobileNo;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }
        public string Email
        {
            get { return _email; }
            set { _email = value; }
        }
        public string Mobile
        {
            get { return _mobile; }
            set { _mobile = value; }
        }
        public bool HideMobileNo
        {
            get { return _hideMobileNo; }
            set { _hideMobileNo = value; }
 }


See that each property has a get and set method internally. The set sets the value passed to property to the field variable contained in keyword value. And the get returns the value that has been just set. This kind of property is called read and write property. We can also declare logic inside set and getFor example we can remove white spaces from the Name property when user enters his/her name like this

 public string Name
 {
      get { return _name; }
      set
      {
          _name = value;
          _name = _name.Trim();
      }
        } 

Here Trim() is a function which removes additional white spaces from string.

So read and write property is useful when there is a possibility of implementing a logic associated with a field. But most of the time additional business logic are implemented in separated class to follow the separation of concern pattern. So we can declare auto property like this

public string Name { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public bool HideMobileNo { get; set; }

So, Lets go back to our project and implement the User class like this

  public class User
  {
        public string Name { getset; }
        public string Email { getset; }
        public string Mobile { getset; }
        public bool HideMobileNo { getset; }

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



Now go to the Form1.class and rewrite the code as followings

    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";
            user.HideMobileNo = setPrivateCheckBox.Checked;

            //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_1(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;
            user.HideMobileNo = setPrivateCheckBox.Checked;

            //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_1(object sender, EventArgs e)
        {
            user.HideMobileNo = setPrivateCheckBox.Checked;
        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            ClearTextBoxes();
        }
   }

Now run the program it will behave as it was supposed to.

So we saw that why encapsulation is an important factor in object oriented programming and also learn how to implement encapsulation in coding. Hope you liked all three parts on OOP encapsulation. Stay geeky. I'll be back soon. :)

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