Thursday, July 31, 2008

Working with Email Using ASP.NET 2.0

Working with Email Using ASP.NET 2.0

Introduction

In ASP.NET 1.x sending email was fairly simple. The only issue was that there were different ways to send email depending on whether the application was web or windows based. Windows developers used MAPI to send emails using an email client like Outlook. Web developers used CDOSYS to send rich emails. Microsoft realized that a change was warranted. In ASP.NET 2.0 Microsoft released a new set of classes to handle email. The only issue is that to many developers, sending email became much more complex. Within this article, we will walk through the changes to the web.config file, the new classes that are available and how to send email using the new MailMessage class.

Examining the Web.config

By now you should be familiar with the system.web section group that is found in the web.config file. In ASP.NET 2.0 a new group was added that contains configurable sections for the System.Net namespace called the system.net section group. This group allows email settings to be established by using the mailSettings section group. Since we are sending emails and not receiving emails, we will use the SMTP protocol. To define the SMTP settings, we will add the SMTP section group to the mailSettings section group. The SMTP section group then contains a network section that specifies attributes for the SMTP network settings. These attributes include host, port, username, and password. An example of the system.net section group can be found in listing 1.

Listing 1

host="mail.contoso.com"

userName="email@contoso.com" password="password" />

Accessing the Web.config from Code

To prevent confusion, in ASP.NET 2.0 the System.Web.Mail namespace has been marked deprecated. All of the classes are still accessible using IntelliSense and will still function properly. However, they too are marked obsolete. Instead, a new namespace found at System.Net.Mail should be used. This new namespace contains classes to manage your mail client and messages. The SmtpClient class is used to establish a host, port, and network credentials for your SMTP server. The MailMessage class is similar to the MailMessage class found in the old System.Web.Mail namespace. This class allows a full email message to be built. There is also an Attachment class that allows an attachment to be generated so it can later be added to the MailMessage object. In addition to these three most commonly used classes, you will find that System.Net.Mail contains an AlternateView and LinkedResource class.

Unfortunately, ASP.NET 2.0 does not provide a clean and easy way to access the system.net section group from the web.config file within code. The SmtpClient object contains a UseDefaultCredentials boolean property, but that specifies whether the SmtpClient object is to use the credentials of the user currently running the application. Before we begin accessing the attributes in the web.config file, we will need to determine what credentials will be required to connect to the SMTP server and ensure that the values we will use will work. In many cases, the credentials that would be used to connect to a Microsoft Exchange server would be different than those to connect to many ISP email systems. In the example to follow we will use a username, password, and hostname.

The first task on our plate is to read the mailSettings section group from the web.config file. To accomplish this task, we will need to create a new object of type System.Configuration.Configuration. This object will store our web.config file. We will assign this new object to the applications web.config by using the OpenWebConfiguration method of the WebConfigurationManager class. The OpenWebConfiguration method will look for a relative path. We will pass in the HttpContext.Current.Request.ApplicationPath since we will want to load the web.config file for the current application.

The second task is to load the specific section group from the object that contains our web.config file into a new object. A new object of type System.Net.Configuration.MailSettingsSectionGroup will be created. This object will be assigned to the mailSettings section in the web.config file. We will use the GetSectionGroup method of our configuration object to obtain this section. ASP.NET does not know that the mailSettings section is found under system.net so we must specify the full section group as system.net/mailSettings. An example of this can be seen in listing 2.

Listing 2

(IN Vb.net)

Dim config As System.Configuration.Configuration = _

WebConfigurationManager.OpenWebConfiguration( _

HttpContext.Current.Request.ApplicationPath)

Dim settings As System.Net.Configuration.MailSettingsSectionGroup = _

CType(config.GetSectionGroup("system.net/mailSettings"), _

System.Net.Configuration.MailSettingsSectionGroup)

(In C#)

System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current.Request.ApplicationPath);

System.Net.Configuration.MailSettingsSectionGroup settings = (System.Net.Configuration.MailSettingsSectionGroup)config.GetSectionGroup("system.net/mailSettings");

Creating the SMTP Client

A new object of type SmtpClient will be created to act as the SMTP server for mail being sent out. The SmtpClient object will need to have the network credentials passed into it. Thus, we will need to create a new object of type System.Net.NetworkCredential and pass in the username and password values from the web.config. These values can be found by assessing the Smtp.Network.Username and Smtp.Network.Password properties of the settings object defined earlier. The NetworkCredential object will be assigned to the Credentials property of the SmtpClient object. The other property we must set is the SmtpClient object's host property. This too will be assigned a value from the settings object created earlier. An example of this can be seen in the listing given below.

Listing 3

'Obtain the Network Credentials from the mailSettings section

Dim credential As New System.Net.NetworkCredential( _

settings.Smtp.Network.UserName, settings.Smtp.Network.Password)

'Create the SMTP Client

Dim client As New SmtpClient()

client.Host = settings.Smtp.Network.Host

client.Credentials = credential

Creating a MailMessage Object

The MailMessage object in ASP.NET 2.0 is much more robust than the one found in the CDOSYS libraries in ASP.NET 1.x. The new MailMessage object still contains all of the common properties that an email message has including To, From, Subject, and Body. The To and From properties have changed a bit. The From property is no longer "just a string." Instead, the From property is of type MailAddress. The To property is similar in that it is a collection of MailAddress objects. Since the CC and Bcc properties have the same requirements as the To property, they too are a collection of MailAddress objects. The MailMessage object contains some additional properties including, but not limited to, AlternateViews, Attachments, BodyEncoding, DeliveryNotificationOptions, IsBodyHtml, Priority, and ReplyTo.

The AlternateViews property allows an alternate view to be specified by passing in either a filename or a stream and assigning a MIME type to the view. The Attachments property allows attachments to be added to the message. The BodyEncoding property is a value that can specify the System.Text.Encoding type of the email message. The DeliveryNotificationOptions property specifies when delivery notifications should be received. The IsBodyHtml property is a boolean value signifying whether the email's body is HTML or plain text. The Priority property specifies whether this email is of high, low, or normal importance. The ReplyTo property is the email address that the reply message would go to.

To send the MailMessage object, the object must be passed into the Send method of the SmtpClient object. An example of this can be seen in the listing below.

Listing 4

'Build Email Message

Dim email As New MailMessage

email.From = New MailAddress("email@contoso.com")

email.To.Add("steveb@contoso.com")

email.CC.Add("billg@contoso.com")

email.Subject = "Test Email"

email.IsBodyHtml = True

email.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure

email.Body = "Hello Steve!"

'Send Email

client.Send(email)

Conclusion

As you can see now, sending email in ASP.NET 2.0 is much more complex. However, it is also much more robust. Many of the email options that you could not access before without adding an email header to the email message can now be added with properties. Hopefully the team will continue to enhance this namespace and add additional functionality in the future.

Resouse url : http://aspalliance.com/articleViewer.aspx?aId=962&pId=-1

Send Mails from within a .NET 2.0 Application

Send Mails from within a .NET 2.0 Application

Most enterprise applications today need to send mail. This means the platform should provide the necessary support for applications to send these mails. In the case of .NET applications, .NET provides excellent support for sending e-mails through a set of intuitive classes. This article introduces the new ways of sending mails through the System.Net.Mail namespace by showing examples. You also will see the steps involved in sending attachments as part of the mails, as well as sending mails to multiple recipients in the form of CC and BCC lists. Finally, it explains the use of XML and XSL in formatting the bodies of HTML-based mails.

.NET 2.0 Mail Functions

Microsoft made some interesting changes in how you can send e-mail in version 2.0 of the .NET Framework. With .NET 1.x versions, you had to utilize the classes contained in the System.Web.Mail namespace for sending mails. Now, with the release of .NET 2.0, the System.Web.Mail namespace is obsolete and its functionality is now available in the System.Net.Mail namespace. This is a welcome change because the mail functionality was intended to be used for all .NET applications and should not have been under System.Web assembly.

In addition to moving the functionality under the System.Net.Mail namespace, the .NET team also completely rebuilt the implementation of SMTP functionality. There are new classes, properties, and methods that provide an elegant and clean way of performing operations related to sending mails. This long list of new enhancements includes quality improvements, different methods, and asynchronous support out of the box.

Now that you have a general understanding of the support provided by .NET 2.0 for sending mails, let us dive deep into the actual classes contained in the System.Net.Mail namespace.

System.Net.Mail Namespace

The System.Net.Mail namespace contains all the classes required for sending mail from within a .NET application. The classes contained in this namespace work a bit differently from the classes in the Web namespace. Table 1 describes the classes contained in the System.Net.Mail namespace.

Table 1. Important Classes in the System.Net.Mail Namespace

Class Description

Attachment Represents an attachment that is sent with a mail and is used in conjunction with the MailMessage class

MailAddress Represents the address of the sender or recipient (To, CC, and BCC)

MailMessage Represents an e-mail message that can be sent using the SmtpClient class and exposes properties such as From, To, CC, BCC, Attachments, Subject, and Body to formulate the message's contents

SmtpClient Allows applications to send emails using the SMTP

SmtpException Represents the exception that is thrown when the SmtpClient is not able to send the message

Of the classes that Table 1 lists, MailMessage and SmtpClient are the two core classes that you need to work with to send the simplest of mails.

Implementation

The SmtpClient class handles the actual sending of e-mail. For a simple mail, you can directly pass in the To address, from, subject, and body of the mail to one of the SmtpClient's overloaded send methods. However, this approach works only for simple mails that don't need any advanced formatting, which is normally provided by the MailMessage class.

To have complete control over the mail message, you need to create an instance of the MailMessage class and set its properties to appropriate values. For the purposes of this example, create a Visual C# Class Library project named MailServer using Visual Studio 2005. Once the project is created, rename the default class to MailService. To the MailService class, add a method named SendMail and modify its code to look as follows (an example of how to use the MailMessage class to create a mail message and then send it using the SmtpClient object):

public void SendMail(string from, string to,

string subject, string body)

{

string mailServerName = "smtp.test.com";

try

{

//MailMessage represents the e-mail being sent

using (MailMessage message = new MailMessage(from,

to, subject, body))

{

message.IsBodyHtml = true;

SmtpClient mailClient = new SmtpClient();

mailClient.Host = mailServerName;

mailClient.UseDefaultCredentials = true;

mailClient.DeliveryMethod =

SmtpDeliveryMethod.PickupDirectoryFromIis;

//Send delivers the message to the mail server

mailClient.Send(message);

}

}

catch (SmtpException ex)

{

throw new ApplicationException

("SmtpException has oCCured: " + ex.Message);

}

catch (Exception ex)

{

throw ex;

}

}

In the above code, at the time of creating an instance of the MailMessage class, you pass in the From, To, Subject, and body of the message as arguments. Then, you set the IsBodyHtml property to true to indicate the type of mail you want to send. After that, you create an instance of the SmtpClient object and then set its properties, such as Host, UseDefaultCredentials, and DeliveryMethod, to appropriate values. Finally, you send the mail using the Send method, which sends out the mail in a synchronous manner. Note that at the time of sending a mail, if an SMTP exception occurs, it will be handled in the SmtpException catch block. All other exceptions are caught by the generic Exception block. Also note that in the above method, you directly set the To property of the MailMessage object to the supplied value. If you are sending mails to multiple recipients, you need to create that many instances of MailAddress objects and add them to the MailMessage.To property, which represents a collection of MailAddressCollection objects.

URL : http://www.developer.com/net/net/article.php/11087_3511731_1

Abstract Class versus Interface

Abstract Class versus Interface

Introduction

In this article along with the demo project I will discuss Interfaces versus Abstract classes. The concept of Abstract classes and Interfaces is a bit confusing for beginners of Object Oriented programming. Therefore, I am trying to discuss the theoretical aspects of both the concepts and compare their usage. And finally I will demonstrate how to use them with C#.

Background

An Abstract class without any implementation just looks like an Interface; however there are lot of differences than similarities between an Abstract class and an Interface. Let's explain both concepts and compare their similarities and differences.

What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn’t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.

When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.

There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:


Feature

Interface

Abstract class

Multiple inheritance

A class may inherit several interfaces.

A class may inherit only one abstract class.

Default implementation

An interface cannot provide any code, just the signature.

An abstract class can provide complete, default code and/or just the details that have to be overridden.

Access Modfiers

An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public

An abstract class can contain access modifiers for the subs, functions, properties

Core VS Peripheral

Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.

An abstract class defines the core identity of a class and there it is used for objects of the same type.

Homogeneity

If various implementations only share method signatures then it is better to use Interfaces.

If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.

Speed

Requires more time to find the actual method in the corresponding classes.

Fast

Adding functionality (Versioning)

If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.

If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.

Fields and Constants

No fields can be defined in interfaces

An abstract class can have fields and constrants defined


Using the Code

Let me explain the code to make it a bit easier. There is an Employee abstract class and an IEmployee interface. Within the Abstract class and the Interface entity I am commenting on the differences between the artifacts.

I am testing both the Abstract class and the Interface by implementing objects from them. From the Employee abstract class, we have inherited one object: Emp_Fulltime. Similarly from IEmployee we have inherited one object: Emp_Fulltime2.

In the test code under the GUI, I am creating instances of both Emp_Fulltime and Emp_Fulltime2 and then setting their attributes and finally calling the calculateWage method of the objects.

Abstract Class Employee

using System;

namespace AbstractsANDInterfaces

{

///

/// Summary description for Employee.

///

public abstract class Employee

{

//we can have fields and properties

//in the Abstract class

protected String id;

protected String lname;

protected String fname;

//properties

public abstract String ID

{

get;

set;

}

public abstract String FirstName

{

get;

set;

}

public abstract String LastName

{

get;

set;

}

//completed methods

public String Update()

{

return "Employee " + id + " " +

lname + " " + fname +

" updated";

}

//completed methods

public String Add()

{

return "Employee " + id + " " +

lname + " " + fname +

" added";

}

//completed methods

public String Delete()

{

return "Employee " + id + " " +

lname + " " + fname +

" deleted";

}

//completed methods

public String Search()

{

return "Employee " + id + " " +

lname + " " + fname +

" found";

}

//abstract method that is different

//from Fulltime and Contractor

//therefore i keep it uncompleted and

//let each implementation

//complete it the way they calculate the wage.

public abstract String CalculateWage();

}

}

Interface Employee

using System;

namespace AbstractsANDInterfaces

{

///

/// Summary description for IEmployee.

///

public interface IEmployee

{

//cannot have fields. uncommenting

//will raise error!

// protected String id;

// protected String lname;

// protected String fname;

//just signature of the properties

//and methods.

//setting a rule or contract to be

//followed by implementations.

String ID

{

get;

set;

}

String FirstName

{

get;

set;

}

String LastName

{

get;

set;

}

// cannot have implementation

// cannot have modifiers public

// etc all are assumed public

// cannot have virtual

String Update();

String Add();

String Delete();

String Search();

String CalculateWage();

}

}

Inherited Objects

Emp_Fulltime:

using System;

namespace AbstractsANDInterfaces

{

///

/// Summary description for Emp_Fulltime.

///

//Inheriting from the Abstract class

public class Emp_Fulltime : Employee

{

//uses all the properties of the

//Abstract class therefore no

//properties or fields here!

public Emp_Fulltime()

{

}

public override String ID

{

get

{

return id;

}

set

{

id = value;

}

}

public override String FirstName

{

get

{

return fname;

}

set

{

fname = value;

}

}

public override String LastName

{

get

{

return lname;

}

set

{

lname = value;

}

}

//common methods that are

//implemented in the abstract class

public new String Add()

{

return base.Add();

}

//common methods that are implemented

//in the abstract class

public new String Delete()

{

return base.Delete();

}

//common methods that are implemented

//in the abstract class

public new String Search()

{

return base.Search();

}

//common methods that are implemented

//in the abstract class

public new String Update()

{

return base.Update();

}

//abstract method that is different

//from Fulltime and Contractor

//therefore I override it here.

public override String CalculateWage()

{

return "Full time employee " +

base.fname + " is calculated " +

"using the Abstract class...";

}

}

}

Emp_Fulltime2:

using System;

namespace AbstractsANDInterfaces

{

///

/// Summary description for Emp_fulltime2.

///

//Implementing the interface

public class Emp_fulltime2 : IEmployee

{

//All the properties and

//fields are defined here!

protected String id;

protected String lname;

protected String fname;

public Emp_fulltime2()

{

//

// TODO: Add constructor logic here

//

}

public String ID

{

get

{

return id;

}

set

{

id = value;

}

}

public String FirstName

{

get

{

return fname;

}

set

{

fname = value;

}

}

public String LastName

{

get

{

return lname;

}

set

{

lname = value;

}

}

//all the manipulations including Add,Delete,

//Search, Update, Calculate are done

//within the object as there are not

//implementation in the Interface entity.

public String Add()

{

return "Fulltime Employee " +

fname + " added.";

}

public String Delete()

{

return "Fulltime Employee " +

fname + " deleted.";

}

public String Search()

{

return "Fulltime Employee " +

fname + " searched.";

}

public String Update()

{

return "Fulltime Employee " +

fname + " updated.";

}

//if you change to Calculatewage().

//Just small 'w' it will raise

//error as in interface

//it is CalculateWage() with capital 'W'.

public String CalculateWage()

{

return "Full time employee " +

fname + " caluculated using " +

"Interface.";

}

}

}

Code for Testing

//This is the sub that tests both

//implementations using Interface and Abstract

private void InterfaceExample_Click(object sender,

System.EventArgs e)

{

try

{

IEmployee emp;

Emp_fulltime2 emp1 = new Emp_fulltime2();

emp = emp1;

emp.ID = "2234";

emp.FirstName= "Rahman" ;

emp.LastName = "Mahmoodi" ;

//call add method od the object

MessageBox.Show(emp.Add().ToString());

//call the CalculateWage method

MessageBox.Show(emp.CalculateWage().ToString());

}

catch(Exception ex)

{

MessageBox.Show(ex.Message);

}

}

private void cmdAbstractExample_Click(object sender,

System.EventArgs e)

{

Employee emp;

emp = new Emp_Fulltime();

emp.ID = "2244";

emp.FirstName= "Maria" ;

emp.LastName = "Robinlius" ;

MessageBox.Show(emp.Add().ToString());

//call the CalculateWage method

MessageBox.Show(emp.CalculateWage().ToString());

}

Conclusion

In the above examples, I have explained the differences between an abstract class and an interface. I have also implemented a demo project which uses both abstract class and interface and shows the differences in their implementation.