Wednesday, February 24, 2010

BASIC Concepts for OOPS

This Article describes the usefullness of Abstract Classes, Sealed Classes, and Interfaces. It also explains when we should use each of them with help from code samples.
Average Rating:
Views (Total / Last 10 Days): 70134/ 972
Article Contents:

* Introduction
* What is an Abstract class?
* What is an Interface?
* Abstract Class vs. Interface
* Sealed Class
* References
* Conclusion

Click Here
[ Back To Top ]

Using sealed classes is a new concept added in C#. It is difficult to say when we should use an abstract class and when we should use an interface. In general defining an abstract class without any implementation means with abstract members has the same effect as defining an interface; however there are a lot more differences than similarities between an abstract class and an interface. In this article I am not only trying to describe the concept of abstract classes, interfaces, and sealed classes, but also describe in what situation we should use which and how. The sample code snippets have been written in C#.
What is an Abstract class?
[ Back To Top ]

An abstract class only allows other classes to inherit from it and cannot be instantiated. When we create an abstract class, it should have one or more completed methods but at least one or more uncompleted methods and these must be preceded by the key word abstract. If all the methods of an abstract class are uncompleted then it is the same as an interface, but there is a restriction that it cannot make a class inherit from it, which means it can not work as a base class.
What is an Interface?
[ Back To Top ]

An interface is defined by the key word interface. An interface has no implementation; it only has the definition of the methods without the body. When we create an interface, we are basically creating a set of methods without any implementation. A class implementing an interface must provide the implementation of the interface members. All the methods and properties defined in an interface are by default public and abstract.

Define an Abstract Class

In the following code listing an abstract class named Product has been defined.

Listing 1

public abstract class Product
protected string id;
protected double price;
public abstract string ID

public abstract double Price

public abstract double CalculatePrice();

Define an Interface

In the following code listing an interface named Iproduct has been defined.

Listing 2

public interface Iproduct
string ID


double Price

double CalculatePrice();


In the following code listing the Iproduct interface has been implemented by the class implementInterface.

Listing 3

public class implementInterface: Iproduct
protected string id;
protected double price;
public string ID
return id;
id = value;
public double price
return price;
price = value;

public double CalculatePrice()
return Price * 1.25;

In the following code listing the abstract Class named Product has been implemented by the class implementAbstract.

Listing 4

public class implementAbstract: Product
public override string ID
return id;
id = value;

public override double Price
return price;
price = value;

public override double CalculatePrice
return Price * 1.25;


How to Test

In the following code listing abstract class implementation is being tested.

Listing 5

ImplementAbstract testAbstract=new implementAbstract();
double amt=testAbstract.CalculatePrice();
Response.Write(“Total Net Price of Product : “ +” “+testAbstract.ID +” “+ “is”+” “+amt);

In the following code listing the implementation of our interface is being tested.

Listing 6

ImplementInterface testInterface=new implementInterface();
double Iamt= testInterface.CalculatePrice();
Response.Write(“Total Net Price of Product : “ +” “+testInterface.ID +” “+ “is”+” “+Iamt);

It should be noted that static members are not inherited under any circumstances. Hence we can not declare a static method in an interface because interfaces have no implementation. We can, however, declare a method as static in an abstract class, because abstract classes can have implementations of static methods. This has been described in the following code listing:

Listing 7

In an abstract class:

public static void test()

But we can not write the following in an interface.

Listing 8

static void test();

Abstract Class vs. Interface
[ Back To Top ]

· An abstract class may contain complete or incomplete methods. Interfaces can contain only the signature of a method but no body. Thus an abstract class can implement methods but an interface can not implement methods.

· An abstract class can contain fields, constructors, or destructors and implement properties. An interface can not contain fields, constructors, or destructors and it has only the property's signature but no implementation.

· An abstract class cannot support multiple inheritance, but an interface can support multiple inheritance. Thus a class may inherit several interfaces but only one abstract class.

· A class implementing an interface has to implement all the methods of the interface, but the same is not required in the case of an abstract Class.

· Various access modifiers such as abstract, protected, internal, public, virtual, etc. are useful in abstract Classes but not in interfaces.

· Abstract classes are faster than interfaces.
Sealed Class
[ Back To Top ]

Classes can be declared as sealed. This is accomplished by putting the sealed keyword before the keyword class in the class definition. For example:

Listing 9

public sealed class classSealed
// Class members here.
public string ID;
public double Price;

In the following code listing the implementation of a sealed class has been tested.

Listing 10

classSealed sc=new classSealed();
double Samt=sc. CalculatePrice();
Response.Write(“Total Net Price of Product : “ +” “+sc.ID +” “+ “is”+” “+Samt);

A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster. Sealing a class means one can not derive from it. Sealing a method means one can not override it. In C# structs are implicitly sealed; therefore, they cannot be inherited. If we try to inherit from a sealed class in another class we will get compile time error about Inconsistent accessibility (code is shown in following code listing).

Listing 11

public class TestClass : classSealed

In C# a method can not be declared as sealed. However when we override a method in a derived class, we can declare the overridden method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method.

Listing 12

public class testClass
public int x;
public int y;
public virtual void testMethod(){



public class TestClass: testClass
public override sealed void testMethod(){


So Which One Should I Use?

Abstract classes can add more functionality without destroying the child classes that were using the old version. Abstract classes provide a simple and easy way to version our components. By updating the base class, all inheriting classes are automatically updated with the change. In an interface, creation of additional functions will have an effect on its child classes due to the necessary implementation of interface Methods in classes. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes. Say there are two classes, bird and airplane, and both of them have methods called fly. It would be ridiculous for an airplane to inherit from the bird class just because it has the fly() method. Rather, the fly() method should be defined as an interface and both bird and airplane should implement that interface. If we want to provide common, implemented functionality among all implementations of component, we should use an abstract class. Abstract classes allow us to partially implement classes, whereas interfaces contain no implementation for any members. So the selection of interface or abstract classes depends on the needs and design of our project. We can make an abstract class, interface, or combination of both depending on our needs.

The most likely situation in which we make a class or method sealed will be if the class or method is internal to the operation of the library, class, or other classes that we are writing. Because any attempt to override some of its functionality will cause problems. We can mark a class or method as sealed for commercial reasons, in order to prevent a third party from extending our classes. For example, in the .NET base class library string is a sealed class.

We should not use the sealed key word on a method unless that method is itself an override of another method in some base class. If we are defining a new method and we don’t want anyone else to override it, we should not declare it as virtual in the first place. If however, we have overridden a base class method, the sealed keyword provides a way of ensuring that the override supplied to a method is a “final” override that means no one else can override it again.
[ Back To Top ]

Recommendations for Abstract Classes vs. Interfaces

Abstract and Sealed Classes and Class Members (C# Programming Guide)
[ Back To Top ]

Well, this is my thought on interfaces and abstract classes, we want to have an abstract class when concrete classes will be sharing similar implementation details, like each employee has a name, that field can be stored in the abstract class, and also the property to access that information can be in the abstract class. So when we have similar classes that will share code use an abstract class, however if we have classes that are nothing to do with one another but share some aspect that they do not share a common ancestor then use an interface. Use sealed classes when the class should not have any derived classes.

Monday, February 22, 2010

Windows Communication Foundation Endpoints: Addresses, Bindings, and Contracts

All communication with a Windows Communication Foundation (WCF) service occurs through the endpoints of the service. Endpoints provide clients access to the functionality offered by a WCF service.

Each endpoint consists of four properties:

* An address that indicates where the endpoint can be found.

* A binding that specifies how a client can communicate with the endpoint.

* A contract that identifies the operations available.

* A set of behaviors that specify local implementation details of the endpoint.

This topic discusses this endpoint structure and explains how it is represented in the WCF object model.
The Structure of an Endpoint

Each endpoint consists of the following:

* Address: The address uniquely identifies the endpoint and tells potential consumers of the service where it is located. It is represented in the WCF object model by the EndpointAddress class. An EndpointAddress class contains:

o A Uri property, which represents the address of the service.

o An Identity property, which represents the security identity of the service and a collection of optional message headers. The optional message headers are used to provide additional and more detailed addressing information to identify or interact with the endpoint.

For more information, see Specifying an Endpoint Address.

* Binding: The binding specifies how to communicate with the endpoint. This includes:

o The transport protocol to use (for example, TCP or HTTP).

o The encoding to use for the messages (for example, text or binary).

o The necessary security requirements (for example, SSL or SOAP message security).

For more information, see Windows Communication Foundation Bindings Overview. A binding is represented in the WCF object model by the abstract base class Binding. For most scenarios, users can use one of the system-provided bindings. For more information, see System-Provided Bindings.

* Contracts: The contract outlines what functionality the endpoint exposes to the client. A contract specifies:

o What operations can be called by a client.

o The form of the message.

o The type of input parameters or data required to call the operation.

o What type of processing or response message the client can expect.

For more information about defining a contract, see Designing Service Contracts.

* Behaviors: You can use endpoint behaviors to customize the local behavior of the service endpoint. Endpoint behaviors achieve this by participating in the process of building a WCF runtime. An example of an endpoint behavior is the ListenUri property, which allows you to specify a different listening address than the SOAP or Web Services Description Language (WSDL) address. For more information, see ClientViaBehavior.

Defining Endpoints

You can specify the endpoint for a service either imperatively using code or declaratively through configuration. For more information, see How to: Create a Service Endpoint in Configuration and How to: Create a Service Endpoint in Code.
In This Section

This section explains the purpose of bindings, endpoints, and addresses; shows how to configure a binding and an endpoint; and demonstrates how to use the ClientVia behavior and ListenUri property.

Endpoint Addresses
Describes how endpoints are addressed in WCF.

Windows Communcation Foundation Bindings
Describes how bindings are used to specify the transport, encoding, and protocol details required for clients and services to communicate with each other.

Describes how contracts define the methods of a service.

How to: Create a Service Endpoint in Configuration
Describes how to create a service endpoint in configuration.

How to: Create a Service Endpoint in Code
Describes how to create a service endpoint in code.

How to: Use Svcutil.exe to Validate Compiled Service Code
Describes how to detect errors in service implementations and configurations without hosting the service using the ServiceModel Metadata Utility Tool (Svcutil.exe).

WCF Feature Details

Windows Communication Foundation (WCF) allows extensive control over the messaging functions of an application. The topics in this section go into detail about the available features. For more information about basic programming, see Basic WCF Programming.
In This Section

1. Windows Communication Foundation Endpoints: Addresses, Bindings, and Contracts
Describes how to control multiple aspects of your service.

2. Data Transfer and Serialization in Windows Communication Foundation
Describes how serialization of data can be tailored for interoperation or future compatibility.

3. Sessions, Instancing, and Concurrency in Windows Communication Foundation
Describes the instancing and session modes of WCF and how to select the right mode for your application.

4. Transports in Windows Communication Foundation
Describes how to configure the transport layer, the lowest level of the channel stack.

5. Queues and Reliable Sessions in Windows Communication Foundation
Describes queues, which store messages from a sending application on behalf of a receiving application and later forward these messages to the receiving application.

6. Transactions in Windows Communication Foundation
Explains how to created transacted operations that can be rolled back if needed.

7. Windows Communication Foundation Security
Describes how WCF security helps you to create applications that have confidentiality and integrity. Authentication and authorization are also available, as are auditing features.

8. Peer-to-Peer Networking
Details how to create peer services and clients.

9. Metadata in Windows Communication Foundation
Describes metadata architecture and formats.

10. Windows Communication Foundation Clients
Describes how to create a variety of clients that access services.

11. Hosting of Windows Communication Foundation Services
Describes hosting. A service can be hosted by another application, or it can be self-hosted.

12. Interoperability and Integration with Windows Communication Foundation
Describes how to use WCF to extend your existing logic rather than having to rewrite it if you have a substantial investment in component-based application logic hosted in COM+.

13. WCF REST Programming Model
Describes the WCF Web Programming Model that allows developers to expose WCF service operations to non-SOAP endpoints.

14. WCF Syndication
Describes support to easily expose syndication feeds from a WCF service.

15. Windows Communication Support for AJAX Integration and JSON
Describes support for ASP.NET Asynchronous JavaScript and XML (AJAX) and the Javascript Object Notation (JSON) data format to allow WCF services to expose operations to AJAX clients.





see below link:

Friday, February 19, 2010

sample Program for xml File creation,Insert Nodes,Delete Nodes Data and Find data by nodename

Private Function createXML() As String
' This method shows how to build an XML file all from code.
Dim xDoc As New XmlDocument

Dim xPI As XmlProcessingInstruction
Dim xComment As XmlComment
Dim xElmntRoot As XmlElement
Dim xElmntRecalac As XmlElement

xPI = xDoc.CreateProcessingInstruction("xml", "version='1.0'")

xComment = xDoc.CreateComment("Server Configuration Information")

xElmntRoot = xDoc.CreateElement("xml")

' Rather than creating new nodes individually,
' count on the fact that AppendChild returns a reference
' to the newly added node.
xElmntRecalac = CType(xElmntRoot.AppendChild(xDoc.CreateElement("SERVER_CONFIG")), XmlElement)
Return xDoc.OuterXml
End Function
Private Sub addElements()
Dim xDoc As New XmlDocument

Dim xNode As XmlNode
Dim xElmntSERVER_CFG As XmlElement = Nothing
' Search for a particular node
xNode = xDoc.SelectSingleNode("//SERVER_CONFIG")
Dim xnode_SERVER_ID As XmlNodeList
xnode_SERVER_ID = xDoc.SelectNodes("//SERVER_ID")
mintSERVER_ID = xnode_SERVER_ID.Count + 1
If mintSERVER_ID = 0 Then
mintSERVER_ID = 1
End If
If xNode IsNot Nothing Then
If TypeOf xNode Is XmlElement Then
xElmntSERVER_CFG = CType(xNode, XmlElement)
End If

InsertTextNode(xDoc, xElmntSERVER_CFG, "SERVER_ID", mintSERVER_ID)
InsertTextNode(xDoc, xElmntSERVER_CFG, "SERVER_NAME", txtServerName.Text)
InsertTextNode(xDoc, xElmntSERVER_CFG, "SERVER_IP", txtIPADDRESS.Text)
InsertTextNode(xDoc, xElmntSERVER_CFG, "DESCRIPTION", txtSERVER_DESC.Text)
End If

End Sub
Private Function InsertTextNode(ByVal xDoc As XmlDocument, ByVal xNode As XmlNode, ByVal strTag As String, ByVal strText As String) As XmlElement
' Insert a text node as a child of xNode.
' Set the tag to be strTag, and the
' text to be strText. Return a pointer
' to the new node.

Dim xNodeTemp As XmlNode

xNodeTemp = xDoc.CreateElement(strTag)

Return CType(xNodeTemp, XmlElement)
End Function

Dim xDoc As New XmlDocument

Dim xnode_SNAME As XmlNodeList
Dim mstrSERVERNAME As XmlNode
xnode_SNAME = xDoc.SelectNodes("//SERVER_NAME")

For Each mstrSERVERNAME In xnode_SNAME
If mstrSERVERNAME.InnerText = Trim(cboServerName.SelectedItem) Then
mstrSERVERNAME.InnerText = txtServerName.Text
mstrSERVERNAME.NextSibling.InnerText = txtIPADDRESS.Text
mstrSERVERNAME.NextSibling.NextSibling.InnerText = txtSERVER_DESC.Text
End If
cboServerName.Visible = False
txtServerName.Visible = True
End Sub
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
MsgBox("UPDATE Successfully !", MsgBoxStyle.Information)
End Sub

Wednesday, February 17, 2010

Session value changes or clear on window .open

I have the same problem i.e, Session is not present whenever i call

When i check this problem more closely then i find that ASP.NET_SessionId cookie is not passed to new window.

There fore i pass the SessionID in Query String in like,'" & Session.SessionID &','V');

and put this in global.asax

Private Sub Application_PostMapRequestHandler(ByVal sender As Object, ByVal e As EventArgs)
If (Request.Cookies("ASP.NET_SessionId") Is Nothing) AndAlso (Request.QueryString("SASID") IsNot Nothing) Then
Request.Cookies.Add(New HttpCookie("ASP.NET_SessionId", Request.QueryString("SASID")))
End If
End Sub

Wednesday, February 10, 2010

Difference between ASP.NET web service e and programming WCF services

In this post I will explain the Difference between ASP.NET web service and programming WCF services like ASP.NET web services. It also discusses how we use the both technologies for developing the web services.

The development of web service with ASP.NET relies on defining data and relies on the XmlSerializer to transform data to or from a service.

Key issues with XmlSerializer to serialize .NET types to XML

* Only Public fields or Properties of .NET types can be translated into XML.
* Only the classes which implement IEnumerable interface.
* Classes that implement the IDictionary interface, such as Hash table can not be serialized.

The WCF uses the DataContractAttribute and DataMemeberAttribute to translate .NET FW types in to XML.

public class Item
public string ItemID;
public decimal ItemQuantity;
public decimal ItemPrice;


The DataContractAttribute can be applied to the class or a strcture.
DataMemberAttribute can be applied to field or a property and theses fields or properties can be either public or private.

Important difference between DataContractSerializer and XMLSerializer.

* A practical benefit of the design of the DataContractSerializer is better performance over XMLserialization.
* XMLSerialization does not indicate the which fields or properties of the type are serialized into XML where as DataCotratSerializer Explicitly shows the which fields or properties are serialized into XML.
* The DataContractSerializer can translate the HashTable into XML.

Developing Service

To develop a service using ASP.NET we must add the WebService attribute to the class and WebMethodAttribute to any of the class methods.


public class Service : System.Web.Services.WebService
public string Test(string strMsg)
return strMsg;

To develop a service in WCF we will write the following code

public interface ITest
string ShowMessage(string strMsg);
public class Service : ITest
public string ShowMessage(string strMsg)
return strMsg;

The ServiceContractAttribute specifies that a interface defines a WCF service contract, OperationContract Attribute indicates which of the methods of the interface defines the operations of the service contract.

A class that implements the service contract is referred to as a service type in WCF.

Hosting the Service

ASP.NET web services are compiled into a class library assembly and a service file with an extension .asmx will have the code for the service. The service file is copied into the root of the ASP.NET application and Assembly will be copied to the bin directory. The application is accessible using url of the service file.

WCF Service can be hosted within IIS or WindowsActivationService.

* Compile the service type into a class library
* Copy the service file with an extension .SVC into a virtual directory and assembly into bin sub directory of the virtual directory.
* Copy the web.config file into the virtual directory.

Client Development

Clients for the ASP.NET Web services are generated using the command-line tool WSDL.EXE.

WCF uses the ServiceMetadata tool(svcutil.exe) to generate the client for the service.

Message Representation

The Header of the SOAP Message can be customized in ASP.NET Web service.

WCF provides attributes MessageContractAttribute , MessageHeaderAttribute and MessageBodyMemberAttribute to describe the structure of the SOAP Message.

Service Description

Issuing a HTTP GET Request with query WSDL causes ASP.NET to generate WSDL to describe the service. It returns the WSDL as response to the request.

The generated WSDL can be customized by deriving the class of ServiceDescriptionFormatExtension.

Issuing a Request with the query WSDL for the .svc file generates the WSDL. The WSDL that generated by WCF can customized by using ServiceMetadataBehavior class.

Exception Handling

In ASP.NET Web services, Unhandled exceptions are returned to the client as SOAP faults.

In WCF Services, unhandled exceptions are not returned to clients as SOAP faults. A configuration setting is provided to have the unhandled exceptions returned to clients for the purpose of debugging.

Advantages of WCF:

benefits of WCF over Web services. Here they are
1.WCF supports more of WS-* standards than web services
2.As I mentioned in the article WCF supports multiple bindings HTTP,TCP,MSMQ,WS-HTTP etc where as web service supports only HTTP.
3.WCF can maintain transactions like COM+
4.It has JSON integration
5.It can be hosted on IIS,WAS, Self hosting and windows services
6.Web services have no instance management ie you can not have a singleton web service or session full webservice