Category Archives: IT Consulting

  • 4

MVC Architecture

MVC architecture  is basically designed to separate the business logic and application data from the presentation data to manage easily.
MVC stands for L Model – View – Controller

1).  Model: The model object knows about all the data that need to be displayed. It is model who is aware about all the operations that can be applied to transform that object. It only represents the data of an application. The model represents enterprise data and the business rules that govern access to and updates of this data. Model is not aware about the presentation data and how that data will be displayed to the browser.

2). View : The view represents the presentation of the application. The view object refers to the model. It uses the query methods of the model to obtain the contents and renders it. The view is not dependent on the application logic. It remains same if there is any modification in the business logic. In other words, we can say that it is the responsibility of the of the view’s to maintain the consistency in its presentation when the model changes.

3). Controller:  Whenever the user sends a request for something then it always go through the controller. The controller is responsible for intercepting the requests from view and passes it to the model for the appropriate action. After the action has been taken on the data, the controller is responsible for directing the appropriate view to the user. The views and the controllers work very closely together.

Advantages of using the MVC Architecture.

1. Code developed using MVC is resuable
2. When the problems recurs, there is no need to invent a new solution, we just have to follow the pattern and adapt it as necessary.
3. By using the MVC design pattern our application becomes more expressive.
4. Expaning of an application is very easy as business logic is seperated from UI.
5. Tomorrow if you need to switch the database from, say, SQL to Oracle you dont need to change the whole application, only the Model layer will be changed.


Bookmark and Share


  • 28

Tips for Creating a better E-Commerce Application

E-Commerce, A name started few years back and now ruling the world. Most of the companies started their E-Commerce portals to sell products online to increase their sales and some are even only online portals they don’t have off line stores and they sell some one else’s products.

Now a days people want the products at their door steps. If your services are on time then no one can beat you in E-Commerce, Following are few of recommendations to develop an E-Commerce Application:

1. A neat and clean website design

Your website UI design must be very clear and soothing that users visit again and again, atleast to review the design.

2. Avoid Ads:

if you want to show some Ads go for internal Ads, Like Ad of one of your product which is going to appear on other page

3. Easy to find Products:

Put a Search box, so that users can easily find the products on website, People don’t remember SKUs so make the search keyword enabled, better to go for Full Text Search.

4.  Better Searched Results Page:

The search results page should be interactive enough to display the maximum products and at the same time the page should not be cluttered enough that irritates the customer to find the required product.

5. Put Drill Down on Searched Results:

The successful websites like Amazon, E-Bay, CNET etc have the Drill Downs impemented on the searched results. Suppose user entered the keyword “Laptop” in the search box, Now it will display the list of all the laptops in the searched results but the true E-Commerce leader will display the searched results as the Groups of Laptops. Grouping by Brand, Grouping By common paratmeters like screen size, RAM, Processor, Next Generation Processors, Price Slabs (500$ – 800$, 1000$ to 1200$) etc so that user’s can easily idetify the product that they required.

6. Product Details Page:

Your  product details page is very important for the user, as its going to behave like a Sales Man, Display the product with Multiple pictures, one picture on the screen of medium size and show some icons of the images below the main image and let the user to view the bigger images. Give all the four views of a product to user for his satisfaction.

Dont write very long descriptions, describe important points and give a summary too.

7. Product Variants:

Display variants of products on Product Detail Pages. When you enter a shop and check a laptop the sales person will also show you the different models of that laptop or different skins available for that so that you can have options to buy. similarily this page is your sales man.

8. Shopping Cart:

Make an interactive shopping cart, easy to operate where the quantity of the prodcuts can be altered.

9. Easy Checkout:

There should be an easy checkout system, Users should be able to enter multiple Shipping addresses while let them have only one billing address and store those shipping and billing addreses for future usage.

10. Payment Gateway Integration:

Always go for Secured and known payment Gateways like paypal, google that people can trust over.

11. Use SSL certificate to make the pages secured:

Its very necessary for you to implement the SSL certificate to prevent fraud and theft of your important information.  Users will not trust your site untill it has the SSL installed – i mean https://

12. Display Secured Logos:

Display the logo of that SSL provider on your website that let the users know that the site is secured. there are various organizations who keep on testing your websites and make sure that your website is hackers safe and fraudulent free. Like Hackerssafe. keep these logos on your website that will assure users that your site is protected and safe which will eventually increase your site traffic.

13. Let the people sell your Products on their sites:

Pubish the XML / CSV feeds. Let people subscribe to that. In this way, your product selling will increase and your brand will be promoted.

14. Google Page Rank:

Google page rank play an important role in E-Commerce Applications, Now a days users are more smart than the programmers. They know the importance of Google Page Rank and they know if a site has high Page rank (atleast PR-4) that means that site has importance in Google eyes and will be Good. Click here to find steps to increase Google Page Rank

15 Alexa Page Rank:

Alexa page rank defines the usage of the site. It shows the rank of a page as per the visits of  the users. so user can some to know how popular is your site is.

These were few steps to make your e-commerce application as the best E-Commerce application.

We at Zonix develop these E-Commerce Application, if you would like to go for that – contact at www.zonixsoft.com or email at sales@zonixsoft.com. Few more things are more which we will be publishing in near future. Keep visiting.

Bigbuyindia is an E-Commerce Portal where you can buy India Jewellery products.


Bookmark and Share


  • 0

Multiple Active Result Sets (MARS – ADO.NET 2.0)

Multiple Active Result Sets (MARS) is a feature in ADO.NET 2.0. It allows execution of multiple batches against Database on a single connection. Preeviously, only one batch could be executed at a time against a single connection. But, execution of multiple batches with MARS does not mean like simultaneous execution of operations.
In previous versions of SQL Server; to access multiple result sets using SqlDataReader objects, a separate SqlConnection object must be used with each SqlCommand object. In ADO.NET 2.0 / SQL Server 2005; MARS feature is disabled by default. It can be enabled by adding the “MultipleActiveResultSets=True” keyword pair to your connection string, as below:

string connectionString = @”Data Source=GTL-263SQLEXPRESS;Initial Catalog=master;Integrated Security=SSPI;MultipleActiveResultSets=True“;

Example:

Without MARS, you could only run one batch per connection. some what like below Example:

private void NoMarsImplementation()
{
SqlConnection conn = new SqlConnection(@”Data Source=GTL-263SQLEXPRESS;
Initial Catalog=master;Integrated Security=SSPI;”);

string sql1 = “SELECT * FROM [Customer].[TBL_Customer]”;
string sql2 = “SELECT * FROM [Supplier].[TBL_Supplier]”;

SqlCommand cmd1 = new SqlCommand(sql1, conn);
SqlCommand cmd2 = new SqlCommand(sql2, conn);
cmd1.CommandTimeout = 500;
cmd2.CommandTimeout = 500;
conn.Open();
SqlDataReader dr1 = cmd1.ExecuteReader();
// misc. code with dr1
conn.Close();

conn.Open();
SqlDataReader dr2 = cmd2.ExecuteReader();
// misc. code with dr2
conn.Close();
}

Above Example shows that you can use the same connection with the second SqlDataReader only when you finished using the connection with first one. The connection must be closed and reopened to use same Connection with Second SqlDataReader. Otherwise you would get this error – “There is already an open DataReader associated with this Command which must be closed first”.

with MARS, it is possible to use a single opened connection for more than one batch. Check out below code:

private void MarsImplementation()
{
SqlConnection conn = new SqlConnection(@”Data Source=GTL-263SQLEXPRESS;
Initial Catalog=master;Integrated Security=SSPI;MultipleActiveResultSets=true;“);

string sql1 = “SELECT * FROM [Customer].[TBL_Customer]”;
string sql2 = “SELECT * FROM [Supplier].[TBL_Supplier]”;

SqlCommand cmd1 = new SqlCommand(sql1, conn);
SqlCommand cmd2 = new SqlCommand(sql2, conn);
cmd1.CommandTimeout = 500;
cmd2.CommandTimeout = 500;
conn.Open();
SqlDataReader dr1 = cmd1.ExecuteReader();
// misc. code with dr1
SqlDataReader dr2 = cmd2.ExecuteReader();
// misc. code with dr2
conn.Close();
}

In this way, using MARS, you can simply execute an SqlDataReader that will open a Read-Only Cursor; use data from that SqlDataReader and perform Insert / Update function against Database. You only need to Open the SqlConnection object once before you execure the SqlDataReader and Close the Connection (without re-openning) at last after performing Insert / Update function.

Here is another Example, in which we retrieve records from Category Table which is having ParentCategoryID as 0 thru SqlDataReader and Update the Product Table records which is having CategoryID from SqlDataReader.

private void MarsImplementation()
{
//connection string
string connectionString = @”Data Source=GTL-263SQLEXPRESS;Initial Catalog=master;
Integrated Security=SSPI;MultipleActiveResultSets=true;“;

SqlTransaction updateTran = null;
//sqlCommand to open SqlDataReader
SqlCommand catCmd = null;
//sqlCommand to update the Product table
SqlCommand updateCmd = null;

int CategoryID = 0;

//Query to fetch the categories with ParentCategoryID having 0
string catSQL =
“SELECT CategoryID, Name FROM Category ” +
“WHERE ParentCategoryID = 0”;

//update all the product’s quantity which is having CategoryID from above Query
string updateSQL =
“UPDATE Product ” +
“SET Qty = Qty + @OrderQty ” +
“WHERE CategoryID = @CategoryID”;

using (SqlConnection Connection =
new SqlConnection(connectionString))
{
Connection.Open(); //open the connection once here
updateTran = Connection.BeginTransaction();

catCmd = new SqlCommand(catSQL, Connection);
catCmd.Transaction = updateTran;

updateCmd = new SqlCommand(updateSQL, Connection);
updateCmd.Transaction = updateTran;
updateCmd.Parameters.Add(“@Qty”, SqlDbType.Int);
updateCmd.Parameters.Add(“@ProductID”, SqlDbType.Int);

//execute the sqlDataReader
using (SqlDataReader catReader = catCmd.ExecuteReader())
{
while (catReader.Read())
{
CategoryID = (int)catReader[“CategoryID”];

updateCmd.Parameters[“@OrderQty”].Value = 100;
updateCmd.Parameters[“@CategoryID”].Value = CategoryID;
//perform Update against Product table with same connection
//without closing and re-openning it again
//having SqlDataReader already openned
updateCmd.ExecuteNonQuery();
}
}
updateTran.Commit();
}

}


Bookmark and Share


  • 6

Move a SharePoint Content Database / Deploy sharepoint site

our Official website (http://www.zonixsoft.com)

You have two initial options, doing a backup and restore within MOSS to move the data, or doing it at the SQL/STSADM level.  I prefer the latter, as it isn’t nearly as inclined to fail and leaves you with more flexibility.

1) Find the content Database

These are listed under Central Admin->Application Management->Site Collection List

2) Backup the content database

You could alternatively detach it, and copy it.  Just doing a backup in SQL Server 2005 Management studio is easier.

3) Restore content database to new server

Copy the BAK file to new server.  Create an empty DB in Management Studio, restore from backup, you may need to change an option in the “options” tab of the restore dialog to get it to work.  (Overwrite db).

4) Create Web App on new Server

Central Admin->Application Management->Create or extend Web App->Create New Web App.

5) Associate restored DB with new Web App

Central Admin->Application Management->

SharePoint Web Application Management->Content Databases->

Remove Content Database from your new web app.

Now use STSADM to add restored DB to this web app

c:program filescommon filesmicrosoft sharedweb server extentions12bin on new server is where you can find the STSADM.

run this command from there.

stsadm -o addcontentdb -url http://yourwebapp:port -databasename yourcontentdb -databaseserver yoursqlserver

6) Run ISSRESET from command prompt.


Bookmark and Share


  • 0

Web Parts

Visit: http://www.zonixsoft.com

This article discuss about the Web Parts, new feature introduced in ASP.NET 2.0. Web Parts are objects which the end user can open, close or move from one zone of the page to another. Web Parts allows for personalization of page content. They allows users to move or hide the Web Parts and add new Web Parts changing the page layout.

Web Parts Modes

Modes are very powerful in that they enable user to edit Web Parts, delete the Web Parts or customize Web Parts.

m    a) Normal mode: End user cannot edit or move sections of page. Simple Browser mode.

m    b) Edit Mode: End user can edit Web Parts on the page including Web Parts title, setting custom properties.

m    c) Design Mode: End user can rearrange the order of the page Web Parts in a WebPartZone.

m    d) Catalog Mode: End user enjoys the choice to add new Web Parts in any WebPartZone on the page.

Web Part Manager:-

Web Part Manager control is server control that completely manages the state of the zones . This control doesn’t have any visual interface,. You can have only one WebPartManager for each page that works with Portal Framework.

Web Part Zone:-

You can declare each web zone in one of two ways. You can use the <asp:WebPartZone> element directly in the code, or you can create the zones within the table by dragging and dropping Web Part Zone controls onto the design surface. You can place anything in zones including HTML elements, web server controls, user controls and custom controls. Any thing placed into WebPartZone can be treated as Web Part. Useful attributes of WebPartZone include LayoutOrientation attribute which controls the display of items either horizontally or vertically.

Catalog Zone:-(To add new Web Part)—-Catalog Mode

The ASP.NET 2.0 Portal Framework enables an end user to add Web Parts, but you must also provide the end user with a list of items he can add. It is designed to allow for categorization of the items that can be placed on the page. Catalog Zone is also a template control. The Catalog Zone control contains a title and checkbox list of items that can be selected. The Catalog Zone control also includes a drop down list of all available Web Part Zones on the page. From here, you can place the selected Web Parts into one of the Web Part Zones available from the list.

CatalogZone Contains CatalogPart controls like DeclarativeCatalogPart, PageCatalogPart, and ImportCatalogPart.

·       PageCatalogPart: Provides a page catalog of Web Part controls that a user has closed on a Web Parts page, and that the user can add back to the page.

·       DeclarativeCatalogPart: Enables developers to add a catalog of Web Part controls to a Web page so that users can choose whether to add them to a page.

·       ImportCatalogPart: Imports Web Parts controls, so that the control can be added to a web page with pre-assigned settings.

Changing mode of page:-

You can use either WebPartManager class directly or through the use of WebPartManager server control, you can change the mode of page. Changing the mode allows the user to make changes to pages they are working with. All the changes (mode changes) are recorded to ASPNETDB.MDF database associated with app_data directory created exclusively for Web Parts. Using WebPartManager object, you can add new Web Parts to the page. It also enables end user to drag and drop elements around the page.

Moving Web Parts—Design Mode

We can also move WebParts from one zone to another zone. This is possible through Design mode. To move any control just hover mouse over title of the control and you can see crosshair mouse symbol. Click the left mouse button and hold the Web Part and drag it to any WebPartZone. While dragging, the control it becomes transparent and drops the control in WebPartZone.

Editing the Web Parts—Editing Mode

Another Web Part mode that allows end-user to edit the Web Parts is Edit mode. This mode enables users to modify the settings related to behavior, appearance and layout for a particular Web Part on the page. When the user change the mode to edit you can see Appearance Editor/Layout Editor appear in the EditorZone. Appearance section allows users to change title and how the title of Web Part appears. Layout section enables user to change the order in which Web Parts appears in a zone or move Web Parts from one zone to another. Behavior section enables site editors to change dynamics of how end user can modify Web Parts.

Connection Between Webparts:-

Web parts are also capable of exchanging data between them, using web part connections. Using connections, you can have one web part provide one or more property values that can be used by other web parts on the page.

A WebPart Connection is a mechanism for sharing or transferring data from one Web Part (called the provider) to another Web Part (called the consumer). it is the ability to expose an interface to a WebPart (Provider) that another WebPart (Consumer) can connect to and use it

·       Connection types

Provider :-
– Control that provides data information
– Implements a provider connection point
– Defines a call back that returns an instance of the interface
– One provider connection point can connect to any number of consumer connection points of the same type

Consumer :-
– Control that gets data
– Implements a consumer connection point
– Defines a call back that gets an instance of the interface return by provider
– One consumer connection point can connect to only one provider connection points of the same type

·       Connection To establish a communication channel between provider and consumer WebParts so that they can exchange required information as defined in communication contract. A connection is establish between two connection points.The ConnectionPoint base class defines an object that is associated with a consumer or provider and contains the details necessary to exchange data. The ProviderConnectionPoint is associated with the provider, and the ConsumerConnectionPoint is associated with the consumer.

you must specify the following required attributes in addition to the id and runat attributes:

·       ConsumerID – Indicates the ID of the consumer control in the connection.

·       ConsumerConnectionPointID – Indicates the ID of a special callback method in the consumer used to establish the connection. This attribute is required only if the consumer has more than one connection point. For details on connection points, see ConnectionPoint.

·       ProviderID – Indicates the ID of the provider control in the connection.

·       ProviderConnectionPointID – Indicates the ID of a special callback method in the provider used to establish the connection. This attribute is required only if the provider has more than one connection point.

Courtesy: The Seo Guru, A Software Development Company, Best OOPS Blog Site, Link Submission, Thanks to Shopping  Site for Link Exchanging


Bookmark and Share



  • 21

Some very special features of crystal reports

Visit: .comhttp://www.zonixsoft

Create a Watermark

A watermark is a graphical or textual element that is placed behind the rest of yourreport. Examples of useful watermarks are your company logo, the word “Draft,”or other items that you may want to appear right behind the rest of the elements of your report.

 

1. Open the report you wish to add the watermark to. Ensure that the Designtab is selected.

2. Position your mouse over the gray Page Header section name. Right-click.

3. Choose Insert Section Below from the pop-up menu. This will insert a second page header section (you’ll now see Page Header a and Page Header b).

4. Insert the graphic or text you want to appear behind the rest of the report into Page Header b (it’s helpful if the graphic has been lightened with a graphic editing program, or if the text is formatted with a light shade of font color).

5. If you want the watermark to appear more toward the vertical center of the page, make Page Header b taller and move the graphic or text farther down in the section.

6. If you want to repeat the watermark more than once on a page, insert it into Page Header b several times, or copy and paste the original item several times in Page Header b.

7. Position your mouse over the gray Page Header b section name. Right-click.

8. Choose Format Section from the pop-up menu in Crystal Reports 8.5, or Section Expert from the pop-up menu in Crystal Reports 9. This will display the Section Expert.

9. Choose the Underlay Following Sections check box for Page Header b in the Section Expert. Click OK to close the Section Expert.

10. If you wish to underlay items in the existing Page Header a section (field titles, the report title, and so forth), swap Page Header b and Page Header a by holding your mouse button down on either gray page header section name. When the mouse cursor changes to the hand icon, drag and drop the page header on top of the other page header. The sections will swap.

 

Change Graphics According to a Condition

Crystal Reports features the capability to format report objects (database fields, formulas, text objects, and so forth) conditionally, depending on the contents of a field, formula, or other condition. However, you may wish to actually insert several different graphic or picture files on your report and display them only when a certain condition occurs.

 

1. Open or create the report that you wish to add multiple conditional graphics to.

2. Add as many graphics to the report as are required. For example, if you want to display “thumbs up” and “thumbs down” graphics, add both graphic files to the report.

3. Place the graphics side by side, so that you may select each graphic individually.

4. Select the first graphic by clicking on it. Right-click. From the pop-up menu, select Format Graphic. The Format Editor will appear.

5. Select the Common tab. Next to the Suppress check box, click the Conditional Formula button. The Format Formula Editor will appear.

6. Add a Boolean formula to conditionally suppress the graphic. For example, to suppress the graphic if Last Year’s Sales is less than $50,000, enter a formula similar to this:

{Customer.Last Year’s Sales} < 50000

7. Click the Save button to close the Format Formula Editor. Click OK to close the Format Editor.

8. Repeat steps 4–7 for the remaining graphics, using “mutually exclusive” condition formulas, so that only one graphic at a time will display. For example, to suppress another graphic if Last Year’s Sales is greater than or equal to $50,000, enter a formula similar to this:

{Customer.Last Year’s Sales} >= 50000

9. Select each graphic and place it on top of the others, so that all graphics are placed in the same position. Because of the “mutually exclusive” conditional formatting, only one will appear at a time when the report is displayed.

 

Use WingDings and Other Symbol Fonts

By default, Crystal Reports uses a particular font face and size for report objects. While you can change the default font choices in the File | Options dialog box, you can also choose font face and size for individual report objects. You are not limited to standard letter-oriented fonts—you may choose symbol fonts such as Wingdings and Webdings as easily as you can choose letter-oriented fonts.

 

1. Add a database field, text object, formula, or other textual element that you wish to display as a symbol to the report.

2. Ensure that the object returns a character value that will “map” to the proper symbol. For example, to display a smile or frown with theWingdings font, you might create a formula similar to this:

If {Customer.Last Year’s Sales} < 50000 Then

“L”

Else

“J”

3. Select the object you wish to format with a symbol font.

4. Either using the Formatting toolbar or the Format Editor, select the symbol font (such as Wingdings or Webdings) that you’d like to use.

Tip: To determine what the proper character value is for the desired symbol, make use of the Windows Character Map. You may choose the symbol font and character you’d like to use and copy the character to the clipboard. Then, when you paste the character into a Crystal Reports formula or text object, the proper symbol will appear when you format the object with the symbol font. The Character Map is available from the System Tools submenu of the Accessories menu from the Start button Programs list.

 

 

Eliminate Blank Address Lines

Crystal Reports is often used for form letters, envelopes, or other mailing applications. In many cases, there is a need to eliminate blank address or “suite number” lines in an address for certain addresses. This can be accomplished in two ways: by embedding multiple address lines in a text object, or by using multiple report sections.

The text object method, while simpler in approach, will not automatically adjust vertical placement of objects that follow on the report. For example, if the address contains four lines in one form letter and three lines in the next, the remainder of the form letter below the text object will not move up or down automatically depending on the vertical size of the text object. For situations that require automatic vertical adjustment of text that follows the address, you’ll need to use multiple report sections.

 

Text Object

To eliminate blank lines using a text object, follow these steps:

1. Add a text object to your report. You will combine several database fields inside this text object.

2. Display the Field Explorer. Drag desired fields into the text object, separating database field with necessary characters, such as commas and spaces. In particular, drag the first address line (that might contain the street number) into the text object. Press ENTER to add a carriage return. Then, drag the second address line that will not always contain data (this might contain the suite number) into the text object. Press ENTER again. Then, drag in City, State, and Zip Code.

3. End editing by clicking anywhere outside the text object.

4. Select the text object you just created. Right-click and choose Format Text from the pop-up menu. The Format Editor will appear.

5. On the Common tab, click the Suppress Embedded Field Blank Lines options. This will suppress any lines in the text object that contain no data.

 

Shade Every Other Report Line

Although most companies have replaced mainframe “green-bar” or “blue-bar” reports with laser-printed output, there’s still a benefit to shaded sections when heavy textual information is being viewed. Shading lines in alternate colors or shades makes it easier for the eye to follow the line across the page. Crystal Reports enables this technique to be easily used for reports that may be printed on paper or viewed online.

By using the Mod function (which performs modulus arithmetic—returning the remainder of a division operation instead of the quotient), combined with the RecordNumber function (which simply numbers each report record sequentially), you may produce creative banded reports.

 

1. Point to the gray Details section name in the Design tab, or the gray D section name in the Preview tab. Right-click.

2. Choose Format Section from the pop-up menu in Crystal Reports 8.5 or Section Expert from the pop-up menu in Crystal Reports 9. The Section Expert will appear.

3. Ensure that the Details section is selected in the Section Expert. Click the Color tab.

4. Click the Conditional Formatting button. The Format Formula Editor will appear.

5. Enter a formula similar to the following (you may change the formatting color to your desired color):

If RecordNumber Mod 2 = 0 Then crSilver Else crNoColor

6. You may alter the frequency of the banding if you desire. For example, to shade every two lines, you can modify the formula as follows:

If RecordNumber Mod 4 In 1 To 2 Then crSilver Else crNoColor

Tip: Use of the crNoColor color constant instead of crWhite will show the alternating report sections with a certain degree of transparency. This may be helpful for certain reporting situations where you wish background information (such as a watermark) to appear behind the sections.

Courtesy: The Seo Guru, A Software Development Company, Best OOPS Blog Site, Link Submission, Thanks to Shopping  Site for Link Exchanging


  • 10

OOPS Concepts and .NET Part 2 Inheritance, Abstraction, Polymorphism

Summary

The following article is the second of a three-part article series that presents definitions and samples for different Object-Oriented Programming (OOP) concepts and its implementation in .NET. The first part examined the concepts of classes, objects, and structures. This part examines the concepts of inheritance, abstraction, and polymorphism. The third and last part will examine the concepts of interface, multiple interface inheritance, collections, and overloading.

Introduction

In Part 1 of Object-Oriented Programming Concepts and .NET, I defined the concepts of class, object, and structure. In addition to defining the concepts, I explained real world samples and presented sample code in C# and VB.NET to create classes and structs. The first article also explains objects as independent building blocks.

In Part 2 of Object-Oriented Programming Concepts and .NET, I will explain the concepts of inheritance, abstraction, and polymorphism. I will also present a Unified Model Language (UML) class diagram to represent an object model that will help as a visual aid to explain some concepts. The purpose of this article is to explain a series of relationships between objects.

Inheritance

In the real world there are many objects that can be specialized. In OOP, a parent class can inherit its behavior and state to children classes. This concept was developed to manage generalization and specialization in OOP and is represented by a is-a relationship.

The following OO terms are commonly used names given to parent and child classes in OOP:

·       Superclass: Parent class.

·       Subclass: Child class.

·       Base class: Parent class.

·       Derived class: Child class

The most common real world sample to explain inheritance is the geometric shapes object model. Squares, circles, triangles, rectangles, pentagons, hexagons, and octagons are geometric shapes. The following figure shows a sample set of geometric figures:

Figure 1. Geometric shapes.

The concept of generalization in OOP means that an object encapsulates common state an behavior for a category of objects. The general object in this sample is the geometric shape. Most geometric shapes have area, perimeter, and color. The concept of specialization in OOP means that an object can inherit the common state and behavior of a generic object; however, each object needs to define its own special and particular state an behavior. In Figure 1, each shape has its own color. Each shape has also particular formulas to calculate its area and perimeter.

Inheritance makes code elegant and less repetitive. If we know that all shapes have color, should we program a color attribute for each shape? The answer is no! Would it be a better idea to create a shape class that has a color attribute and to make all the specialized shapes to inherit the color attribute? The answer is yes!

An object model for this sample could have a shape parent class and a derived class for each specific shape. The following UML class diagram shows the set of classes needed to model the geometric shapes sample. Observe the field, properties, and methods for each class:

 

Figure 2. The Shape class is the parent class. Square, Rectangle, and Circle are derived classes that inherit from Shape. The triangle-connector in the diagram represents an is-a relationship.

The .NET framework has many base classes. Everything is derived from System.Object. You can create almost anything you imagine using the built-in functionality provided in the .NET Framework Class Library.

To create a derived class in C#, the class declaration should be done as:

class child: parent 

To create a derived class in VB.NET, the class declaration should be done as:

Class child
Inherits
parent
End
Class

Multiple inheritance

Multiple inheritance is the possibility that a child class can have multiple parents. Human beings have always two parents, so a child will have characteristics from both parents.

In OOP, multiple inheritance might become difficult to handle because it allows ambiguity for the compiler. There are programming languages such as C++ that allow multiple inheritance; however, other programming languages such as Java and the .NET Framework languages do not allow multiple inheritance. Multiple inheritance can be emulated in .NET using Multiple Interface Inheritance, which I will explain in Part 3 of this series.

Sealed class

A sealed class is a class that does not allow inheritance. Some object model designs need to allow the creation of new instances but not inheritance, if this is the case, the class should be declared as sealed.

To create a sealed class in C#, the class declaration should be done as:

sealed class Shape

To create a sealed class in VB.NET, the class declaration should be done as:

NonInheritable Class Shape

Abstraction

Abstraction is “the process of identifying common patterns that have systematic variations; an abstraction represents the common pattern and provides a means for specifying which variation to use” (Richard Gabriel).

An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or more abstract methods that do not have implementation. Abstract classes allow specialization of inherited classes.

Figure 2 shows a Shape class, which is an abstract class. In the real world, you never calculate the area or perimeter of a generic shape, you must know what kind of geometric shape you have because each shape (eg. square, circle, rectangle, etc.) has its own area and perimeter formulas. The parent class shape forces all derived classes to define the behavior for CalculateArea() and CalculatePerimeter(). Another great example is a bank account. People own savings accounts, checking accounts, credit accounts, investment accounts, but not generic bank accounts. In this case, a bank account can be an abstract class and all the other specialized bank accounts inherit from bank account.

To create an abstract class in C#, the class declaration should be done as:

abstract class Shape

To create an abstract class in VB.NET, the class declaration should be done as:

MustInherit Class Shape

To following code shows a sample implementation of an abstract class:

/// C#
using System;
namespace
DotNetTreats.OOSE.OOPSamples
{
public
abstract class Shape
{
private
float _area;
private
System.Drawing.Color _color;
private
float _perimeter;
public
float Area
{
get
{
return
_area;
}
set
{
_area = value;
}
}
public
System.Drawing.Color Color
{
get
{
return
_color;
}
set
{
_color = value;
}
}
public
float Perimeter
{
get
{
return
_perimeter;
}
set
{
_perimeter = value;
}
}
public
abstract void CalculateArea();
public
abstract void

CalculatePerimeter();
}
}
Listing 1. The Shape abstract class in C#.
 

 

Polymorphism

Polymorphism allows objects to be represented in multiple forms. Even though classes are derived or inherited from the same parent class, each derived class will have its own behavior. Polymorphism is a concept linked to inheritance and assures that derived classes have the same functions even though each derived class performs different operations.

Figure 2 shows a Rectangle, a Circle, and Square. All of them are shapes and as shapes their area and perimeter can be calculated; however, each shape calculates its area in a specialized way. Declaring a member as abstract allows polymorphism. The Shape class defines the CalculateArea() and CalculatePerimeter() methods as abstract, this allows each derived class to override the implementation of the parent’s methods.

To following sample code shows an implementation of a derived class (rectangle). The specific CalculateArea() and CalculatePerimeter() methods for the rectangle class illustrate polymorphism:

/// C#
using System;
namespace
DotNetTreats.OOSE.OOPSamples
{
class
Rectangle : Shape
{
private
float _height;
private
float _width;
public
rectangle(float height, float width)
{
_height = height;
_width = width;
}
public
float Height
{
get
{
return
_height;
}
set
{
_height = value;
}
}
public
float Width
{
get
{
return
_width;
}
set
{
_width = value;
}
}
public
override void CalculateArea()
{
this.Area = _height * _width;
}
public
override void

CalculatePerimeter()
{
this.Perimeter = (_height * 2) + (_width * 2);
}
}
}
Listing 2. Polymorphism represented in the Rectangle’s methods.
 

 

Virtual keyword

The virtual keyword allows polymorphism too. A virtual property or method has an implementation in the base class, and can be overriden in the derived classes.

To create a virtual member in C#, use the virtual keyword:

public virtual void Draw()

To create a virtual member in VB.NET, use the Overridable keyword:
Public Overridable Function Draw()
 

 

Override keyword

Overriding is the action of modifying or replacing the implementation of the parent class with a new one. Parent classes with virtual or abstract members allow derived classes to override them.

To override a member in C#, use the override keyword:

public override void CalculateArea()

To override a member in VB.NET, use the Overrides keyword:

Public Overrides Function CalculateArea()

Conclusion

Inheritance allows developers to manage a generalization and specialization relationship between objects. OOP concepts such as abstraction and polymorphism help to define better object models where object hierarchies are designed with reusability in mind. In this article, I examined the concept of inheritance, abstraction, and polymorphism. The third and last part of this series will examine the concepts of interface, multiple interface inheritance, collections, and overloading.

Courtesy: The Seo Guru, A Software Development Company, Best OOPS Blog Site, Link Submission, Thanks to Shopping  Site for Link Exchanging


Bookmark and Share