Feeds:
Posts
Comments

Reflection

10. Reflection

 

Definition:

            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:

            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 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.

STATIC CLASS:

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

STATIC CONSTRUCTOR:

            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.

PRIVATE CONSTRUCTOR:

            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.

POLYMORPHISM:

Definition:

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.

Types:

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.

Overloading:

               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
Overriding:

            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.

VIRTUAL FUNCTION:

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.

Example

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 ();

Notes:

*    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:

          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.

 

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 (127.0.0.1) (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()

        {

            InitializeComponent();

        }       

    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”);

        try

        {

            objSC.Send(objMM);

        }

        catch (Exception ex)

        {

            MessageBox.Show(ex.ToString());

        }

 

        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 ;) .

 

Extra:

 

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

Property

 Description

Attachments

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

Bcc

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

Body

 Gets or sets the message body.

CC

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

From

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

Subject

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

To

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

Below you will find an example of using the MailMessage class

Example:

//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.

Name

Description

Address

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

DisplayName

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

Example:

//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

[C#]

 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(“127.0.0.1″);

smtp.Send(mail);

 

}

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.

Name

Description

Credentials

Gets or sets the credentials used to authenticate the sender.

DeliveryMethod

Specifies how outgoing email messages will be handled.

EnableSsl

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

Host

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

Port

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:

Name

Description

BaseUri

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

LinkedResources

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.

Follow

Get every new post delivered to your Inbox.