Monday, December 12, 2011

What is the DataGridView

With the DataGridView control, you can display and edit tabular data from many different kinds of data sources.
The DataGridView control is highly configurable and extensible, and it provides many properties, methods, and events to customize its appearance and behavior. When you want your Windows Forms application to display tabular data, consider using the DataGridView control before others (for example, DataGrid). If you are displaying a small grid of read-only values, or if you are enabling a user to edit a table with millions of records, the DataGridView control will provide you with a readily programmable, memory-efficient solution.
                                             
The DataGridView control replaces and adds functionality to the DataGrid control; however, the DataGrid control is retained for both backward compatibility and future use, if you choose. See below for details on the differences between the DataGrid and DataGridView controls.

Differences between the DataGridView and DataGrid controls
The DataGridView control provides numerous basic and advanced features that are missing in the DataGrid control. Additionally, the architecture of the DataGridView control makes it much easier to extend and customize than the DataGrid control.

The following table describes a few of the primary features available in the DataGridView control that are missing from the DataGrid control.

The DataGridView control provides more built-in column types than the DataGrid control. These column types meet the needs of most common scenarios, but are also easier to extend or replace than the column types in the DataGrid control.

The DataGrid control is limited to displaying data from an external data source. The DataGridView control, however, can display unbound data stored in the control, data from a bound data source, or bound and unbound data together. You can also implement virtual mode in the DataGridView control to provide custom data management.

The DataGridView control provides many properties and events that enable you to specify how data is formatted and displayed. For example, you can change the appearance of cells, rows, and columns depending on the data they contain, or you can replace data of one data type with equivalent data of another type.

Multiple options for changing cell, row, column, and header appearance and behaviorThe DataGridView control enables you to work with individual grid components in numerous ways. For example, you can freeze rows and columns to prevent them from scrolling; hide rows, columns, and headers; change the way row, column, and header sizes are adjusted; change the way users make selections; and provide ToolTips and shortcut menus for individual cells, rows, and columns.
The only feature that is available in the DataGrid control that is not available in the DataGridView control is the hierarchical display of information from two related tables in a single control. You must use two DataGridView controls to display information from two tables that are in a master/detail relationship

Highlight of features
The following table highlights the DataGridView’s major features. Further details about a feature can be found later in this document

Structure of DGV

The DataGridView control and its related classes are designed to be a flexible, extensible system for displaying and editing tabular data. These classes are all contained in the System.Windows.Forms namespace, and they are all named with the "DataGridView" prefix.

The primary DataGridView companion classes derive from DataGridViewElement.The DataGridViewElement class provides a reference to the parent DataGridView control and has a State property, which holds a value that represents a combination of values from the DataGridViewElementStates enumeration.

The DataGridView control comprises two fundamental kinds of objects: cells and bands. All cells derive from the DataGridViewCell base class. The two kinds of bands, DataGridViewColumn and DataGridViewRow, both derive from the DataGridViewBand base class.


The DataGridView control interoperates with several classes, but the most commonly encountered are DataGridViewCell, DataGridViewColumn, and DataGridViewRow.

DataGridViewCellThe cell is the fundamental unit of interaction for the DataGridView. Display is centered on cells, and data entry is often performed through cells. You can access cells by using the Cells collection of the DataGridViewRow class, and you can access the selected cells by using the SelectedCells collection of the DataGridView control.The DataGridViewCell type is an abstract base class, from which all cell types derive. DataGridViewCell and its derived types are not Windoyws Forms controls, but some host Windows Forms controls. Any editing functionality supported by a cell is typically handled by a hosted control.

DataGridViewCell objects do not control their own appearance and painting features in the same way as Windows Forms controls. Instead, the DataGridView is responsible for the appearance of its DataGridViewCell objects. You can significantly affect the appearance and behavior of cells by interacting with the DataGridView control's properties and events. When you have special requirements for customizations that are beyond the capabilities of the DataGridView control, you can implement your own class that derives from DataGridViewCell or one of its child classes.

An important part of understanding the structure of the DataGridView is to understand how a DataGridViewCell works.
A Cell’s Value
At the root of a cell is its value. For cells in a column that is not databound and the grid is not in virtual mode the cells actually store the value in the cell instance. For databound cells the cell doesn’t “know” or keep the value is at all. Anytime the cell’s value is needed the grid goes to the datasource and looks up the value for the column and row and returns that as the cell’s value. In virtual mode this routine is very similar except the grid raises the CellValueNeeded event to get the cell’s value. At the cell level, all of this is controlled via the DataGridViewCell::GetValue(...) method.
The data type for the cell’s Value property by default is of type object. When a column becomes databound its ValueType property is set which causes each cell’s ValueType to be updated. The value of the ValueType property is important for formatting.
Formatting for Display
Anytime the grid needs to know “how would this cell display” it needs to get its FormattedValue. This is a complex routine because formatting something on the screen usually needs to be converted to a string. For example, although you set a cell’s value to the integer value of 155 when 155 needs to be displayed it has to become formatted for the display. The cells and column’s FormattedValueType property determines the type that is used for display. Most columns use string, but the image and check box cells\columns have different values. The DataGridViewImageCell and column use Image as the default FormattedValueType since its painting code knows how to display an image. A checkbox cell\column’s FormattedValueType varies depending upon the value of ThreeState. At the cell level, all of this is controlled via the DataGridViewCell::GetFormattedValue(...) method.
By default, the DataGridView uses TypeConverters to convert a cell’s value to its formatted value. Retrieving the proper TypeConverter is based upon the cell’s ValueType and FormattedValueType properties.
For a cell, the FormattedValue is requested many times. Anytime the cell is painted or when a column needs to be autosized based upon the cell’s content; the FormattedValue is even needed when determining if the mouse is over the cell content or not. Anytime the FormattedValue is required the DataGridView raises the CellFormatting event. This provides you with the opportunity to modify how the cell is formatted.
If a cell cannot retrieve its formatted value correctly it raises the DataError event.
Part of formatting a cell for display is understanding what the preferred size of the cell is. The preferred size is a combination of the cell’s FormattedValue, any padding or additional display and the borders.
Painting the Display
After the FormattedValue is retrieved the cell’s responsible for painting the cell’s content. The cell determines the correct style to paint with (see the Styling section later in this document) and paints the cell. It is important to note that if a cell does not paint itself then nothing is painted. A row or column performs no painting, so ensure that at least a background is painted in the cell otherwise the rectangle remains invalidated (unpainted).
Parsing the Display
After the user interacts with a cell at some point the user will edit a cell’s value. One important thing to note is that the user in reality is editing the cell’s FormattedValue. When committing the value the FormattedValue has to be converted back to the cell’s value. This is called parsing. At the cell level, all of this is controlled via the DataGridViewCell:: ParseFormattedValue (int rowIndex) method.
By default, TypeConverters are used again to parse the formatted value to the real value. The DataGridView raises the CellParsing event at this time to provide you with the opportunity to modify how the cell’s formatted value is parsed.
If a cell cannot correctly parse the formatted value it raises the DataError event.

The schema of the DataGridView control's attached data store is expressed in the DataGridView control's columns. You can access the DataGridView control's columns by using the Columns collection. You can access the selected columns by using the SelectedColumns collection.Some of the key cell types have corresponding column types. These are derived from the DataGridViewColumn base class.

DataGridView Editing Controls
Cells that support advanced editing functionality typically use a hosted control that is derived from a Windows Forms control. These controls also implement the IDataGridViewEditingControl interface.
The following table illustrates the relationship among cell types, column types, and editing controls.
<><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><> <><>

Cell type

Hosted control

Column type

DataGridViewButtonCell

n/a

DataGridViewButtonColumn

DataGridViewCheckBoxCell

n/a

DataGridViewCheckBoxColumn

DataGridViewComboBoxCell

DataGridViewComboBoxEditingControl

DataGridViewComboBoxColumn

DataGridViewImageCell

n/a

DataGridViewImageColumn

DataGridViewLinkCell

n/a

DataGridViewLinkColumn

DataGridViewTextBoxCell

DataGridViewTextBoxEditingControl

DataGridViewTextBoxColumn

DataGridViewRow

The DataGridViewRow class displays a record's data fields from the data store to which the DataGridView control is attached. You can access the DataGridView control's rows by using the Rows collection. You can access the selected rows by using the SelectedRows collection.
You can derive your own types from the DataGridViewRow class, although this will typically not be necessary. The DataGridView control has several row-related events and properties for customizing the behavior of its DataGridViewRow objects.
If you enable the DataGridView control's AllowUserToAddRows property, a special row for adding new rows appears as the last row. This row is part of the Rows collection, but it has special functionality that may require your attention. For more information, see Using the Row for New Records in the Windows Forms DataGridView Control.

Friday, December 9, 2011

Creating an ActiveX Control in VB.NET

I will walk you through creating an ActiveX control that will show a simple user interface and accept input from a web page. This process will involve the following steps:
  1. Create an assembly (class library project) that contains an item of type User Control.
  2. Expose an interface for the control.
  3. Embed the user control into a web page.
  4. Transfer data from a web form to the control and display the data on the control.
Step 1: Create an assembly.
You can use the example provided for download, or simply create your own project from scratch. In this section I will outline everything you need to do in order to properly create your assembly.

Once the project is created, delete the Class1.cs file from your project as it will not be necessary. Next, add a User Control to the project by right clicking on the project in your solution explorer, choose Add, then User Control. Name your user control "myControl".

On the user control, add some UI elements, and a text box control named txtUserText. The txtUserText control will display the user data that is typed into the web form. This will demonstrate how to pass data to your User Control.
When you are done adding your user interface to the control we now have to add a key element to the control, an Interface. The interface will allow COM/COM+ objects to know what properties they can use. In this case, we are going to expose one public property named UserText. That property will allow us to set the value of the text box control.

Step 2: Expose the Interface for the control.
First, create a private String to hold the data passed from the web form to the control:
private Dim mStr_UserText as String
Place this String just inside the Class myControl.
Next, we will create a public property. The web page will use this property to pass text back to your control. This property will allow reading and writing of the value mStr_UserText.
CODES:

In this example, you will note the extra code in the set section of the public property. When a value is passed from the web form to the control we will set the private String value equal to the value passed to the property. In addition, we are simply going to modify the value of the Text Box control directly. Typically you would NOT do this. Instead, you would raise an event and then validate the data being passed by examining the private variable mStr_UserText. Then you would set the value of the Text Box Control. However, that would add significant code to this example and for simplicity sake I am omitting that security precaution.
Now that you have a public property that .NET assemblies can use, you need to make that property available to the COM world. We do this by creating an Interface and making the myControl class inherit the interface. This will allow COM objects to see what properties we have made available.

Your code will now look like this: 

CODES:

Notice that we now have an interface defined, the interface tells COM/COM+ that there is a public property available for use that is of type String and is readable (get) and writeable (set). All we do now is have the Class myControl inherit the interface and viola! We have a .NET assembly that acts like an ActiveX Control.

Step 3: Embed the user control in a web page.
The last thing we do now is use the control in an example web page.
CODES:

You will notice in the HTML code above, that you call your .NET assembly very similar to an ActiveX control; however there is no GUID, and no .OCX file. Your CLASSID is now the path to your DLL and the Namespace.Classname identifier. Refer to the code above to understand the syntax of the CLASSID object tag property. Place the HTML file and your DLL in the same directory on your web server and navigate to the HTML document. (Do not load the HTML document by double clicking on it, navigate to it in your browser by using the Fully Qualified URL.) *NOTE: You might need to add your web server to your Trusted Sites list in your Internet Explorer browser.

Step 4: Transfer data from the web form to the user control.
When you load the HTML page, your control should load into the page and you will see a web form with a text box and a button. In this example, if you type some text into the text box and click the button, it will use JavaScript to send the text from the web page form, to the User Control that you just built. Your User Control will then display the text in the Text Box control that I on the form.There are many issues that you should investigate in order to properly create User Controls that work on a web page. .NET Security plays a big part in what you can actually do within the confines of your code. You should also investigate code signing your control.

Working with MSChart in VB.Net

The MSChart control is an ActiveX control that lets you to add charting capabilities to your applications. We can create 2D or 3D charts in different styles. It will support almost all type of chart like Line Chart, Bar Chart, Pie Chart, Step, Combination, XY (Scatter) etc. . We can Add/Delete/Modify any items in the chart, such as Axis title, Axis scale, footnotes, data point series, and so on. You can even rotate the graph, add backdrop color or images to virtually any element of the chart. At run time, users can select portions of the chart and move and resize them at will, if you want to provide them with this capability.


Since MSChart is not a standard component so it will not visible in the toolbox, we need to add it manually. For adding Chart to your Project do the following steps:

1. Right Click The toolbox , click Choose Items- Choose Toolbox Items, new window comes with name “Choose Toolbox Items”

2. from that Select COM Components 

3. From the controls Select by checking -> Microsoft     Chart Control(6.0) (SP4)(OLEDB)







 5. Now double click the Chart Icon In the components, chart will appeared in your form, you need to enlarge that one to get propped view






Setting the Property of the Chart

We can set the property of the chart by Property Page or by Property Window:

a. Property Page
Right click the MSChart and select Properties, then a new window will appear (Property Page)



There are 8 property tabs in Property Page
1. Chart
In this tab we can select the type of chart, like 2D line or 3d line graph like that
2. Axis
In this tab we can set the Axis Color, Width, Scaling of axis etc
3. Axis Grid
In this tab we can set the Axis Major Gridlines Style, Width, Color etc
4. Series
In this tab we can set how much series we required, there will be option for hide and exclude the series and some built-in statistical function like Mean, Standard Deviation, regression etc that will automatically calculate and assign to series. By default there will be only 4 series, if want more then we need to add the programmatically (will explain later)
5. Series Color
In this tab we can set the Series Color, style and Width
6. Fonts
In this tab we can set the font, font style, size, effects and color for Title, Footnote, Legend and Axis Labels
7. Text
In this tab we can set text for 3Axis (X-Axis, Y-Axis, Second Y-Axis) and Footnotes
8. Backdrop
In this tab we can set Color and pattern for Chart, Title, Footnote, Legend and Plot

b. Property Window
By using Property window also you can set properties

Making Chart with MSChart

The topmost object of this hierarchy is MSChart, which lets you set the general characteristics of the chart and also exposes several custom events. All the other objects in the hierarchy are dependents of MSChart.

The MSChart associated with a DataGrid Object, This datagrid will store whatever the value we pass to the chart. We can pass valve to chart data grid directly or from spread sheet or from database. The Plot object is a compound object (that is, an object with other child objects) that contains all the graphical information about the data series (color, markers, backdrop pattern, position and attributes of light sources, and so on). The Title, Legend, and Footnote objects are compound objects with similar structures and control over the features of the relevant elements of the chart (text, color, position, and so on).
This example shows how to make a simple MSChart from database (MS Access).
1st step to create a database with 4 fields- Sample, Values, Max, Min and make fields as Sample- Text, Values- Number, Max- Number, Min-Number, then add some values for each column.

Then Open Microsoft VS and click on file menu, then from New select New Project, new project window will appear and from that select Visual basic ->windows Application and press ok.

New form will appear and on that add reference to the project because we are using MS access as database, fro that click on project menu and then click on add reference
New window will appear and from that select COM tab and select Microsoft ActiveX Data Objects 2.0 Library, then press OK
Create a data base with four fields (Sample, Values, Max, and Min) , place the database in bin folder of your application, then add MSChart control and Button Control to form as explained in the starting section. Then Right click the Solution Explore and then click Add and click on the Module.


Then add this code to module 

Public cn As ADODB.Connection
Public rs As ADODB.Recordset
Public cmd As String
Public Sub Connection()
On Error GoTo xx
cn = New ADODB.Connection
cn.CursorLocation = ADODB.CursorLocationEnum.adUseClient
cn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & My.Application.Info.DirectoryPath & "\database1.mdb"
If cn.State = ADODB.ObjectStateEnum.adStateClosed Then
cn.Open()
End If
Exit Sub
xx: 
MsgBox(Err.Description, MsgBoxStyle.Critical, "Error ...")
Exit Sub
End Sub

Then in the main form add one Button and MSChart control to the form and in the in the property of MSChart set the property that is color, axis etc (change chart type to Line, add Title, X and Y axis name from Text tab etc) and write the below code in the button click

Call Connection()
rs = New ADODB.Recordset
cmd = "select Sample,Values, Max, Min from Table1"
rs.Open(cmd, cn, ADODB.CursorTypeEnum.adOpenKeyset)
rs.MoveFirst()
With MSChart1
.ShowLegend = True
.EditCopy()
.EditPaste()
.DataSource = rs
End With

Then run the project and click on the button

Some Useful Property 

1. Providing X and Y axis value
For that 1st value scale auto value false, after that you can specify maximum and minimum value
MSChar1.Plot.Axis(MSChart20Lib.VtChAxisId.VtChAxisIdX).ValueScale.Auto = False
MSChar1.Plot.Axis(MSChart20Lib.VtChAxisId.VtChAxisIdX).ValueScale.Maximum = 100
MSChar1.Plot.Axis(MSChart20Lib.VtChAxisId.VtChAxisIdX).ValueScale.Minimum = 10
MSChar1.Plot.Axis(MSChart20Lib.VtChAxisId.VtChAxisIdY).ValueScale.Maximum = 50
MSChar1.Plot.Axis(MSChart20Lib.VtChAxisId.VtChAxisIdY).ValueScale.Minimum = 5

2. For Labeling X and Y axis
Mschart1.Plot.Axis(MSChart20Lib.VtChAxisId.VtChAxisIdX).AxisTitle.Text = "XXXXXX"
Mschart1.Plot.Axis(MSChart20Lib.VtChAxisId.VtChAxisIdY).AxisTitle.Text = "yyyyyyy"

3. Setting X and Y axis division
Set auto scale value of both axis to false
Mschart1.Plot.Axis(MSChart20Lib.VtChAxisId.VtChAxisIdX).ValueScale.MajorDivision = 20
Mschart1.Plot.Axis(MSChart20Lib.VtChAxisId.VtChAxisIdX).ValueScale.MinorDivision = 5
Mschart1.Plot.Axis(MSChart20Lib.VtChAxisId.VtChAxisIdY).ValueScale.MajorDivision = 10
Mschart1.Plot.Axis(MSChart20Lib.VtChAxisId.VtChAxisIdY).ValueScale.MinorDivision = 2 

4. Selection Property
Returns or sets a value that indicates whether or not users can select chart objects. True is the default value-The user can interactively select chart objects. False means the user cannot select chart objects.
MSChart1.AllowSelections = True / False

5. Adding more series (Default value 4)
ColumnCount property sets the number of columns in the current data grid associated with a chart.
MSChart1.ColumnCount = 10

6. Setting color and width of Series
For color –setting RBG format
Mschart1.Plot.SeriesCollection(1).DataPoints(1).Brush.FillColor.Set(250,250,)

For width -For that set the Width Property, need to specify Width in Point
MSChart1.Plot.SeriesCollection(1).Pen.Width = 25

7. Making Series Invisible 
For that need to set the ShowLine property to false, default value is zero
MSChart1.Plot.SeriesCollection(1).ShowLine = False

8. Add legend 
MSChart1.Legend.Location.LocationType =_ MSChart20Lib.VtChLocationType.VtChLocationTypeBottom
MSChart1.Legend.Location.Visible = True


Developing Desktop Applications




Windows Forms is a set of classes that encapsulates the creation of the graphical user interface (GUI) portion of a typical desktop application. Previously, each programming language had its own way of creating windows, text boxes, buttons, etc. This functionality has all been moved into the .NET Framework class library—into the types located in the System.Windows.Forms namespace. Closely related is the System.Drawing namespace, which contains several types used in the creation of GUI applications. The capabilities provided by the types in the System.Drawing namespace are commonly referred to as GDI+. In here, we'll examine the form (or window) as the central component in a classic desktop application. We'll look at how forms are programmatically created and how they're hooked to events. We'll also examine how multiple forms in a single application relate to one another and how you handle forms in an application that has one or more child forms. Finally, we'll discuss two topics, printing and 2-D graphics, that are relevant to desktop application development.

Friday, December 2, 2011

Object Oriented Programming Concepts

There are various approaches to solve a problem. Moreover, these approaches are to a great extent dependant upon how each one of us tries to analyze and solve the problem.

We have a very simple assignment:
Lets say we want to calculate a distance formula for traveling from one place to another. The distance formula has to include all the attributes of the journey. So let us see what data do we have-
Variables:
Location: Have to go from one city to another (both the cities can be anywhere
in the world).
Modes of travel: Car/Bus/Train
Date constraints: Departure/Arrival Date.
Time Preference: Morning/Afternoon /Evening
Distance: Break Journey
Travel Cost. Etc


Now, we have termed these data items as “variables” because their value would be changing based upon the various choices made. Even for such a trivial problem, there are being so many options/constraints,there are so many approaches to arrive at a decision. On similar lines, given a problem and basic resources (which also act as constraints), various algorithms can do the task programmatically. An algorithm is nothing but the thought process/approach involved.

A good approach should
  1. Be generic so that it works well with all possible combinations of inputs.
  2. Flexible / adaptable to absorb new inputs. (New destination, routes, rates,
    timings or even new mode of travel - say space travel)
  3. Give solutions in the desired time frame.
  4. Make best use of resources available. (Optimize the solution)
  5. Cost effective.
  6. Simple enough.
Primitively, there was a very straightforward manner to write applications. Straightforward in the sense that the various tasks in the application would be identified and would be automated. This approach did work for many scenarios but when it came to the robustness or maintenance of the application, this approach proved to be insufficient.

In this section we will first discuss what was the procedural approach and how the design of an application be made using this approach. By trying to figure out the negative points in the approach we will then appreciate the advantages of object oriented programming by discussing it as a solution to overcome the shortcomings of procedural programming.

Concept of Procedural Programming
The whole core of procedural programming lies in deriving a straightforward sequential step-by-step guide to do a particular task. Let us understand this by analyzing a case study. 

Lets take up a classic Payroll application that deals with various types of specifications for different employees. Lets say that this application is developed in one of the best procedural languages – C.

So, the “Employee” in the application will be represented by a structure, which will contain all the Employee attributes as data members of the structure. Assume that the application deals with three types of employees – Clerk,Manager and Marketing executive. All the employees do have some common attributes and certain specific allowances (lets not talk of deductions!). The clerk gets medical allowance, the executive gets the traveling allowance and the manager gets house rent allowance and dearness allowance. Our Employee structure might look something like this:

CODES:
The application would have functions, which would act upon the data, and do the necessary functionalities. So there would be at least following functions apart from others:
CODES:

This also could have been done having three different structures one for each Employee type but this would increase the overhead in programming in the functions and there would be a requirement of declaring three different arrays;one to store all clerk variables, one for manager variables and one for executive.
So let us have a common structure, which would suite all the employee types.


If we try to figure out the central algorithm of every function it would be quite monotonous wherein every function would have a strict type inspection routine to check the type of Employee every time. Because the functionalities differ for every type of Employee.

CODES:

This kind of type inspection will be featuring in every function, which would be dependant upon the type of the Employee.Now, if we have to add a new Employee type to this application, which has its own specification about, the allowances received try to figure out the changes that we will have to do in the current case study. Not only will the Employee structure have to be modified but also even the functions have to be changed in order to accommodate the new Employee type. So just as we are currently
having a case statement to correspond to one employee type, we will have to introduce one more case statement corresponding to the new employee type. In addition, while calculating the salary we might introduce some local variables in the function to do the necessary calculations. There is a probability that the new additions may lead to certain bugs being introduced in the current “working” code. So let us list down the various problems we would face in this application:


Maintenance: If the application has to support some change in the existing business logic for a particular employee type there might be more problems introduced since it is the same function that would be called for the different employee types.


Enhancement: When the application has to be enhanced further to add a new type of employee there would be changes made in all the functions,which depend upon the type of employee. Hence enhancing an application further would be quite hectic. Why only new type of employee? Even if have to add a little more functionality to an existing function it would prove quite cryptic.


Extensibility: The current design of the application does not allow us to have extensibility easily. Therefore, if we have to add more functions, which would do certain tasks for all the employee types or maybe for some of the type of employees; the new function also will have a strict type inspection routine to check for the type of employee.

Storage: A small but significant problem. Whenever we have the data saved in a persistent storage i.e. having the data into files on the hard disk we will have to take care of saving the data along with the appropriate type of the employee. Also, while reading the data from the file its necessary to read the type first and then accordingly initialize the members in the structure. 



If we try to look for the core problem in the application design which can be qualified as a cause for all the problems discussed above it definitely would be an attempt to design a common algorithm to suit all the types of employees. It would definitely prove helpful if rather than concentrating on the procedures we concentrate more upon the entities in the application.


Object Oriented Programming
Now with the major shortcomings of procedural programming let us look at how a different approach would help us. As mentioned earlier it is necessary to concentrate more upon the entities in the application and not only upon the tasks done by the application.


Based upon this bottom line we have a certain set of rules defined as object oriented paradigm. If a programming language satisfies these rules i.e. provides certain features or keywords to implement these rules it would be qualified as an object oriented programming language. Lets discuss the major conventions for object-oriented programming.



Classes
One of the major problems in the earlier approach was also the data and the functions working upon the data being separate. This leads to the necessity of checking the type of data before operating upon the data. The first rule of the object-oriented paradigm says that if the data and the functions acting upon the
data can go together let them be together. We can define this unit, which contains the data and its functions together as a class. A class can also be defined as a programmatic representation of an entity and the behavior of that entity can be represented by the functions in the class. In our earlier case study the employee, can be represented as a class. A class will contain its data into various variables, which would be termed as data members and the behavior of the class, which will be encapsulated, as functions will be termed as member functions.




Encapsulation
Many a times when we use certain tools, we hardly pay attention to the details about the functionality of the tool. We hardly pay attention to the various other units, which make up the tool. This behavior to ignore unwanted details of an entity is termed as abstraction. 

Now if the details are unwanted why show them to the user? Therefore, the creator might attempt to hide these unwanted details. This behavior is termed as encapsulation. So we can say that encapsulation is an implementation of abstraction. Encapsulation directly leads to two main advantages:

Data Hiding: The user of the class does not come to know about the internals of the class. Hence, the user never comes to know about the exact data members in the class. The user interacts with the data members only through the various member functions provided by the class.


Data Security: Since the data, members are not directly available to the user directly but are available only through the member functions a validity check can always be imposed to ensure that only valid data is been inserted into the class. So a Date class, which contains individual data members for storing date, month and year, will have it ensured the month is never 13 or the date is never exceeding 31



Inheritance
What is common between a father and a son? At least one thing would be common – their assets!


In real life, inheritance allows us to reuse things that belong to a particular entity. Also, in object oriented world a class can inherit the properties and functionalities defined in some another class so that they can be reused. Then we have to be a bit careful in designing these classes because reusability cannot be done unless the classes are of the same type. So the class which would be reusing the functionalities of the other class in object oriented terms we would say that the class is “deriving” from the former class and is termed as the derived class. The class that is being “derived from” is termed as the base class.Inheritance directly results in the following benefits:


Reusability: Inheritance results in functionalities defined in one class being reused in the derived classes. So the efforts of rewriting the same functionality for every derived class is being saved. This definitely saves a lot of development time.


Enhancement and Specification: Due to the characteristic of inheritance, we can club the common functionalities in the base class and have the specific functionalities in the derived class. This feature can be used to have a functionality defined in the base class to be further modified for betterment or specification by the derived class. This mechanism of redefining the functionality of the base class in the derived class is termed as “overriding”


Avoiding type inspection: In the case study that we discussed to understand procedural approach we had a strict type inspection routine at the library end wherein in every function in the library we had to check for the type of the employee for whom the work has to be done. With inheritance, we would have a common base class called as “Employee” which would have all the common functionalities defined where as the specific routines do be done for various types of employees would go in the respective derived classes. So there would be class defined for every type of employee and the class would all the specifications for that type of employee and would be derived from the base class Employee to inherit the common functionalities. Therefore, in the functions now we wont have to check for the type of employee every time because every employee type has its own specific routines defined within it.



Polymorphism
The word “polymorphism” means “different forms”. Applied in object-oriented paradigm it means the ability of an entity to exhibit different forms at runtime.


However, why would such a kind of feature be required? One major reason to have this is to eliminate the type inspection. As we can see in the earlier case study that we discussed there would also be a type inspection checking at the client application level where in the employee entities would be used. So just as in every functionality, we had checked for the type of employee we will also have to check in the main function about the type of employee we are handling. With polymorphism, we can have this level of type inspection also being eradicated totally.



How does .NET support object oriented programming?
As we have discussed in the earlier sections .NET happens a to be a “complete framework”. The basic approach adopted by the framework is object-oriented and the framework would support only object-oriented code. So no more C and COBOL applications! Although C++ and OO-COBOL would work perfectly fine.



Since the framework is inherently object-oriented everything i.e. every data type in the framework will be a class. Unlike C++, even the primitive data types will be given by the framework as a set of classes. 

The framework also provides us with a rich set of classes which can be used by instantiating them or writing new classes by deriving from the framework classes. The framework does have a systematic organization of classes wherein the Object class from the System namespace (we will discuss namespaces in details later) tops the chart. All the other classes are derived from the Object class.

Component Oriented Programming

However, is it really enough just to have an object oriented approach? Well, now with the increasing influence of the web and code reusability getting extended across the language barriers its very much essential to even extend “Object Oriented approach “ itself. 


We need to extend the definition of the “class” which happens to be the basic element of object oriented programming. We know that the class serves as an abstraction or simulation of a real life entity. However, in order to have a total encapsulation the internals of the class has to be totally hidden. Secondly, the class should be instantiable across various programming languages to have a more range of reusability. The class should ideally support properties (will be discussed a little later) to offer more user friendliness and overcoming the incompatibilities.

Therefore, a class must have the following extra abilities in addition to what it serves in object-oriented scenario:

  • Encapsulated data and implementations
  • Properties
  • Language Interoperable
We can term instance of such a class as a “component”. VB.NET and C# happen to be component- oriented languages in a way that every class created in any of these languages when instantiated results in a component.

Understanding C# and VB.NET as Object Oriented Programming languages
After knowing the object-oriented concepts let us examine how these concepts can be implemented in CSharp (C#) or VB.NET. These two languages are been introduced along with the .NET framework and are totally .NET compliant. So VB.NET will be a natural upgrade for VB programmers and CSharp for C++ programmers. We will be looking at the various syntaxes of both these languages to implement object oriented programming.