My Adsense

Thursday, December 3, 2009

Implementing database concepts to develop an application in agile approach : Part 1.3 (Coding)

Hello everyone. In my last two post, i have showed how to create a database according to the user's story. In this post, i will show you how to develop/code the application to access the database. I am assuming you all know how to create an application in visual studio 2008 and run it. So, i am not discussing the steps of creating a windows application in Visual Studio IDE. If you have problem in this, please find my other posts in where i have discussed about creating the desktop application in C#. Ok. Lets start.

  1. Open Visual Studio 2008
  2. Create a desktop application named ‘ABCUniversityApplication’
  3. Create a windows form named ‘StudentEntryUI’
  4. We have found an object student from our problem domain. So create a class Student which have name, email address, address and phone number as its data. Create a constructor to assign these values when creating a new student object. 

public class Student
      {
  private string name;
        private string emailAddress;
        private string address;
        private string phoneNumber;       

public Student(string name,string emailAddress, string address, string phoneNumber)
        {
            this.name = name;
            this.emailAddress = emailAddress;
            this.address = address;
            this.phoneNumber = phoneNumber;
        }

       public string Name
       {
         get { return name; }
       }

       public string EmailAddress
       {
         get { return emailAddress; }
       }

       public string Address
       {
         get { return address; }
       }

       public string PhoneNumber
       {
         get { return phoneNumber; }
       }

    }
      
  5.      Now create a user interface like the given figure


     6. Now take a note. Your ‘Student’ class holds the student data. Your UI class takes data from user. So   you need a class which will check the validity of the data input by the user. That’s why you need a manager  class which will perform different works related with the student object. Create a ‘StudentManager’ class       which will take data from UI and pass it to another class for saving.
public class StudentManager
       {
        public void SaveStudentManager(Student student)
        {
            StudentGateway studentGateway=new StudentGateway();
            studentGateway.SaveStudentIntoDatabase(student);
        }
      }


    7. Create the ‘StudentGateway’ class for saving the student object into the database.

    To do so, you need to use some built in class of C#.

a.       Create a connection string which will be used as a parameter to establish a connection with the database
string connectionString = @"server=Magicbox\SQLEXPRESS; Integrated Security = SSPI; database = ABCUniversityDatabase";
b.      To create a connection with the database, you need to use SqlConnection class. To use it, you have to import system’s SqlClient directive into your code
c.       Create an object of that class.
SqlConnection connection = new SqlConnection(connectionString);
d.      Open the connection of the databse.
connection.Open();
e.       Now create the insert query string for execution to save the data into the database.
Since your Student class doesn’t have the get properties of the data, change your Student class adding the get part for each of the data.
         string insertQueryString =
   @"INSERT INTO t_Student VALUES ('" +student.Name + @"','" +student.EmailAddress + @"','" +student.Address + @"','" +student.PhoneNumber + @"')";
f.       Now you need a SqlCommand object to execute the query you have built to save the data
SqlCommand command = new SqlCommand(insertQueryString, connection);
g.       Now execute the command
command.ExecuteNonQuery();
h.      So at the end, your StudentGateway class will have the following code snippet
    public class StudentGateway
    {
              public void SaveStudentIntoDatabase(Student student)
        {
string connectionString = @"server=Magicbox\SQLEXPRESS; Integrated Security = SSPI; database = ABCUniversityDatabase";
SqlConnection connection = new SqlConnection(connectionString);
            connection.Open();

                  string insertQueryString =
            @"INSERT INTO t_Student VALUES (
                                           '" +student.Name + @"',
                                           '" +student.EmailAddress + @"',
                                           '" +student.Address + @"',
                                           '" +student.PhoneNumber + @"'
                                        )";
SqlCommand command = new SqlCommand(insertQueryString, connection);
            command.ExecuteNonQuery();
        }
}
  1. Now go back to your UI class. Write down the following code into your saveButton method block
        private void saveButton_Click(object sender, EventArgs e)
        {
Student student=new Student(nameTextBox.Text,emailAddressTextBox.Text,
addressTextBox.Text,phoneNumberTextBox.Text);
            StudentManager studentManager = new StudentManager();
            studentManager.SaveStudentManager(student);
MessageBox.Show(student.Name+"'s information is saved into database");
nameTextBox.Text = "";
            emailAddressTextBox.Text = "";
            addressTextBox.Text = "";
phoneNumberTextBox.Text = "";           
        }
  1. Now build the application and run it. Enter the data given like the following figure and click on the save button




  1. If the data is saved, the messagebox will appear showing you the success of the saving of your data.
  2. Now go to your Sql Server Management Studio Express and right click on t_Student table
  3. Click ‘Open Table’ option to check whether our data is really saved or not
  4. You will see the following figure


  1. Thus we have saved a sample data into the database through an application.

Wednesday, November 18, 2009

Implementing database concepts to develop an application in agile approach : Part 1.2 (Database Server)


Hello everyone. In my last post, i have showed how to create a table schema from real time problem domain, which is now we called as user story. But to work on a database, we need to create tables in a database server. Since i am working on .NET Platform, i am using Microsoft's SQL Server  2005.

Installing Microsoft SQL Server 2005:
This server is automatically installed when we install Visual Studio 2008. Or you can download the server file from http://www.microsoft.com/Sqlserver/2005/en/us/express.aspx.

Installing Microsoft SQL Server 2005 Management Studio Express:
To working on the SQL Server, you need to install a management tool. You can download this from http://www.microsoft.com/downloads/details.aspx?familyid=C243A5AE-4BD1-4E3D-94B8-5A0F62BF7796&displaylang=en this location.

OK. Now we are ready to work on the SQL Server.
When you lunch the management studio express, the following window will appear.


Figure 1: SQL Server Management Studio Express

I am giving you the short description of the SQL Server Management Studio Express opening window. Please Google yourself if you want to know more on this topics.


Server name:
In your computer, you may have several instances on of sql server 2005, or different versions of sql server like as 2005, 2008 etc. you will give them a specific name to work with it.
In this case, MAGICBOX is the server name and SQLEXPRESS is the instance name of the sql server 2005 on which we are currently working on.


Authentication:
Sql server provides you couple of types of authentication. In Windows Authentication, server assumes since you logged into the machine, you are authenticated to access on the server. But if you use the other type (SQL Server Authentication), you have to enter the credentials of User name and the Password field of that server instance.

Now we will create the table in database.

Walkthrough 1: Creating ‘t_Student’ table using SQL Server Management Studio Express
Steps:
1. Go to: StartMicrosoft SQL Server 2005SQL Server Management Studio Express
2. The following window will appear


Figure 2: Opening Window of Management Studio

3. Click the ‘Connect’ button
4. There are several nodes you will find on which you can work with. Each of the nodes explains itself.


Figure 3: Explorer of Management Studio


5. Right click on the ‘Databases’ node
6. Click on ‘New Database’
7. Enter the database name meaningful. For our user requirement, we will enter ‘ABCUniversityDatabase’ as the name.
8. Click on the button given in the following figure to select the destination path of the database files


Figure 4: Select the Destination Path


9. Click ‘OK’
10. You will find the following figure on your screen


Figure 5: Newly Created Database

11. Check your HDD file location to check the database file


Figure 6: Files created in your hard disk

12. Now expand the ‘ABCUniversityDatabase’ on your management studio express
13. Right click on the ‘Tables’ node
14. Click on ‘New Table’ option
15. Enter the column names given in the following figure


Figure 7: Column Definition of student's table

16. Click on save option and enter the table name as ‘t_Student’
17. Now expand the ‘Tables’ node from Object Explorer window
18. You will find your just created table in here


Figure 8: Columns Viewed in Explorer

Thus you have created a table (t_Student) in your database (ABCUniversityDatabase) to store data (information of studetns). :)

In my next post i will show you how to create the application in C#, which will take the information from the user and store it in the table.
Happy coding.

Tuesday, November 17, 2009

Implementing database concepts to develop an application in agile approach : Part 1.1 (Database Concept)

Waterfall vs Agile:
Most of the developers in the world start making their software in the traditional way. Traditional means first they gather most of the requirements of the client and then start designing the database where the data will be stored. After designing the database, which is called Entity-Relationship Diagram (ERD), they start coding. This approach is called waterfall .
This is a very inefficient approach and it is turning obsolete day by day.
New types of thinking and implementations are coming one by one to make a software robust and easily maintainable. The most popular thinking approach now a days is. AGILE
The main part of agile is to start the working without waiting for the whole requirement of the client and evolve the application on the requirement of the client [Details] .
In agile, we don't use 'Requirement' types of word. We rather use 'User Story' as the specification of the software given by the client. I have used a traditional conversation process as the specification of the software.

I am assuming you are familiar with ERD, Basic Programming and you have sound concept on OOP.
If you don't have much confidence on OOP part, i prefer you to go http://tiemoon.blogspot.com here for the primary OOP concept.

Ok. Lets start developing an application for 'ABC University'.

The technical officer of 'ABC University' is Mr. X. Last month he came to me and talked with me about a software for his university.
The conversation was similar to the following one.
[User story:]
Mr. X: “I am the technical officer of ABC University. We admit a lot of students in every semester. So entry down those students is very tough for us in pen and paper. I want to store the information in a computer”
Me: “What data do you want to store for a particular student?”
Mr. X: “Well. I want to store a student’s name, email address, address and phone number”
Me: “Ok. Fair enough. I am going to start developing the software for you”

Entity:
The thing which can be uniquely identified and stored to database is called en entity. It is like an object in OOP concept. The collection of the entity which shares the common characteristics is called the Entity Sets. We can map this concept in OOP as Class.


Analysis:
So in our user story, we can identify Student as an object. So it is an entity and it is the thing that is to be stored.


Notation:
We use a rectangle for expressing an entity in ERD.


Result:

Figure 1: Entity


Attribute:
The information we want to store about our entity is called attribute. Any data that will qualify, identify, classify or express the state of entity is called attributes. It can be mapped like the data of an object in OOP.

Analysis:
Since Student is our primary entity, we start analyze its attributes which holds the information of a particular student. And we found a student’s name, email address, address and phone number those are going to be stored for a particular entity.

Notation:
We use an oval to denote an attribute of an entity.

Result:

Figure 2: Entity and Attributes

NB: Each of the entity must have a table containing its attribute as the column name.

Naming convention that i will follow through my posts:
  • Each of the entity will be in a Noun form. A table will be started with the charactre ‘t’ followed by a underscore ‘_’ and then the entity name. eg: t_Student
  • A column will be started with it’s entity name of camel case and then an underscore and then it’s original name. eg: student_Name
So, if we sketch our table structure as a schema, then according to our user story, we will find the table schema as,
t_Student ( student_Name, student_EmailAddress, student_Address, student_Phone)


The table schema is been created. Now we will create it in our database server. I describe it in my next post (1.2)

Thursday, November 5, 2009

Introduction to C# : A hands on approach (Part 2)

Introduction to C#: Day 2

           
            In this lesson you will be familiar with different types of C# syntax some conceptual things.
            Objectives:
            After completing this unit you should have a clear concept on:
*        Data types
*        Expressions
*        Conditional statements
*        Iteration statements
*        Methods in C#
*        Enum

You will be able to create applications using the following controls:
*        ComboBox
*        GridVeiw
*        ListView etc.


Topics

In this lesson you will learn about the following topics
*        Data types
*        Data types conversions
*        Data type: String
*        Data type: Constant
*        Expressions
*        Operators
*        Conditional statements
*        Switch
*        Iteration statements
*        Enum








Data types:
When we instruct a machine to execute some operation, the machine changes the high level language (which we are sending) into machine code (sequence of 1s and 0s).
The instruction we are sending also contains data on which the operation will be executed.
But not all data should contain the same amount of memory nor do the same types of operation. So, different sets of data have different size and perform different types of operation. And they are not interpreted in the same way.
So, a instructor (programmer) has to tell the system before-hand, the type of number or characters he is using in the instruction. These type are called Data Types. There are many data types in C# language. A programmer has to use appropriate data types as per his requirement.

There are 2 types of Data Type. They are
                                                                                 i.            Predefined Data Types
                                                                               ii.            User defined Data Types

Predefined Data Types:
This kind of data types are created by the C# creator programmers (Microsoft Programmers). They define the characteristics of the data types and also define the set of allowed activities a specific data type can do. Different types of predefined data types allocated different amount of memory and performs different types of operation.
The following data table lists the predefined data types and describes the data that they are designed to store.
Type Name
Definition
Byte
Byte
Integer (0 to 255)
1
Sbyte
Integer(-127 to 128)
1
Short
Integer (-32768 to 32767)
2
Ushort
Integer (0 to 65535)
2
Int
Integer (-2147483648 to -2147483648)
4
Uint
Integer (0 to 4294967295)
4
Long
Integer (-9223372036854775808 to -9223372036854775808)
8
Ulong
Integer (0 to 18446744073709551615)
8
Bool
Boolean value(true or false)
1
Float
Single-precision floating point value
4
Double
Double-precision floating point value
8
Decimal
Precise decimal value to 28 significant digits
12
Object
Base type of all other types
N/A
Char
Single Unicode character
2
String
An unlimited sequence of Unicode characters
N/A
                       
                        User defined data types:
User defined data types are composed of different combination of predefined data types. Sometimes a user defined data type contains another user defined data type in it. A user defined data type can also perform some operations and the definition of the operation will be stated into the type definition.

                        Working with data types:
To use a data in our program, we have to follow some specified way and use some specific keywords that are defined by the language creators.

a.       Declaration:
Declaration is something like allocating a memory space for a specific data and gives the memory address a name by which the programmer can operate on that data later. It is linking of a memory location to a data. The name of the memory location is called Variable.
Example: int count;
b.      Initialization:
Initialization is the next step of declaring of a variable. In initialization, valid data is inserted into the variable memory location. Valid data means the allowed types of data that the memory location can contain.
Example: int count = 10;
c.       Literals:
Literals are a single character used at the end of a data. It is used to put data into a memory location that is normally invalid for that memory location.
Example: decimal priceWithVat = 123.123M;

Walkthrough 1: Working with data types
            To make the data type clear, we will practice some works on data types.
            Steps:
1.      Create a new console application
2.      Declare a variable of Integer type
3.      Initialize it with some data
4.      Display the variable in the console.
5.      Now declare a float type variable and initialize it
6.      Build it
7.      You will find an error saying “Literal of type double cannot be implicitly converted to type 'float'; use an 'F' suffix to create a literal of this type”
8.      Put a character ‘F’ or ‘f’ at the end of the data of the initialization statement.
float variable = 12.2f;
9.      Build it
10.  Run it


                        Data Type: String
As stated above, a string variable contains a sequence of alphanumeric characters. We can declare a string variable like other types of variable.
Example:
               string name;    // Declaration
               string firstName = "Foyzul";    //Initialization

Escape characters:
Escape characters are used when we want to set a run time meaning of a part of a string.
Example:
string greetings = "Hello everyone.\nWelcome to BASIS.";

                                    Verbatim characters:
A verbatim string is a string that is interpreted by the compiler exactly as it is written, which means that even if the string spans multiple lines or includes escape characters, these are not interpreted by the compiler and they are included with the output. The only exception is the quotation mark character, which must be escaped so that the compiler can recognize where the string ends.
Example:
string address = @"C:\Software\Books\Beginning”;
As you can see, verbatim is indicated with an ‘@’ sign at the beginning of a string.
If you want to use a quotation mark inside a verbatim string, you must escape it by using another set of quotation marks.
Example:
string greetings = @"""Hello everyone"".said the trainer.";

Walkthrough 2: Working with String types
Steps:
1.      Create a console application
2.      Declare a string variable and initialize it by your name
3.      Display the variable in console
4.      Build the solution and run it
5.      Now change the value of the variable using "Hello everyone.\nWelcome to BASIS."
6.      Build it and run it
7.      Change the value of the string with the address of your project directory using verbatim




                        Data Type: Constants
A constant is a variable whose value remains constant. Constants are useful in situations where the value that you are using has meaning and is a fixed number, such as pi, the radius of the earth, or a tax rate.
Example:
const int radiusOfEarth = 6378;                              
As you can see, constant variable starts with the keyword ‘const’ at the declaration, or initialization.
Walkthrough 3: Working with Constant
            Steps:
1.       Create a console application
2.       Declare a constant integer type variable and initialize it
3.       Display the variable in console
4.       Build it and run the application

          Data Type Conversions:
Sometimes we have to change the data that we are using. Sometimes this change may change the value of the data or sometimes it just changes the memory space allocated by that data. This change is called data type conversion.
Data type is converted in 2 ways. They are:
a.       Implicit conversion
b.       Explicit conversion
They are described below.

Implicit conversion:
An implicit conversion converts data automatically without losing any data. Normally, data types can implicitly converted into the data types those contain more memory space.
Example:
short firstNumber = 65;
long secondNumber = firstNumber;
                        Explicit conversion:
An explicit conversion convert data that are automatically can’t be converted. It may converts data from bigger size to smaller size or converts data from one type into totally different type.
Example:
short firstNumber = 65; //Initialization
 long secondNumber = firstNumber; //Implicit conversion
short thirdNumber = (short)secondNumber; //Explicit  conversion
                Console.WriteLine(thirdNumber); //outputs 65
char a = (char)firstNumber; //Explicit conversion
Console.WriteLine(a); //outputs A

We can use some built in functions those are provided with C#.
a.       Convert class:
A convert class contains numerous method those can change one data type into another type. It is another implementation of explicit conversion.
Example:
 int number = 65;    //Initialization
char character = Convert.ToChar(number);    //Conversion using System's Class
Console.WriteLine(character);   //Output: A           
b.      ToString() method:
A ToString() method converts any kind of data type into String type. It doesn’t change the internal value of that data.
Example:
char character = Convert.ToChar(65);    //Conversion using System's Class
string numberString = (65).ToString();
Console.WriteLine(character);   //Output: A
Console.WriteLine(numberString);    //Output(value is in String form): 65
                                         
Figure: A Memory location
          Walkthrough 4: Working with data conversion
          To make the conversion more clear, we will go through a walkthrough now.        
            Steps:
1.       Create a desktop application
2.       Design a user interface given below




3.       Select the last textbox and change its Readonly property to True
4.       Double click on the button
5.       Write down the following code into the button click event block
 int firstNumber = Convert.ToInt32(firstNumberTextBox.Text);
                        int secondNumber = Convert.ToInt32(secondNumberTextBox.Text);
                        int sum = firstNumber + secondNumber;
sumTextBox.Text = sum.ToString();
6.       Build the application and run it


          Expressions:
An expression is a sequence of operators and operands. An operator is a concise symbol that indicates the action that you want to occur in your expression.
An operand is the value on which an operation is performed.
An operator is specifically designed to produce a new value from the value that is being operated on.
Example:
Conditional operator: &&,||
Mathematical operator: +

            Conditional statements:
A conditional statement allows you to control the flow of your application by selecting the statement that is executed, based on the value of a Boolean expression.
                        Syntax:
a.       If(boolean-expression)         statement
b.       If(boolean-expression) statement1
else statement2
c.       If(boolean-expression) statement1
else if(boolean-expression) statement2
else statement3
                        Example:
                        bool condition;
if (condition == true)
            {
                Console.WriteLine("condition is true");
                                            }
            else
                if (condition == false)
                                                                {
                    Console.WriteLine("condition is false");
                }
                else
                                                                {
                    Console.WriteLine("unknown valueA+");
                                                                }
d.       If((boolean-expression) operator (boolean-expression)) statement
Example:
if (scoreOutOfHundred >= 60 && scoreOutOfHundred < 80)
                                {
                          return "A+";
 }
e.       (boolean-expression) ? (statement1) : (statement2)
Example:
         bool value = true;
 Console.WriteLine(value ? "True Value" : "False Value");
           
          Walkthrough 5: Working with conditional statements      
            Steps:
1.       Create a desktop application
2.       Design the user interface like the following figure



3.       Double click on the button
4.       Write down the code snippet in the block
                         string planetName=planetNameComboBox.Text;
                         if(planetName=="Planet")
                         {
                                 MessageBox.Show("It is in 3rd position");
                         }
                         if(planetName=="Saturn")
                        {
                                 MessageBox.Show("It is in 6th position");
                        }
                        if(planetName=="Mars")
                        {
                                 MessageBox.Show("It is in 4th position");
                         }
5.       Build the solution and run it

          Iteration Statements:
C# provides several looping mechanisms, which enable you to execute a block of code repeatedly until a certain condition is met. In each case, a statement is executed until a Boolean expression returns true. By using these looping mechanisms, you can avoid typing the same line of code over and over.
a.       For loop:
A for loop must have 3 basic parameters. It must have a loop initializer value, a loop ending value and also an increment/decrement operator. These 3 types of value can be written in any part of the for loop block. But generally, these are written in the heading part of the loop.
Example:
         for (int count = 0; count < endingValue; count++)
                                                {
                    sum += count;
                }
b.      While loop:
While loop first checks a boolean expression and then enters into the code block. This loop runs until that expression turns into false.
Example:
         while (condition == true)
                                                {
                    sum += count++; ;
                                     if (count > 50)
                                                                {
                        condition = false;
                                                }
                                                }
c.       Do-While loop:
Do while loop first executes the whole code block one time and then checks the boolean expression. If the expression is false, this loop quit execution and go to the next statements. Otherwise, it runs until it finds the boolean expression false.
Example:
                       do
                                       {
                sum += count++;
}while (count < 10);

                        Keywords:
                                    Continue:
To continue the loop operation without executing the rest of the statements on the block, continue keyword is used.
                                    Break:
                                                Break keyword is used to break the loop.
                                    Example:
for (int count = 0; count < MAXIMUM_VALUE; count++)
                      {
                    if (count == expectedValue)
                {                    
                              break;
                                                                                  }
                else
                          {
                        continue;
           }
                                                       }


          Walkthrough 6: Working with iteration statements
          Steps:
1.       Create a desktop application
2.       Design the user interface like the following figure



3.       Double click on the button and write the code snippet given below
int itemNumber = Convert.ToInt32(numberTextBox.Text);
                        for (int count = 1; count <= itemNumber; count++)
                       {
                          numberListView.Items.Add(count.ToString());
                       }
4.     Build the solution and run it

[Note: I assumed all of my readers are Computer Science Graduate so that I haven’t made the theoritical parts more lengthy.]