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

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

Free SEO Tools You Can’t Live Without

Visit Zonix Software Solutions

Here are six important SEO Tools to get you started:

1. Backlink Anchor Text Analysis – This tool is especially useful, as we all know that anchor text (if you don’t, then take my word for it) plays a huge part in the weight given to a link to your site. By inputting your URL, you can check all of the backlinks pointing to your site and the anchor text used for each. Quality, relevant, keyword related anchor text is the best way to link to someone, so if you see people that are linking to you using the infamous “click here”, kindly shoot them an email and ask them to change it if they have time. It’s worth the trouble.

2. Free Keyword Suggestion Tool – Okay, so I covered this a little in my last post, but it’s definitley worth listing again. As you know, it’s an quick way to nail down some nice keywords, and get a general idea of the amount of search volume each one commands. Quick, easy, and fun.

3. Domain Stats Tool – Yeah, spying on your competitor is so much fun! This tool comes in handy if you just can’t seem to figure out why your enemies are ranking higher than you (other than the normal stuff). Input a URL, and it will tell you things like domain age, big directory listings, backlink count in the big 3 (Google, Yahoo, MSN). Nothing too detailed, but it may be useful information at one point or another.

4. Keyword Difficulty Check – This seo tool is just downright cool. In your quest for the ultimate keywords, wouldn’t it be nice to see how difficult it would be to rank for a particular keyword? Problem solved. This famous tool over at SEOChat will do just that. It will tell you how hard it’s going to be percentage wise to rank for whatever keyword you put in. For instance, the keyword “SEO” gets a score of 78.5%, compared to “Florida SEO Company” scores a 42.03%. I could actually do this for hours, so I better move on before I digress….

5. Google Vs. Yahoo Search Results – Talk about interesting. This tool lets you put in a keyword or keyphrase of your choice, and after it runs, it will present you with a graph showing where they rank on each site. Lines are drawn across the graph for matching domains. It’s very cool to see how each search engine ranks pages for certain keywords. For instance, I ran a query on the keyword “seo tips”, and I noticed that the 3rd result site in Google is ranked well over 40 in Yahoo. Not all of them are that far apart..some are actually really close. By the way, does anyone know the algorithms for each? I just need to borrow it real quick….

6. Term Extractor – This little handy tool will let you input a URL, and after analyzing, it will tell you what it thinks is a search engine targeted term. This is a VERY clever tool, which I recommend you run on your site periodically, that way if you’re trying to target “garden tools” and the term extractor tells you that it thinks “sea monkey poop” is more SE targeted, that you have some work to do, keyword density wise!


Bookmark and Share

Introduction to .NET Remoting – Part [1]

Click Here to visit our website

Welcome to the world of Distributed Application!

The article will give you introduction to the world of Distributed Application development and its respective technologies.

What is Remoting?

Remoting” is the process of programs interacting across certain boundaries. The boundaries are either different processes or different machines. In .NET Framework, Remoting can be called the foundation of distributed application.

Remoting implementation generally distinguishes between Remote Objects and Mobile Objects.

Remote Object” provides the facility to execute methods on remote servers. You can pass parameters as well as return values. The “Remote Object” will always “Stay” at server and only a reference to it will be passes around other machines / processes.

While “Mobile Objects” passes the boundary, they are serialized in to some general representation – XML – and then deserialized to the other boundary involved in the process. Both the processes – server and client – hold the copies of the same object. Method execution will always be carried out in local context boundary, and no message will travel back to the process from where the object is actually originated. We can say, there is no distinction between a server object and a client object.

Scenarios for .NET Remoting

I mean, why Remoting comes into picture?

At the beginning of Client/Server era, Remoting was mostly used to access Server Resources; as each database or file server has an implementation which allow code to be executed remotely.

Now-a-days, it’s quite feasible building a distributed application among various machines to improve performance, scalability and maintainability using Remoting.

  • Centralized Business Logic

One of key scenario for remoting implementation is the concentration of business logic on one or more central servers. This simplifies the maintainability and operability of a large-scale application. Because any changes in business logic do not entail you to roll out the application at all user’s end – you just have to update one single server only.

Thus, in this scenario; we need a technique which can be used to communicate in between two process / context boundaries that is the program or process running at user end and another one is running at business server.

  • Physical Separation of Layers

The security is the common concern in web-enabled business. So, general recommendation is against for directly connecting from web server to database server. Instead of that, we used to have one application server / business server as discussed above.

  • Accessing Other Platforms

You will commonly encounter a heterogeneous combination of different platforms, frameworks and programming languages. It is uncommon to find that a bunch of tools, programming languages have been used and implemented to develop an application for a mid-to-large scale enterprise.

Integrating these systems can be a daunting task. Remoting architecture is an absolute necessity in large scale enterprise application integration.

  • Third Party Access

Opening your system for third party access in a business-to-business environment is quite common now-a-days. Application like online Order-entry, which allows third party to place orders from one system to other, is one good example of an application utilizing remoting architecture. More application examples are – address verification system, online price comparison, distributed visitor guard house application etc.

Click Here to visit our website


Bookmark and Share

Introduction to .NET Remoting – Part [1]

Click Here to visit our website

Welcome to the world of Distributed Application!

The article will give you introduction to the world of Distributed Application development and its respective technologies.

What is Remoting?

Remoting” is the process of programs interacting across certain boundaries. The boundaries are either different processes or different machines. In .NET Framework, Remoting can be called the foundation of distributed application.

Remoting implementation generally distinguishes between Remote Objects and Mobile Objects.

Remote Object” provides the facility to execute methods on remote servers. You can pass parameters as well as return values. The “Remote Object” will always “Stay” at server and only a reference to it will be passes around other machines / processes.

While “Mobile Objects” passes the boundary, they are serialized in to some general representation – XML – and then deserialized to the other boundary involved in the process. Both the processes – server and client – hold the copies of the same object. Method execution will always be carried out in local context boundary, and no message will travel back to the process from where the object is actually originated. We can say, there is no distinction between a server object and a client object.

Scenarios for .NET Remoting

I mean, why Remoting comes into picture?

At the beginning of Client/Server era, Remoting was mostly used to access Server Resources; as each database or file server has an implementation which allow code to be executed remotely.

Now-a-days, it’s quite feasible building a distributed application among various machines to improve performance, scalability and maintainability using Remoting.

  • Centralized Business Logic

One of key scenario for remoting implementation is the concentration of business logic on one or more central servers. This simplifies the maintainability and operability of a large-scale application. Because any changes in business logic do not entail you to roll out the application at all user’s end – you just have to update one single server only.

Thus, in this scenario; we need a technique which can be used to communicate in between two process / context boundaries that is the program or process running at user end and another one is running at business server.

  • Physical Separation of Layers

The security is the common concern in web-enabled business. So, general recommendation is against for directly connecting from web server to database server. Instead of that, we used to have one application server / business server as discussed above.

  • Accessing Other Platforms

You will commonly encounter a heterogeneous combination of different platforms, frameworks and programming languages. It is uncommon to find that a bunch of tools, programming languages have been used and implemented to develop an application for a mid-to-large scale enterprise.

Integrating these systems can be a daunting task. Remoting architecture is an absolute necessity in large scale enterprise application integration.

  • Third Party Access

Opening your system for third party access in a business-to-business environment is quite common now-a-days. Application like online Order-entry, which allows third party to place orders from one system to other, is one good example of an application utilizing remoting architecture. More application examples are – address verification system, online price comparison, distributed visitor guard house application etc.

Click Here to visit our website


Bookmark and Share

Turning off friendly errors in MOSS

Click Here to visit Zonix’s Website

We found many times sharepoint only display some text like unknown/unspecified error occured. If you want to sharepoint display you to proper error follow below given article.

While in development, the friendly error page that SharePoint displays when our page has an error can make debugging master page issues very difficult.
We can make an easy change to the Web config file for the site to turn friendly error messages off, therefore providing us with more useful information if page breaks. Only do the following in a development environment, and we should never want to turn off friendly error messages in a production environment. Also be sure to make a back up of the file prior to editing.
1. On the Web server, navigate to the site directory:Local Drive:InetpubwwwrootwssVirtualDirectories[directory for site]
2. Open Web.config in Notepad.
3. Search for “CallStack”. Change the CallStack status to “true”.
4. Search for “CustomErrors”. Change the mode to “off”.
5. Save and close the file.
Now when the site encounters an error, you will receive a .NET screen outlining the issue instead of the friendly SharePoint error screen. This is particularly useful with dealing with missing Content Placeholders and editing Master Pages. To turn friendly error messages back on, just walk through these steps setting the CallStack to false and CustomErrors mode to On.


Bookmark and Share


Bookmark and Share

Web Application Performance

Click Here to visit Zonix’s Website

Web Application performance can be enhanced by considering the following points:

1. Database ResultSets
2. Paging
3. Connection Pooling
4. Server Control View State
5. Caching

Below are details of the points:

Database Resultsets
Review your database code to see if you have request paths that go to the database more than once. Each of those round-trips decreases the number of requests per second your application can serve. By returning multiple resultsets in a single database request, you can cut the total time spent communicating with the database. You’ll be making your system more scalable; too, as you’ll cut down on the work the database server is doing managing requests.

While you can return multiple resultsets using dynamic SQL, I prefer to use stored procedures. It’s arguable whether business logic should reside in a stored procedure, but I think that if logic in a stored procedure can constrain the data returned (reduce the size of the dataset, time spent on the network, and not having to filter the data in the logic tier), it’s a good thing.

Using a SqlCommand instance and its ExecuteReader method to populate strongly typed business classes, you can move the resultset pointer forward by calling NextResult. Returning only the data you need from the database will additionally decrease memory allocations on your server.

// read the first resultset
reader = command.ExecuteReader();

// read the data from that resultset
while (reader.Read()) {
suppliers.Add(PopulateSupplierFromIDataReader( reader ));
}

// read the next resultset
reader.NextResult();

// read the data from that second resultset
while (reader.Read()) {
products.Add(PopulateProductFromIDataReader( reader ));
}
Paging

Good approach to writing better paging code is to use stored procedures

CREATE PROCEDURE northwind_OrdersPaged
(
@PageIndex int,
@PageSize int
)
AS
BEGIN
DECLARE @PageLowerBound int
DECLARE @PageUpperBound int
DECLARE @RowsToReturn int

— First set the rowcount
SET @RowsToReturn = @PageSize * (@PageIndex + 1)
SET ROWCOUNT @RowsToReturn

— Set the page bounds
SET @PageLowerBound = @PageSize * @PageIndex
SET @PageUpperBound = @PageLowerBound + @PageSize + 1

— Create a temp table to store the select results
CREATE TABLE #PageIndex
(
IndexId int IDENTITY (1, 1) NOT NULL,
OrderID int
)

— Insert into the temp table
INSERT INTO #PageIndex (OrderID)
SELECT
OrderID
FROM
Orders
ORDER BY
OrderID DESC

— Return total count
SELECT COUNT(OrderID) FROM Orders

— Return paged results
SELECT
O.*
FROM
Orders O,
#PageIndex PageIndex
WHERE
O.OrderID = PageIndex.OrderID AND
PageIndex.IndexID > @PageLowerBound AND
PageIndex.IndexID < @PageUpperBound
ORDER BY
PageIndex.IndexID

END

Connection Pooling

Of course you need to watch out for leaking connections. Always close your connections when you’re finished with them. I repeat: no matter what anyone says about garbage collection within the Microsoft® .NET Framework, always call Close or Dispose explicitly on your connection when you are finished with it. Do not trust the common language runtime (CLR) to clean up and close your connection for you at a predetermined time. The CLR will eventually destroy the class and force the connection closed, but you have no guarantee when the garbage collection on the object will actually happen.

To use connection pooling optimally, there are a couple of rules to live by. First, open the connection, do the work, and then close the connection. It’s okay to open and close the connection multiple times on each request if you have to (optimally you apply Tip 1) rather than keeping the connection open and passing it around through different methods. Second, use the same connection string (and the same thread identity if you’re using integrated authentication). If you don’t use the same connection string, for example customizing the connection string based on the logged-in user, you won’t get the same optimization value provided by connection pooling. And if you use integrated authentication while impersonating a large set of users, your pooling will also be much less effective. The .NET CLR data performance counters can be very useful when attempting to track down any performance issues that are related to connection pooling.

Whenever your application is connecting to a resource, such as a database, running in another process, you should optimize by focusing on the time spent connecting to the resource, the time spent sending or retrieving data, and the number of round-trips. Optimizing any kind of process hop in your application is the first place to start to achieve better performance.

The application tier contains the logic that connects to your data layer and transforms data into meaningful class instances and business processes. For example, in Community Server, this is where you populate a Forums or Threads collection, and apply business rules such as permissions; most importantly it is where the Caching logic is performed.

Server Control View State

View state is a fancy name for ASP.NET storing some state data in a hidden input field inside the generated page. When the page is posted back to the server, the server can parse, validate, and apply this view state data back to the page’s tree of controls. View state is a very powerful capability since it allows state to be persisted with the client and it requires no cookies or server memory to save this state. Many ASP.NET server controls use view state to persist settings made during interactions with elements on the page, for example, saving the current page that is being displayed when paging through data.

There are a number of drawbacks to the use of view state, however. First of all, it increases the total payload of the page both when served and when requested. There is also an additional overhead incurred when serializing or deserializing view state data that is posted back to the server. Lastly, view state increases the memory allocations on the server.

Several server controls, the most well known of which is the DataGrid, tend to make excessive use of view state, even in cases where it is not needed. The default behavior of the ViewState property is enabled, but if you don’t need it, you can turn it off at the control or page level. Within a control, you simply set the EnableViewState property to false, or you can set it globally within the page using this setting:

If you are not doing postbacks in a page or are always regenerating the controls on a page on each request, you should disable view state at the page level.


Bookmark and Share


Bookmark and Share

Advice to young programmers

Click Here to visit Zonix’s Website

(This is the summary of speech Given by Alex Stepenov (Principal Scientist, Adobe Systems) at Adobe India on 30 Nov 2004. )

1. Study , Study and Study

– Never ever think that you have acquired all or most of the knowledge which exists in the world. Almost everybody in US at age of 14 and everybody in India at age of 24 starts thinking that he has acquired all the wisdom and knowledge that he needs. This should be strictly avoided.

– You should be habituated to studies…exactly in the same way as you are habituated to brushing teeth and taking bath every morning. The habit of study must become a ‘part of your blood’. And the study should be from both the areas: CS, since it is your profession, and something from non-CS…Something which doesnot relate to your work. This would expand your knowledge in other field too. A regular study, everyday, is extremely essential. It doesnot matter whether you study of 20 minutes of 2 hours, but consistency is a must.

– You should always study basics and fundamentals. There is no point in going for advanced topics. When I was at the age of 24, I wanted to do PhD in program verification, though I was not able to understand anything from that. The basic reason was that my fundamental concepts were not clear. Studying ‘Algebraic Geometry’ is useless if you donot understand basics in Algebra and Geometry. Also, you should always go back and re-read and re-iterate over the fundamental concepts.

What is the exact definition of ‘fundamental’? The stuff which is around for a while and which forms basic part of the concepts can be regarded as more fundamental. Of course, everybody understands what a fundamental means.

– Here are few books which I would strongly recommend that every CS professional should read and understand.

i. “Structure and Interpretation of Computer Programs” by Albenson and Sussman

I personally donot like the material present in this book and I do have some objections about it but this is the best book I have ever seen which explains all the concepts in programming in a clear and excellent way.

This book is available online at http://mitpress.mit.edu/sicp/

ii. Introduction to Computer Architecture: by Hennessy and Patterson.

How many of you have shipped the programs by writing them in assembly? A very good understanding of basics of how a computer operates is what every CS professional must have.

H&P Wrote two books on CA. I am talking about their first book, the introductory text for understanding basic aspects of how a computer works.

Even if you feel that you know whatever is written in that book, donot stop reading. It’s good to revise basics again and again.

iii. “Fundamentals of Programming” by Donald Knuth.

The core of CS is algorithms and Data structures. Every CS professional must have the 3 volumes of Knuth’s Book on programming. It really doesnot matter if you take 30 years of your life to understand what Knuth has written, what is more important is that you read atleast some part of that book everyday without fail.

iv. Introduction to Algorithms by Cormen, Leiserson and Rivest

This book should be read daily to keep your concepts fresh. This is the best book for fundamental concepts in algorithms.

2. Learn Professional Ethics

– As a CS Professional, you are morally obliged to do a good job. What this means is that you are supposed to do your job not for your manager but for yourself. This is already told in Bhagwatgeeta : Doing duties of your life.

– The direct implication of this is: never ever write a bad code. You don’t need to be fastest and run after shipping dates; rather you need to write quality code. Never write junk code. Rewrite it till it is good. Thoroughly test every piece of code that you write. Donot write codes which are “sort of allright”. You might not achieve perfection, but atleast your code should be of good quality.

– Let me quote my own example in this context. You might have heard about STL, The Standard Template Library that ships in with C++ compilers. I wrote it 10 years ago, in 1994. While implementing one of the routines in the STL, namely the “search routine”, I was a bit lazy and instead of writing a good linear order implementation of KMP which was

difficult to code, I wrote a best quadratic implementation. I knew that I could make the search faster by writing a linear-order implementation, but I was lazy and I did not do that. And, after 10 years of my writing STL, exactly the same implementation is still used inside STL and STL ships with an inefficient quadratic implementation of search routine even today!! You might ask me: why can’t you rewrite that? Well…I cannot, because that code is no more my property!! Further, nobody today will be interested in a standalone efficient STL …people would prefer one which automatically ships out with the compiler itself.

– Moral is, you should have aesthetic beauty built inside you. You should “feel” uneasy on writing bad code and should be eager to rewrite the code till it becomes upto the quality. And to the judge the quality, you need to develop sense regarding which algorithms to use under what circumstances.

3. Figure out your Goals

– Always aspire doing bigger things in life

– “Viewing promotion path as your career” is a completely wrong goal. If you are really interested in studying and learning new things, never ever aspire for being a manager. Managers cannot learn and study…they have no time. “Company ladder aspiration” is not what should be important for you.

– You might feel that you want to do certain things which you cannot do till you become a manager. When you become a manager, you will soon realize that now you just cannot do anything!

– You will have a great experience as programmers. But if you care for people and love people, you will never enjoy being a manager…most good managers are reluctant managers. If you see people as people, you cannot survive at management level.

– Always aspire for professional greatness. Our profession is very beautiful because we create abstract models and implement them in reality. There is a big fun in doing that. We have a profession which allows us to do creative things and even gives nice salary for that.

– The three biggest mistakes that people usually make are aiming for money, aiming for promotion and aiming for fame. The moment you get some of these, you aspire for some more…and then there is no end. I donot mean that you shouldnot earn money, but you should understand how much

money would satisfy your needs. Bill Clinton might be the richest person in the world; he is certainly not the happiest. Our lives are far better than his.

– Find your goal, and do best in the job that you have. Understand that what is in your pocket doesnot matter…what is in your brain finally matters. Money and fame donot matter. Knowledge matters.

4. Follow your culture

I have seen the tradition that whatever junk is created in US, it rapidly spreads up in the rest of the world, and India is not an exception for this. This cultural change creates a very strong impact on everybody’s life. Habits of watching spicy Bollywood or Hollywood movies and listening to pop songs and all such stupid stuff gets very easily cultivated in people of your age…but believe me, there is nothing great in that. This all just makes you run away from your culture. And there is no wisdom in running away from your culture. Indian culture, which has great Vedas and stories like Mahabharata and Bhagwatgeeta is really great and even Donald Knuth enjoys reading that. You should understand that fundamental things in Indian culture teach you a lot and you should never forget them.

Finally, I would like to conclude by saying that it’s your life…donot waste it on stupid things…develop your tests, and start the fight.

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


Bookmark and Share

Advice to young programmers

Click Here to visit Zonix’s Website

(This is the summary of speech Given by Alex Stepenov (Principal Scientist, Adobe Systems) at Adobe India on 30 Nov 2004. )

1. Study , Study and Study

– Never ever think that you have acquired all or most of the knowledge which exists in the world. Almost everybody in US at age of 14 and everybody in India at age of 24 starts thinking that he has acquired all the wisdom and knowledge that he needs. This should be strictly avoided.

– You should be habituated to studies…exactly in the same way as you are habituated to brushing teeth and taking bath every morning. The habit of study must become a ‘part of your blood’. And the study should be from both the areas: CS, since it is your profession, and something from non-CS…Something which doesnot relate to your work. This would expand your knowledge in other field too. A regular study, everyday, is extremely essential. It doesnot matter whether you study of 20 minutes of 2 hours, but consistency is a must.

– You should always study basics and fundamentals. There is no point in going for advanced topics. When I was at the age of 24, I wanted to do PhD in program verification, though I was not able to understand anything from that. The basic reason was that my fundamental concepts were not clear. Studying ‘Algebraic Geometry’ is useless if you donot understand basics in Algebra and Geometry. Also, you should always go back and re-read and re-iterate over the fundamental concepts.

What is the exact definition of ‘fundamental’? The stuff which is around for a while and which forms basic part of the concepts can be regarded as more fundamental. Of course, everybody understands what a fundamental means.

– Here are few books which I would strongly recommend that every CS professional should read and understand.

i. “Structure and Interpretation of Computer Programs” by Albenson and Sussman

I personally donot like the material present in this book and I do have some objections about it but this is the best book I have ever seen which explains all the concepts in programming in a clear and excellent way.

This book is available online at http://mitpress.mit.edu/sicp/

ii. Introduction to Computer Architecture: by Hennessy and Patterson.

How many of you have shipped the programs by writing them in assembly? A very good understanding of basics of how a computer operates is what every CS professional must have.

H&P Wrote two books on CA. I am talking about their first book, the introductory text for understanding basic aspects of how a computer works.

Even if you feel that you know whatever is written in that book, donot stop reading. It’s good to revise basics again and again.

iii. “Fundamentals of Programming” by Donald Knuth.

The core of CS is algorithms and Data structures. Every CS professional must have the 3 volumes of Knuth’s Book on programming. It really doesnot matter if you take 30 years of your life to understand what Knuth has written, what is more important is that you read atleast some part of that book everyday without fail.

iv. Introduction to Algorithms by Cormen, Leiserson and Rivest

This book should be read daily to keep your concepts fresh. This is the best book for fundamental concepts in algorithms.

2. Learn Professional Ethics

– As a CS Professional, you are morally obliged to do a good job. What this means is that you are supposed to do your job not for your manager but for yourself. This is already told in Bhagwatgeeta : Doing duties of your life.

– The direct implication of this is: never ever write a bad code. You don’t need to be fastest and run after shipping dates; rather you need to write quality code. Never write junk code. Rewrite it till it is good. Thoroughly test every piece of code that you write. Donot write codes which are “sort of allright”. You might not achieve perfection, but atleast your code should be of good quality.

– Let me quote my own example in this context. You might have heard about STL, The Standard Template Library that ships in with C++ compilers. I wrote it 10 years ago, in 1994. While implementing one of the routines in the STL, namely the “search routine”, I was a bit lazy and instead of writing a good linear order implementation of KMP which was

difficult to code, I wrote a best quadratic implementation. I knew that I could make the search faster by writing a linear-order implementation, but I was lazy and I did not do that. And, after 10 years of my writing STL, exactly the same implementation is still used inside STL and STL ships with an inefficient quadratic implementation of search routine even today!! You might ask me: why can’t you rewrite that? Well…I cannot, because that code is no more my property!! Further, nobody today will be interested in a standalone efficient STL …people would prefer one which automatically ships out with the compiler itself.

– Moral is, you should have aesthetic beauty built inside you. You should “feel” uneasy on writing bad code and should be eager to rewrite the code till it becomes upto the quality. And to the judge the quality, you need to develop sense regarding which algorithms to use under what circumstances.

3. Figure out your Goals

– Always aspire doing bigger things in life

– “Viewing promotion path as your career” is a completely wrong goal. If you are really interested in studying and learning new things, never ever aspire for being a manager. Managers cannot learn and study…they have no time. “Company ladder aspiration” is not what should be important for you.

– You might feel that you want to do certain things which you cannot do till you become a manager. When you become a manager, you will soon realize that now you just cannot do anything!

– You will have a great experience as programmers. But if you care for people and love people, you will never enjoy being a manager…most good managers are reluctant managers. If you see people as people, you cannot survive at management level.

– Always aspire for professional greatness. Our profession is very beautiful because we create abstract models and implement them in reality. There is a big fun in doing that. We have a profession which allows us to do creative things and even gives nice salary for that.

– The three biggest mistakes that people usually make are aiming for money, aiming for promotion and aiming for fame. The moment you get some of these, you aspire for some more…and then there is no end. I donot mean that you shouldnot earn money, but you should understand how much

money would satisfy your needs. Bill Clinton might be the richest person in the world; he is certainly not the happiest. Our lives are far better than his.

– Find your goal, and do best in the job that you have. Understand that what is in your pocket doesnot matter…what is in your brain finally matters. Money and fame donot matter. Knowledge matters.

4. Follow your culture

I have seen the tradition that whatever junk is created in US, it rapidly spreads up in the rest of the world, and India is not an exception for this. This cultural change creates a very strong impact on everybody’s life. Habits of watching spicy Bollywood or Hollywood movies and listening to pop songs and all such stupid stuff gets very easily cultivated in people of your age…but believe me, there is nothing great in that. This all just makes you run away from your culture. And there is no wisdom in running away from your culture. Indian culture, which has great Vedas and stories like Mahabharata and Bhagwatgeeta is really great and even Donald Knuth enjoys reading that. You should understand that fundamental things in Indian culture teach you a lot and you should never forget them.

Finally, I would like to conclude by saying that it’s your life…donot waste it on stupid things…develop your tests, and start the fight.

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


Bookmark and Share

Passing lists to SQL server stored procedures

Click Here to visit Zonix’s Website

Article is about:

The ability to pass “a list of values” from .Net as a parameter to a T-SQL based stored procedure.

Scenarios:

There are lots of scenarios where we need to pass a list of values to save in database. Here’s a couple of obvious ones:

INSERT a list of values into the database in one “chunky” call (e.g. some IDs from a CheckBoxList)
SELECT rows where IDs are IN ()
Some general Approaches:

Taking the INSERT statements as an example, there are various general approaches that we adopt to achieve the desired result:

Use dynamic / Inline SQL! But ideally say, dynamic / Inline SQL is rarely the ideal solution for obvious reasons.
Make a stored proc call for each ID to insert. This is the most common approach we see in various projects, mainly because it is the easiest to implement. The drawback of course is if we were to insert 60 values, it would result in 60 “chatty” calls to the database.
Pass comma separated values via a VARCHAR (or similar) parameter. This works fine but has messy “string splitting” in the stored procedure to extract the IDs and then build the SQL statement in the procedure itself. Prone to SQL injection and not the best performance.
Pass the list as an XML parameter. This is nicer and is the point of this article.
Coming to the main Point, Using XML:

Using XML for “list passing” has a number of benefits, in particular the ability to pass lists of more “complex types” rather than just single values.

Lets take an example. Suppose we are having 2 CheckedListBox; one is list of Users and another is the list of tasks / roles that can be assigned to Users. We want to store the values in Table which is having Fields UserID and TaskID. The Stored Procedure will accept Parameter with XML Datatype as,

CREATE PROCEDURE [dbo].[usp_InsertUserTask]
@UserTaskXML XML
AS
BEGIN
INSERT INTO UserTasks (UserID,TaskID)
SELECT
UserTaskTab.UserTaskCol.value(‘UserID[1]’,’int’) AS UserID,
UserTaskTab.UserTaskCol.value(‘TaskID[1]’,’int’) AS TaskID
FROM @UserTaskXML.nodes(‘//UserTaskList/UserTaskData’) AS UserTaskTab(UserTaskCol)
END

To call this in Stored Procedure, you would have something like this:

EXEC [dbo].[usp_InsertUserTask]
@UserTaskXML = ‘

1
100

2
200

In your application, your C# calling code could be:

SqlConnection sqlCN = new SqlConnection();
sqlCN.ConnectionString = ConfigurationManager.AppSettings[“DBConn”].ToString();
string strQuery = “usp_InsertUserTask”;
SqlParameter[] sqlParams = new SqlParameter[1];
sqlParams[0] = new SqlParameter(“@UserTaskXML”, GetStudyDataXMLString());
SqlHelper.ExecuteNonQuery(sqlCN, CommandType.StoredProcedure, strQuery, sqlParams);
if (sqlCN.State == ConnectionState.Open)
sqlCN.Close();
sqlCN.Dispose();

which calls the method below to translate the UserID and TaskID from CheckBoxLists into an XML String:

private string GetUserTaskListXML()
{
try
{
StringBuilder XMLString = new StringBuilder();
XMLString.AppendFormat(“”);
for (int iUserCount = 0; iUserCount < UserCheckBoxList.Items.Count; iUserCount++)
{
if(UserCheckBoxList.Items[iUserCount].Selected)
{
for (int iTaskCount = 0; iTaskCount < TaskCheckBoxList.Items.Count; iTaskCount++)
{
if(TaskCheckBoxList.Items[iTaskCount].Selected)
{
XMLString.AppendFormat(“”);
XMLString.AppendFormat(“{0}”, UserCheckBoxList.Items[iUserCount].value);
XMLString.AppendFormat(“{0}”, UserCheckBoxList.Items[iUserCount].value);
XMLString.AppendFormat(“”);
}
}
}
}
XMLString.AppendFormat(“”);
}
catch (Exception Ex)
{
throw Ex;
}
return XMLString.ToString();
}

Here, StringBuilder is used for the xml concatenation as in this case I think it fits the bill but purists might prefer an XmlTextWriter approach. In summary, it performs very well and is adaptable for various lists of objects and more complex structures.

Referenced Link:

Passing lists to SQL server stored procedures


Bookmark and Share