Category Archives: Technology

  • 1

Google Chrome OS

Google is launching Chrome OS. Google is saying that the modern computerChrome-logo user spends so much time working with Web-based resources that the main control system for the computer should be the browser, not the operating system. Furthermore, Google declared that the Chrome OS experience will bear little resemblance to existing way that users interact with their computer’s main control program. It is expected that in Chrome OS world there would be no Win/Web every thing looks to be managed using the web browser.

Security of computer system could be an issue as everything would be maintained using web browsers.

Another important noticeable thing is Google can give Google Docs to users to store their important documents in their computer harddrive than storing on Google Docs online. Google allows to store meta information with the document which actually makes the searching very fast with in the system.

Microsoft uses indexing service to automatically index all the documents & folders created within the computer system. would that be gone in Google Chrome?

Google may also take a cue from its own e-mail application, GMail, which blends the traditional idea of having folders for e-mail with the concept of “labels.” In GMail, you can drag messages into folders to file them, or you can drag folders (or labels) over messages to categorize them. It’s the same thing, but the hierarchy people are used to in operating systems, where a file is in one folder at a time, and the folder may be nested in another folder, is simply not there. Folders and labels are interchangable and far more fluid.

It is also expected that the Chrome OS will be using the interface of Chrome browser–like a tabbed view for switching between “apps,” and the mind-reading command line (address bar in the browser). It may also evidence Google’s traditional obsession with clean (if not necessarily attractive) design and speed. The Chrome OS should be fast.


  • 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


  • 2

How Big is google’s database

Visist : http://www.zonixsoft.com (Our Official Website)

Google search crawler uses 850 TB of information, so that’s the amount of raw data from the web.

Google Analytics uses 220 TB stored in two tables: 200 TB for the raw data and 20 TB for the summaries.

Google Earth uses 70.5 TB: 70 TB for the raw imagery and 500 GB for the index data.

The second table “is relatively small (500 GB), but it must serve tens of thousands of queries per second per datacenter with low latency”.

Personalized Search doesn’t need too much data: only 4 TB.
Personalized Search stores each user’s data in Big table.
Each user has a unique user id and is assigned a row named by that user id.
All user actions are stored in a table.

Google Base uses 2 TB and Orkut only 9 TB of data.
If we take into account that all this information is compressed. For example, the crawled data has compression rate of 11%, so 800 TB become 88 TB, Google uses for all the services mentioned before 220 TB.

It’s also interesting to note that the size of the raw imagery from Google Earth is almost equal to the size of the compressed web pages crawled by Google.


Bookmark and Share


  • 0

New in C-Sharp 3.0

Visit: http://www.zonixsoft.com

New in C-Sharp 3.0

New in C# 3.0
This article discusses the following major new enhancements expected in C# 3.0:
• Implicitly typed local variables
• Anonymous types
• Extension methods
• Object and collection initializers
• Lambda expressions
• Query expressions
• Expression Trees

Implicitly typed local variables:
C# 3.0 introduces a new keyword called “var”. Var allows you to declare a new variable, whose type is implicitly inferred from the expression used to initialize the variable.
Syntax: var i=1;
The preceding line initializes the variable i to value 1 and gives it the type of integer. It is not an object or variant.
Anonymous types:
C# 3.0 gives you the flexibility to create an instance of a class without having to write code for the class beforehand. So, you now can write code as shown below:
new {StudentID=1, StudentName=”XYZ”, Marks=90}
The preceding line of code, with the help of the “new” keyword, gives you a new type that has three properties: StudentID, StudentName, and Marks. Behind the scenes, the C# compiler would create a class that looks as follows:
class __Anonymous1
{
private int _StudentID = 1;
private string _StudentName = “XYZ”;
private int _Marks = 64;
public int StudentID {get { return _StudentID; } set { _StudentID = value; }}
public string StudentName {get { return _StudentName; } set { _StudentName = value; }}
public int Marks {get { return _Marks; } set { _Marks = value; }}
}

Extension methods:

Extension methods enable you to extend various types with additional static
methods. Extension methods can be declared only in static classes and are identified by
the keyword “this” as a modifier on the first parameter of the method.

The following is an example of a valid extension method:
public static int ToInt32(this string s)
{
return Convert.ToInt32(s) ;
}
Object and collection initializers:
C# 3.0 is expected to allow you to include an initializer that specifies the initial values of the members of a newly created object or collection. This enables you to combine declaration and initialization in one step.
For instance, if you defined a CoOrdinate class as follows:
public class CoOrdinate
{
public int x;
public int y;
}

You then could declare and initialize a CoOrdinate object using an object initializer, like this:

var myCoOrd = new CoOrdinate{ x = 0, y= 0} ;
You should easily be able to give values to collections in a rather concise and compact manner in C# 3.0.
In C# 2.0 Code we write :

List<string> animals = new List<string>();

animals.Add(“monkey”);
animals.Add(“donkey”);
animals.Add(“cow”);
animals.Add(“dog”);
animals.Add(“cat”);

It can be written in  C# 3.0 shortened to simply.
List<string> animals = new List<string> {“monkey”, “donkey”, “cow”, “dog”, “cat” } ;
Lambda expressions:
C#(1.x) allowed you to write code blocks in methods, which you could invoke easily using delegates.Delegates are definitely useful, and they are used throughout the framework, but in many instances you had to declare a method or a class just to use one. Thus, to give you an easier and more concise way of writing code, C# 2.0 allowed you to replace standard calls to delegates with anonymous methods.
In C# 2.0, using anonymous methods, you could rewrite the code as follows:
class Program
{
delegate void DemoDelegate();
static void Main(string[] args)
{
DemoDelegate myDelegate = delegate()
{
Console.Writeline(“Hiya!!”);
};
myDelegate();
}
}
The above code can now be replaced with the following code in C# 3.0:
class Program
{
delegate void DemoDelegate();
static void Main(string[] args)
{
DemoDelegate myDelegate = () => Console.WriteLine(“Hiya!!”) ;
myDelegate();
}
}

Reference Site: http://www.developer.com/net/csharp/article.php/10918_3561756_1


Bookmark and Share



  • 3

Customizing the Map using Google Maps API

Get ready to code! In this section, we’ll be making changes and additions to the map HTML file to customize the map based on your preferences.

 

1.    Open your myapp.html file.

2.    Add the code to center the map at particular the latitude/longitude .The line that centers the map in the current code is: map.setCenter(new GLatLng(37.4419, -122.1419), 13);

 

This line calls setCenter on the map object, and passes in a GLatLng for the center, and a number for the zoom level. Change the two parameters of GLatLng to the latitude/longitude you want to locate, and if you’d like, change the zoom parameter. Zoom level 0 is the lowest zoom level (showing all of the world), and increasing numbers zoom in closer.

 

3.    Add code to change the default map type. Currently the map is showing the Map map type, which shows street names, country borders, etc. The other two options are the Satellite and Hybrid map types. You can see the difference at http://maps.google.com by pressing each of the three buttons in the top right corner. The line of code to change the map type is:

    map.setMapType(G_NORMAL_MAP);

    map.setMapType(G_SATELLITE_MAP);

    map.setMapType(G_HYBRID_MAP);

 

    The default that it’s already using is G_NORMAL_MAP, so if you      want to change it, use either G_SATELLITE_MAP or G_HYBRID_MAP. Add this line of code after the map.setCenter code.

 

4.    Add the code to create a marker at the center of the map, like the markers you see when you find businesses on Google Maps. The line of code to create a marker is:

var marker = new GMarker(new GlatLng(34.019968,-118.289988));

The line of code to add a marker to the map is:

map.addOverlay(marker);

 

5.    Add the code to open an info window (bubble) over the marker and add some information about the location.

The code to open an info window over a marker is:

 

 

var html=”<img src=’simplemap_logo.jpg'” +

“width=’128′ height=’41’/> <br/>” +

“USC GamePipe Lab<br/>” +

“3650 McClintock Ave, Los Angeles CA”;

marker.openInfoWindowHtml(html);

As you can see from my example, you can pass any HTML into the info window. You do need to be careful about quotation marks in the HTML, however. Here, I’ve used double quotation marks around the HTML, and single quotation marks around attributes in the HTML tags.

If you include an IMG tag in the HTML, you should define the width and height attributes of the image so that the info window is sized correctly to fit the image inside.

 

 

6.    Add the code to add controls to the map. On the maps.google.com map, you’ll notice multiple controls overlaid on the map that aid you in navigation and changing the map view. With the API, you can add any of these controls to your map, and you may want to do so to let people visiting your map view the area around your map. Here are the various controls options:

map.addControl(new GSmallMapControl());

map.addControl(new GLargeMapControl());

map.addControl(new GSmallZoomControl());

map.addControl(new GScaleControl());

map.addControl(new GMapTypeControl());

map.addControl(new GoverviewMapControl());

 

You should only add one of the zoom/pan controls: either GSmallMapControl, GLargeMapControl, or GSmallZoomControl, since they show up in the same location and accomplish similar things. You can add any or all of the other controls, as you so desire. These lines of code should be added anywhere under the map.setCenter line.

   7.Change the HTML to resize the map. The default map has dimension of  500×300 pixels. You may want your map to be larger or smaller than that. The map size is dependent on the size of the div that the map is initialized within, so you’ll need to change the dimensions of that div to your desired dimensions. Find the following line of code and replace the default width and height to whatever you want:

 

<div id=”map” style=”width: 500px; height: 300px”></div>

 

 

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


Bookmark and Share


  • 0

SMS service to send Message to a URL

Here is the sample code for same , I used it for implementing SMS service in project that sends message to particular URL which in turn sends SMS to particualr phone number,

using System.Net;

using System.Xml;

XmlDocument xDoc = new XmlDocument();

//xDoc = ; //some xml data

Byte[] outputbyte;

string sXML = “”;

string strResult = “”;

String URL = “http://someurl.com/”;//url that

Byte[] inputbyte = System.Text.Encoding.ASCII.GetBytes(xDoc.OuterXml);

WebClient wc = new WebClient();

wc.Headers.Add(“Content-Type”, “text/xml”);

outputbyte = wc.UploadData(URL, inputbyte);//will upload a byte of data to specific url service

sXML = System.Text.Encoding.ASCII.GetString(outputbyte);

System.Xml.XmlDocument xmlData = new System.Xml.XmlDocument();

xmlData.LoadXml(sXML); // will load whole xml and now you can traverse to any xml node.


Bookmark and Share


  • 6

GZipStream Class to Compress and Decompress Stream Data

Provides methods and properties used to compress and decompress streams.

Namespace: System.IO.Compression
Assembly: System (in system.dll)

 

This class represents the gzip data format, which uses an industry standard algorithm for lossless file compression and decompression. The format includes a cyclic redundancy check value for detecting data corruption. The gzip data format uses the same algorithm as the DeflateStream class, but can be extended to use other compression formats. The format can be readily implemented in a manner not covered by patents. The format for gzip is available from the RFC 1952, “GZIP .” This class cannot be used to compress files larger than 4 GB.

 

Notes to Inheritors When you inherit from GZipStream, you must override the following members: CanSeek, CanWrite, and CanRead.

 

 Example

The following code example shows how to use the GZipStream class to compress and decompress a file.

using System;
using System.IO;
using System.IO.Compression;

public class GZipTest
{
    public static int ReadAllBytesFromStream(Stream stream, byte[] buffer)
    {
    // Use this method is used to read all bytes from a stream.
    int offset = 0;
    int totalCount = 0;
        while (true)
        {
        int bytesRead = stream.Read(buffer, offset, 100);
            if ( bytesRead == 0)
            {
            break;
            }
    offset += bytesRead;
    totalCount += bytesRead;
        }
    return totalCount;
    }

    public static bool CompareData(byte[] buf1, int len1, byte[] buf2, int len2)
    {
        // Use this method to compare data from two different buffers.
        if (len1 != len2)
        {
        Console.WriteLine(“Number of bytes in two buffer are different {0}:{1}”, len1, len2);
        return false;
        }

        for ( int i= 0; i< len1; i++)
        {
            if ( buf1[i] != buf2[i])
            {
            Console.WriteLine(“byte {0} is different {1}|{2}”, i, buf1[i], buf2[i]);
            return false;
            }
        }
    Console.WriteLine(“All bytes compare.”);
    return true;
    }

    public static void GZipCompressDecompress(string filename)
    {
    Console.WriteLine(“Test compression and decompression on file {0}”, filename);
    FileStream infile;
        try
        {
        // Open the file as a FileStream object.
        infile = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
        byte[] buffer = new byte[infile.Length];
        // Read the file to ensure it is readable.
        int count = infile.Read(buffer, 0, buffer.Length);
            if ( count != buffer.Length)
            {
            infile.Close();
            Console.WriteLine(“Test Failed: Unable to read data from file”);
            return;
            }
        infile.Close();
        MemoryStream ms = new MemoryStream();
        // Use the newly created memory stream for the compressed data.
        GZipStream compressedzipStream = new GZipStream(ms , CompressionMode.Compress, true);
        Console.WriteLine(“Compression”);
        compressedzipStream.Write(buffer, 0, buffer.Length);
        // Close the stream.
        compressedzipStream.Close();
        Console.WriteLine(“Original size: {0}, Compressed size: {1}”, buffer.Length, ms.Length);

        // Reset the memory stream position to begin decompression.
        ms.Position = 0;
        GZipStream zipStream = new GZipStream(ms, CompressionMode.Decompress);
        Console.WriteLine(“Decompression”);
        byte[] decompressedBuffer = new byte[buffer.Length + 100];
        // Use the ReadAllBytesFromStream to read the stream.
        int totalCount = GZipTest.ReadAllBytesFromStream(zipStream, decompressedBuffer);
        Console.WriteLine(“Decompressed {0} bytes”, totalCount);

        if( !GZipTest.CompareData(buffer, buffer.Length, decompressedBuffer, totalCount) )
        {
        Console.WriteLine(“Error. The two buffers did not compare.”);
        }
    zipStream.Close();
        } // end try
        catch (InvalidDataException)
        {
            Console.WriteLine(“Error: The file being read contains invalid data.”);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine(“Error:The file specified was not found.”);
        }
        catch (ArgumentException)
        {
            Console.WriteLine(“Error: path is a zero-length string, contains only white space, or contains one or more invalid characters”);
        }
        catch (PathTooLongException)
        {
            Console.WriteLine(“Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters.”);
        }
        catch (DirectoryNotFoundException)
        {
            Console.WriteLine(“Error: The specified path is invalid, such as being on an unmapped drive.”);
        }
        catch (IOException)
        {
            Console.WriteLine(“Error: An I/O error occurred while opening the file.”);
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine(“Error: path specified a file that is read-only, the path is a directory, or caller does not have the required permissions.”);
        }
        catch (IndexOutOfRangeException)
        {
            Console.WriteLine(“Error: You must provide parameters for MyGZIP.”);
        }
    }
    public static void Main(string[] args)
    {
        string usageText = “Usage: MYGZIP <inputfilename>”;
        //If no file name is specified, write usage text.
        if (args.Length == 0)
        {
            Console.WriteLine(usageText);
        }
        else
        {
            if (File.Exists(args[0]))
                GZipCompressDecompress(args[0]);
        }
    }
}
   

Demo Application:

 

Default.aspx :

 

<%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”Default.aspx.vb” Inherits=”_Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” >

<head runat=”server”>

<title>Compression Demo</title>

</head>

<body style=”margin-top:10; margin-left:0″>

<form id=”form1″ runat=”server”>

<div>

<asp:Panel ID=”Panel1″ runat=”server” Height=”500px” Width=”100%” HorizontalAlign=”Center”>

<asp:Label ID=”Label1″ runat=”server” Font-Bold=”True” Font-Size=”Large” Font-Underline=”True”

Text=”File Upload & Compression Tutorial”></asp:Label><br />

<br />

<table style=”width: 100%”>

<tr>

<td align=”right”>

<asp:Label ID=”Label2″ runat=”server” Text=”File to upload and compress: “ Width=”100%”></asp:Label></td>

<td style=”width: 100px” align=”left”>

<input id=”fileUpload” type=”file” runat=”server” />

</td>

</tr>

<tr>

<td>

</td>

<td style=”width: 50%” align=”left”>

<asp:Button ID=”btnUpload” runat=”server” Text=”Upload” />

<asp:Button ID=”btnCompress” runat=”server” Text=”Upload & Compress” /></td>

</tr>

<tr>

<td>

</td>

<td align=”left”>

<asp:Label ID=”lblResult” runat=”server” Font-Bold=”True” ForeColor=”RoyalBlue” Width=”100%”></asp:Label></td>

</tr>

</table>

</asp:Panel>

</div>

</form>

</body>

</html>

Default.aspx.cs :

Imports System.IO

Imports System.IO.Compression

 

Partial Class _Default

Inherits System.Web.UI.Page

 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

End Sub

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click

If fileUpload.PostedFile Is Nothing Then

Me.lblResult.Text = “No File Selected to Upload.”

Exit Sub

End If

‘Retrieve file information and upload to server.

Dim strName As String

strName = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName)

Try

fileUpload.PostedFile.SaveAs(Server.MapPath(strName))

Me.lblResult.Text = “””” + strName + “”” was uploaded successfully.”

Catch ex As Exception

Me.lblResult.Text = “An Error Occured While Uploading File.”

End Try

End Sub

Protected Sub btnUploadCompressed_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCompress.Click

If fileUpload.PostedFile Is Nothing Then

Me.lblResult.Text = “No File Selected to Upload.”

Exit Sub

End If

Try

‘A String object reads the file name (locally)

Dim strName As String = System.IO.Path.GetFileName(fileUpload.PostedFile.FileName)

‘Create a stream object to read the file.

Dim myStream As Stream = fileUpload.PostedFile.InputStream

‘Allocate space in buffer for use according to length of file.

Dim myBuffer(myStream.Length) As Byte

‘Read the file using the Stream object and fill the buffer.

myStream.Read(myBuffer, 0, myBuffer.Length)

myStream.Close()

‘Change the extension of the file creating a FileStream object.

Dim myCompressedFile As FileStream = File.Create(Server.MapPath(Path.ChangeExtension(strName, “rar”)))

‘GZip object that compress the file

Dim myStreamZip As New System.IO.Compression.GZipStream(myCompressedFile, CompressionMode.Compress)

‘Write Back

myStreamZip.Write(myBuffer, 0, myBuffer.Length)

myStreamZip.Close()

Me.lblResult.Text = “””” + strName + “”” was uploaded successfully and compressed.”

Catch ex As Exception

Me.lblResult.Text = “An Error Occured While Uploading File.”

End Try

End Sub

End Class


Bookmark and Share


  • 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