Daily Archives: February 10th, 2009

Xml Basics


XML stands for Extensible Markup Language. XML is a markup language much like HTML. XML was designed to describe data. XML tags are not predefined in XML. You must define your own tags. XML is self describing. XML uses a DTD (Document Type Definition) to formally describe the data.

Xml Document:

Xml Document is composed of markups and contents. Six kinds of markups can occur in xml Document.

1. Document Type Declaration
2. Elements
3. Entity References
5. Processing Instruction
6. Conditional Section

The elements should follow the following rules:

• Every start-tag must have a matching end-tag.
• Tags cannot overlap. Proper nesting is required.
• XML documents can only have one root element.
• Element names must obey the following XML naming conventions:
o Names must start with letters or the “_” character. Names cannot start with numbers of punctuation characters.
o After the first character, numbers and punctuation characters are allowed.
o Names cannot contain spaces.
o Names should not contain the “:” character as it is a “reserved” character.
o Names cannot start with the letters “xml” in any combination of case.
o The element name must come directly after the “<” without any spaces between them.
• XML is case sensitive.
• XML preserves white space within text.
• Elements may contain attributes. If an attribute is present, it must have a value, even if it is an empty string “”.

What is Element?

Elements are the logical components of XML documents. When all of our documents are abstracted into smaller parts, we can manipulate their content from whichever perspective we require. The smaller parts of our larger documents can be represented in XML using “elements.”
Elements consist of words that serve as the “names” for your element “tags” and are surrounded on either side by “less than” (<) and “greater than” (>) characters. These start and end tags may be used to encapsulate character data (text), as in the following example.

<Summary>Text goes in here</Summary>

What is Attributes?

Attributes provide a means of assigning “extra” information to elements in order to further describe properties of those elements. Attribute-value pairs can be associated with elements by including them inside of an element’s start tag.
XML attributes are normally used to describe XML elements, or to provide additional information about elements.

XML Schema:

Xml Schema is an Xml based alternative to DTD. Xml Schema describes the structure of the Xml Document. Xml schema language is also referred to as Xml Schema Definition (XSD).

Xml Schema defines the following

• Elements and attributes that can appear in a Document.
• Child Elements
• The order and number of child elements
• Whether an element is empty or can include Text.
• Data types for elements and attributes
• Default and fixed values for elements and attributes.
Xml Schema Elements:

The First Element in an Xml Schema file is schema element.
Xmlns- xml Namespace

<xsd: schema xmlns: xsd =“ http://www.w3.org/2001/XMLSchema“ >

</xsd: schema>
The main sub elements in xml schema
1. element: declares an element
2. attribute: declares an attribute
3. complexType: The elements that can contain other elements and attributes.
4. simpleType: the elements that can not contain other elements or attributes. These elements are the basic types, including string, data, integer etc.
The xsd: annotation and xsd: documentation tags are used for providing description of the document.

For example

<xsd: schema xmlns:xsd=”http://www.w3.org/2001/XMLSchema”&gt;
<xsd: annotation>
<xsd: documentation xml: lang =”en”>
Bookstore schema for book.xml
</xsd: documentation>
</xsd: annotation>
</xsd: schema>

In our XML example the element bookstore is a complexType element because it contains book sub-elements.

<xsd: element name=”bookstore” type=”bookstoreinfo”/>
<xsd: complexType name=”bookstoreinfo”>
<xsd: sequence>
<xsd: element name=”book” type=”bookinfo”/>
</xsd: sequence>
</xsd: complexType>

Our book element is also a complexType element.

<xsd: complexType name=”bookinfo”>
<xsd: sequence>
<xsd: element name=”title” type=”titleinfo”>
<xsd: element name=”author” type=”xsd:string”/>
<xsd: element name=”year” type=” xsd:string”/>
<xsd: element name=”price” type=” xsd:string”/>
</xsd: sequence>
</xsd: complexType>

The sub-elements author, year and price are of type xsd:string. The sub-element title is of complexType because it has an attribute named id. To define an attribute use the following:

<xsd: attribute name=”id” type=”xsd: string” use=”required”/>
Use value required means this attribute is mandatory. By default attributes are optional.

The main difference between XML and HTML:

XML is not a replacement for HTML. XML and HTML were designed with different goals:
• XML was designed to describe data and to focus on what data is. HTML was designed to display data and to focus on how data looks.
• HTML is about displaying information, XML is about describing information.

Use of XML:

• XML can keep data separated from your HTML
• XML can be used to store data inside HTML documents
• XML can be used as a format to exchange information
• XML can be used to store data in files or in databases

Find whether the class inherited from a particular interface

/* interface and ‘is’ operator*/

By using ‘is’ operator we can find that, whether the class is inherited from a particular interface/class.


using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace LearningConcepts

interface INode

string Text

object Tag

int Height

int Width

float CalculateArea();


public class Node : INode

public Node()
{ }
public string Text
get {return m_text;}
set {m_text = value;}

private string m_text;
public object Tag

get{return m_tag;}
set{m_tag = value;}


private object m_tag = null;
public int Height

get {return m_height;}
set {m_height = value;}


private int m_height = 0;
public int Width
Get {return m_width;}
Set {m_width = value;}


private int m_width = 0;
public float CalculateArea()

if ((m_width < 0) || (m_height < 0))
return 0;

return m_height * m_width;


class ClonableNode :ICloneable
public object Clone()
return null;

// INode members

class Program
static void Main(string[] args)
Node nodeC=new Node();
if (nodeC is INode)
Console.WriteLine(“nodeC is object of INode type”);
//this will be displayed
Console.WriteLine(“nodeC isn’t object of INode type”);


10. Reflection



            We can access some data about object at runtime by using Reflection.

That information contain

·          Data of the class

·          Names of the Methods that are inside the class

·          Constructor of that Object.

To write a C# .Net program this uses reflection,

                        The program should use the namespace System.Reflection.

To get type of the object,

                         The typeof operator can be used.                                

             There is one more method GetType ().

          uses to get data about object’s type

By using Reflection we can do the following

·         Can get all methods from a class

·         Can get all Fields and Properties from a class

·         Can get information about assembly

·         Can create instance for a class

·         Can execute a class method indirectly

·         Can get type information: base type, is abstract, is com object, is sealed, is class

·         Can get all implemented interfaces and inherited base classes 

Oops Concepts

7. Oops Concepts


            Abstract class can simply defined as incomplete class. It contains one or more incomplete methods called abstract methods. It leaves the implementation of these methods to derived or sub classes. Since abstract classes are incomplete, they can not be instantiated.

They must be sub-classed in order to use their functionality. So the abstract class can not be sealed. We can declare a reference of the type of abstract class and it can point to the object of the class that has inherited the abstract class.

We can add more functionality in abstract class without destroying child classes that were using old class.

Abstract class class_name


                                 // Constructor, constructor overloading and static constructor definition

                                 // Abstract method declaration;

                                 // Variable declaration;

                                 // Ordinary method declaration with their definition;

                                 // Static and virtual method declaration with their definition;


Few things about abstract class

*    Abstract class having declaration for abstract method.

*    You should define the abstract method using override keyword.

*    Abstract class support ordinary constructor, static constructor and constructor overloading.

*    Except private, all the access modifiers are allowed.

*    Ordinary methods will be having the definition part.

*    To declare the variables.

*    Static and virtual methods also to allow.

*    You can declare the interface inside the abstract class.

*    You should inherit the abstract class in derived class.

*    You can’t inherit more than one abstract class in derived class.

*    You can’t create the object for the abstract class, but you can create the reference for the abstract class.


            Sealed classes are used to restrict the inheritance feature of object oriented programming. Once a class is defined as sealed class, this class cannot be inherited.


The main features of a static class are:

·         They only contain static members.

·         They cannot be instantiated.

·         They are sealed.

·         They cannot contain Instance Constructors

Creating a static class is therefore much the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. Static classes cannot contain a constructor, although it is still possible to declare a static constructor to assign initial values or set up some static state


            It is possible to write a static no-parameter constructor for a class. One reason for writing a static constructor would be if your class has some static fields or properties that need to be initialized from an external source before the class is first used. It will be called automatically before the first instance is created.

Use of Static constructors:

*    Static constructor is used to initialize static data.

*    To perform particular action that needs performed once only

*    Another use of static constructor is, when the class is using a log file and the constructor is used to write entries to this file.


            A class can have private constructor also. It prevents the class from being instantiated by callers.

There are some cases where the private constructors can be useful:

*    Class containing only static utility methods

*    To implement singleton class.



It means “Ability to take more than one form”. An operation may exhibit different behavior and different instances. Behavior is depends upon the operation.

Polymorphism is the ability for classes to provide different implementations of methods that are called by the same name.


1.      Compile Time Polymorphism

2.      Runtime Polymorphism

Compile Time Polymorphism:

            Compile time polymorphism is functions and operators overloading.

Runtime polymorphism:

            Runtime time polymorphism is done using inheritance and virtual functions.


               Two or more methods within the same class can share the same name, as long as their parameter declarations are different.
*    number of parameters
*    type of parameters

            Mainly the overriding is to achieve Runtime Polymorphism. It allows a subclass to re-define a method it inherits from its super class

·If the super class method is public, the overriding method must be public
·If the super class method is protected, the overriding method may be protected or public
·If the super class method is package, the overriding method may be package, protected, or public
·If the super class methods is private, it is not inherited and overriding is not an issue


Overloading Vs. Overriding:

*    Overloading is nothing but static binding.

*    Overriding is dynamic binding which will be resolved at run-time.


*    Overloading deals with multiple methods in the same class with the same name but different signatures.

*    Overriding deals with two methods, one in a parent class and one in a child class, which have the same signature.


*    Overloading lets you define a similar operation in different ways for different data.

*    Overriding lets you define a similar operation in different ways for different object types.

Dynamic Binding/Late Binding:

                        It means that the code associated with a given procedure Call at Runtime.

Static Binding:

               It means that the code associated with a given procedure call during compile time itself.


A virtual function is a member function of the base class and which is redefined by the derived class. When a derived class inherits the class containing the virtual function, it has ability to redefine the virtual functions. A virtual function has a different functionality in the derived class according to the requirement. The virtual function within the base class provides the form of the interface to the function. Virtual function implements the philosophy of one interface and multiple methods (polymorphism).

The virtual functions are resolved at the run time. This is called dynamic binding. The functions which are not virtual are resolved at compile time which is called static binding. A virtual function is created using the keyword virtual which precedes the name of the function.

Comparison of interface with class (interface vs. class):

  • An interface cannot inherit from a class.
  • An interface can inherit from multiple interfaces.
  • A class can inherit from multiple interfaces, but only one class.
  • Interface members must be methods, properties, events, or indexers.
  • All interface members must have public access (the default).
  • By convention, an interface name should begin with an uppercase I.

Using and Using Alias

6. Using & Using Alias


The using directive has two uses:

  • To allow the use of types in a namespace so that you do not have to qualify the use of a type in that namespace:

Using System.Text; // Using Directives

All of the members defined within name of a Namespace are brought into view and can be used without qualification.

  • To create an alias for a namespace or a type. This is called a using alias directive.

Using Project = PC.MyCompany.Project; //Using Alias

The using keyword is also used to create using statements, which help ensure that IDisposable objects such as files and fonts are handled correctly.

As a rule, when you use an IDisposable object, you should declare and instantiate it in a using statement. The using statement calls the Dispose method on the object in the correct way, and (when you use it as shown earlier) it also causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and cannot be modified or reassigned.

The using statement ensures that Dispose is called even if an exception occurs while you are calling methods on the object. You can achieve the same result by putting the object inside a try block and then calling Dispose in a finally block; in fact, this is how the using statement is translated by the compiler.

Using has a second form that is called the using statement.

It has these general forms:

Using (obj) {//Using Statement

    // use obj


    Using (type obj = initializer) {

    // use obj



Obj is an object that is being used inside the using block. In the first form, the object is declared outside the using statement. In the second form, the object is declared within the using statement. When the block concludes, the Dispose () method (defined by the System.IDisposable interface) will be called on obj. The using statement applies only to objects that implement the System.IDisposable interface.


Font font2 = new Font (“Arial”, 10.0f);

Using (font2) // not recommended


    // use font2


// font2 is still in scope

// but the method call throws an exception

Float f = font2.GetHeight ();


*    The scope of a using directive is limited to the file in which it appears.

*    Create a using alias to make it easier to qualify an identifier to a namespace or type.

*    Create a using directive to use the types in a namespace without having to specify the namespace. A using directive does not give you access to any namespaces that are nested in the namespace you specify.

*    Namespaces come in two categories: user-defined and system-defined. User-defined namespaces are namespaces defined in your code. For a list of the system-defined namespaces, see .NET Framework Class Library Reference.

C# Namespaces

C# .Net Namespaces


          Namespace is logically group’s classes. Namespace can span in multiple assemblies.

Namespaces and its usage:

     System is the basic namespace for .Net Framework. It is having the following Namespaces

  1. Collections: The .NET Framework provides specialized classes for data storage and retrieval.   These classes provide support for stacks, queues, lists, and hash tables.
  2. ComponentModel: The ComponentModel namespace provides classes that are used to implement the run-time and design-time behavior of components and controls. This namespace includes the base classes and interfaces for implementing attributes and type converters, binding to data sources, and licensing components.
  3. Configuration: The Configuration namespace contains the types that provide the programming model for handling configuration data.
  4. Data: The Data namespace provides access to classes that represent the ADO.NET architecture. ADO.NET lets you build components that efficiently manage data from multiple data sources.
  5. Diagnostics: It Contains classes that enable you to debug and follow the execution of your applications.
  6. DirectoryServices: It Provides access to Active Directory services. Drawing Contains classes that enable you to use basic, graphical display interface (GDI) capabilities.
  7. EnterpriseServices: This Namespace Contains objects that enable you to control how components behave on a server.
  8. Globalization: This Namespace Contains classes that define culture-related information.
  9. IO: This Namespace Contains classes that enable you to read and write to data streams and files.
  10. Media: The Media namespace contains classes for playing sound files and accessing sounds provided by the system.
  11. Net: This Namespace Provides classes to work with network protocols.
  12. Reflection: This Namespace Contains classes that enable you to view information about other types in the .NET Framework.
  13. Resources: This Namespace Contains classes that enable you to manage culture specific resources.
  14. Runtime: This Namespace contains advanced types that support diverse namespaces.
  15. Security: The Security namespace provides the underlying structure of the common language runtime security system, including base classes for permissions.
  16. Text: The Text namespace contains classes representing ASCII, Unicode, UTF-7, and UTF-8 character encodings; abstract base classes for converting blocks of characters to and from blocks of bytes; and a helper class that manipulates and formats String objects without creating intermediate instances of String.
  17. Threading: This Namespace Contains classes that enable multi-threaded programming.
  18. Timers: This Namespace Contains classes to raise events on specified time intervals.
  19. XML: This Namespace contains the classes to work with XML file.

Just in time compiler

3. Just In Time Compiler (JIT)


               During Run Time, the CLR invokes the JIT compiler to convert the MSIL into Native code (i.e. Executable Binary Code). When the Function is called, the IL of the function’s body is converted to Native code Just In Time. So the part of code that is not used by the particular run is never converted to native code. If some IL is converted to native code, the next time it’s needed, the CLR reuses the same copy without re-compiling.

Types of JIT:

·   PreJIT

·   EconoJIT

·   Standard JIT

(1) PRE JIT: It Compiles complete source code to native code in a single Compilation.
(2) ECONO JIT: It compiles only those methods that are called at Runtime.
(3) NORMALE JIT: It compiles only those methods that are called at Runtime and are stored in cache.

Sending e-mails with C# .NET 2.0


First step: Setting-up your SMTP (Simple Mail Transfer Protocol)


you must have installed IIS (internet information services), so you can setup your SMTP Virtual Server from there.


Control Panel->Administrative Tools->Internet Information Services , then you select the SMTP Virtual Server Properties and grant permission to local host ( (Access->Relay).


Second Step: Writing the basic C# Code


Example: Windows Application


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Net;

using System.Net.Mail;

using System.Windows.Forms;


namespace Threading


    public partial class Form1 : Form


        public Form1()




    protected void Button1_Click(object sender, EventArgs e)


        MailMessage objMM = new MailMessage();

        objMM.From = new MailAddress(textBox1.Text, “sender name”);

        objMM.To.Add(new MailAddress(textBox2.Text, “reciever name”));

        objMM.Subject = textBox3.Text;

        objMM.Body = richTextBox1.Text;

        SmtpClient objSC = new SmtpClient(“localhost”, 25);

        objSC.DeliveryMethod = SmtpDeliveryMethod.Network;

        objSC.Host = “smtp.gmail.com”; // for example gmail smtp server

        objSC.EnableSsl = true;

        objSC.Credentials = new System.Net.NetworkCredential(“mailid”, “password”);





        catch (Exception ex)





        MessageBox.Show(“Mail send successfully”);






Be sure that the recipient checks his spam messages because many of the e-mails using this algorithm go there. Also don’t forget to include System.Net.Mail namespace (using System.Net.Mail ;).




In .NET 1.1 you can use SmtpMail class (.NET1.1 does not support SmtpClient class) and be sure to include System.WEB.Mail.

Smtp Classes in .Net

MailMessage Class:

     The MailMessage class can be considered the foundation class of the System.Net.Mail namespace. It deals with creating and managing the email message. All other classes will somehow interact with this class. The MailMessage class exposes such properties as the




 Gets the attachment collection used to store data attached to this e-mail message.


 Gets the address collection that contains the blind carbon copy (BCC) recipients for this e-mail message.


 Gets or sets the message body.


 Gets the address collection that contains the carbon copy (CC) recipients for this e-mail message.


 Gets or sets the from address for this e-mail message.


 Gets or sets the subject line for this e-mail message.


 Gets the address collection that contains the recipients of this e-mail message.

Below you will find an example of using the MailMessage class


//create the mail message
MailMessage mail = new MailMessage ();
//set the addresses
mail.From = new MailAddress ("me@mycompany.com");
mail.To.Add ("you@yourcompany.com");
//set the content
mail.Subject = "This is an email";
mail.Body = "this is the body content of the email”;

MailAddress Class:

            The MailAddress class is used for creating email addresses. This class is used for setting the MailMessage.From, MailMessage.To, MailMessage.CC and MailMessage.BCC properties. Of these properties the .From class is actually a MailAddress, while the To, CC and BCC properties are actually collections of MailAddresses. The two most common properties of the MailAddress class are the DisplayName and the Address properties. They are described below.




Gets the e-mail address specified when this instance was created.


Gets the display name composed from the display name and address information specified when this instance was created.


//set the addresses

//to specify a friendly 'from' name, we use a different ctor
mail.From = new MailAddress ("me@mycompany.com", "Steve James");

Attachment Class:

            The Attachment class is used for creating and managing individual attachments of the MailMessage object. Attachments can be created from streams or file paths. The stream or file path must be set in the ctor of the Attachment.

Below is an example demonstrating the Attachment class


 Static void AttachmentFromFile ()


//create the mail message

MailMessage mail = new MailMessage ();

//set the addresses

mail.From = new MailAddress (“me@mycompany.com”);

mail.To.Add (“you@yourcompany.com”);

//set the content

mail.Subject = “This is an email”;

mail.Body = “this content is in the body”;


//add an attachment from the file system

mail.Attachments.Add (new Attachment (“c:\\temp\\example.txt”));

//to add additional attachments, simply call .Add (…) again

mail.Attachments.Add (new Attachment (“c:\\temp\\example2.txt”));

mail.Attachments.Add (new Attachment (“c:\\temp\\example3.txt”));

//send the message

SmtpClient smtp = new SmtpClient(“”);




SmtpClient Class:

The SmtpClient class is responsible for sending or transporting the email. The SmtpClient can transport the email content over the network, or it can actually write them to the filesystem in the MS IIS Smtp Service Pickup Directory format, which resembles a RFC821 formatted message. Emails can be sent either synchronously or asynchronously. The SmtpClient also supports sending email via SSL for security purposes. The following list of properties are the most common used on the SmtpClient class.




Gets or sets the credentials used to authenticate the sender.


Specifies how outgoing email messages will be handled.


Specify whether the SmtpClient uses Secure Sockets Layer (SSL) to encrypt the connection.


Gets or sets the name or IP address of the host used for SMTP transactions.


Gets or sets the port used for SMTP transactions.


AlternateView class:

The AlternateView class is used for providing alternate bodies and creating Multi-Part mime emails. If you want to create an email that will be rendered properly in both Html capable and Plain Text only mail clients, then you will create alternate views of the message. There are a few main properties and methods you will use with the AlternateView class. They are:




Gets or sets the Base URI to use for resolving relative URIs in the AlternateView


Gets the set of embedded resources referred to by this attachment.

CreateAlternateViewFromString (static method)

Overloaded. Creates an AlternateView to view an email message using the specified format..


LinkedResource class:

The LinkedResource class is the last, and least used main class. It is mainly used for creating embedded images. To create an embedded image you will need to first create a Html formatted AlternateView. Within that alternate view you create an tag, that points to the ContentId (CID) of the LinkedResource. You then create a LinkedResource object and add it to the AlternateView’s LinkedResources collection.

SMTP Basics

Simple Mail Transfer Protocol:

Short for Simple Mail Transfer Protocol, a protocol for sending e-mail messages between servers. Most e-mail systems that send mail over the Internet use SMTP to send messages from one server to another; the messages can then be retrieved with an e-mail client using either POP or IMAP. In addition, SMTP is generally used to send messages from a mail client to a mail server.

Reasons why you might want to send email from your Web application:

*    create a “give us your feedback” Web page

*    implement a “forgotten password” script that sends a password to the user’s email account

*    send an automatic welcome email to your new newsletter subscriber

*    send automatic email update notifications

*    send automatic email notifications whenever an error occurs in your Web application

SMTP Server:

A relay is a service that allows you to send email. It is usually a full fledged mail server, or can be a specialized SMTP Service. Some examples of a mail server include Microsoft Exchange, IMail by IPSwitch, or Mail Enable by Mail Enable. An example of a SMTP service is the SMTP Service installed that can be installed with IIS. SNM sends email to a relay server, and the relay server is responsible for delivering the email to the final destination. When sending email to a relay server, you must have protocol permissions to use that server. Because of SPAM problems, relay servers are normally locked down, either by IPAddress or by some type of username/password authentication. Relaying errors are the most common problems when programmatically sending emails.


System. Net. Mail Namespace:

System.Net.Mail is the namespace used to send email if you are using the 2.0 (or higher) .NET Framework.

Unlike System.Web.Mail, which was introduced in the 1.0 Framework, it is not built upon the CDO/CDOSYS libraries. Although some functionality has been removed, the new System.Net.Mail namespace is much more versatile than the older CDO dependant System.Web.Mail.

In this Mail Namespace, the following classes are available

è    MailMessage

è    MailAddress

è    Attachment

è    SmtpClient

è    AlternateView

è    Linked Resource