Click here to Skip to main content
15,886,518 members
Articles / Mobile Apps
Article

Simple Windows Service Sample

Rate me:
Please Sign up or sign in to vote.
4.85/5 (407 votes)
14 Jul 20037 min read 3M   69.3K   836   307
A simple application to show how to create a Windows service.

Introduction

As a matter of fact Microsoft Windows services, formerly known as NT services enable you to create long-running executable applications that run in its own Windows session, which then has the ability to start automatically when the computer boots and also can be manually paused, stopped or even restarted.

This makes services ideal for use on a server or whenever you need long-running functionality that does not interfere with other users who are working on the same computer. You can also run services in the security context of a specific user account that is different from the logged-on user or the default computer account.

Windows services don’t have any interface to the user, so it can not be debugged like any regular application, but it’s debugged as a process. .NET has a very nice tool that enables processes debugging while it’s in the run status, by easily pressing Ctrl + Alt + P shortcut.

Background

I’ve searched well so many sites about a code that I can with the help of it, build a simple Windows service, but I found a lot of code on how to manage the current Windows services of the system and that’s through the ServiceController class.

After searching the MSDN, I’ve found some nice code that helped me to create this simple Windows service. Hope it can help as a basic architecture for and usage of such a Windows service.

Using the code

At first you should simply open VS.NET and then at the File menu click on New, Project. From the New Project Dialog Box, choose the Windows service template project and name it MyNewService like shown below:

Winows Service New Project

The project template automatically adds a component class that is called Service1 by default and inherits from System.ServiceProcess.ServiceBase.

Click the designer. Then, in the Properties window, set the ServiceName property for Service1 to MyNewService.

Set the Name property to MyNewService. Set the AutoLog property to true.

In the code editor, edit the Main method to create an instance of MyNewService. When you renamed the service in step 3, the class name was not modified in the Main method. To access the Main method in VC#, expand the Component Designer generated code region.

C#
static void Main()
{ 
    System.ServiceProcess.ServiceBase[] ServicesToRun; 
    //Change the following line to match. 
    ServicesToRun = new 
        System.ServiceProcess.ServiceBase[] { new MyNewService() }; 
    System.ServiceProcess.ServiceBase.Run(ServicesToRun);  
}

In the next section, you will add a custom event log to your Windows service. Event logs are not associated in any way with Windows services. Here the EventLog component is used as an example of the type of components you could add to a Windows service.

To add custom event log functionality to your service:

  1. In the Solution Explorer, right-click Service1.vb or Service1.cs and select View Designer.
  2. From the Components tab of the Toolbox, drag an EventLog component to the designer.
  3. In the Solution Explorer, right-click Service1.vb or Service1.cs and select View Code.
  4. Edit the constructor to define a custom event log.

To access the constructor in Visual C#, expand the Component Designer generated code region.

C#
public MyNewService()
{
 
    InitializeComponent()
    if(!System.Diagnostics.EventLog.SourceExists("DoDyLogSourse"))
    System.Diagnostics.EventLog.CreateEventSource("DoDyLogSourse",
                                                          "DoDyLog");

    eventLog1.Source = "DoDyLogSourse";
    // the event log source by which 

    //the application is registered on the computer

    eventLog1.Log = "DoDyLog";
}

To define what happens when the service starts, in the code editor, locate the OnStart method that was automatically overridden when you created the project, and write code to determine what occurs when the service begins running:

C#
protected override void OnStart(string[] args)
{ 
    eventLog1.WriteEntry("my service started"); 
}

The OnStart method must return to the operating system once the service's operation has begun. It must not loop forever or block. To set up a simple polling mechanism, you can use the System.Timers.Timer component. In the OnStart method, you would set parameters on the component, and then you would set the Timer.Enabled property to true. The timer would then raise events in your code periodically, at which time your service could do its monitoring.

To define what happens when the service is stopped, in the code editor, locate the OnStop procedure that was automatically overridden when you created the project, and write code to determine what occurs when the service is stopped:

C#
protected override void OnStop()
{ 
    eventLog1.WriteEntry("my service stoped");
}

You can also override the OnPause, OnContinue, and OnShutdown methods to define further processing for your component. For the method you want to handle, override the appropriate method and define what you want to occur. The following code shows what it looks like if you override the OnContinue method:

C#
protected override void OnContinue()
{
    eventLog1.WriteEntry("my service is continuing in working");
}

Some custom actions need to occur when installing a Windows service, which can be done by the Installer class. Visual Studio can create these installers specifically for a Windows service and add them to your project. To create the installers for your service.

  1. Return to design view for Service1.
  2. Click the background of the designer to select the service itself, rather than any of its contents.
  3. In the Properties window, click the Add Installer link in the gray area beneath the list of properties. By default, a component class containing two installers is added to your project. The component is named ProjectInstaller, and the installers it contains are the installer for your service and the installer for the service's associated process.
  4. Access design view for ProjectInstaller, and click ServiceInstaller1.
  5. In the Properties window, set the ServiceName property to MyNewService.
  6. Set the StartType property to Automatic.

Tip

To avoid being asked about the system username and password you must change the Account for the serviceProcessInstaller to LocalSystem. This is done by opening the ProjectInstaller design and then selecting the serviceProcessInstaller, press F4 and then change the Account property to LocalSystem. Or you can manually do that by creating a class that inherits from System.Configuration.Install.Installer like this:

C#
[RunInstaller(true)]

public class ProjectInstaller : System.Configuration.Install.Installer 
private System.ServiceProcess.ServiceProcessInstaller 
                                  serviceProcessInstaller1;
private System.ServiceProcess.ServiceInstaller serviceInstaller1; 
/// <summary> 
/// Required designer variable. 
/// </summary> private System.ComponentModel.Container components = null;

public ProjectInstaller()
   // This call is required by the Designer.
   InitializeComponent();

   // TODO: Add any initialization after the InitComponent call 
} 
private void InitializeComponent() 
{ 
   this.serviceProcessInstaller1 = 
     new System.ServiceProcess.ServiceProcessInstaller(); 
   this.serviceInstaller1 = 
     new System.ServiceProcess.ServiceInstaller(); 
   // serviceProcessInstaller1 
   // 
   this.serviceProcessInstaller1.Account = 
     System.ServiceProcess.ServiceAccount.LocalSystem; 
   this.serviceProcessInstaller1.Password = null;
   this.serviceProcessInstaller1.Username = null; 
   // 
   // serviceInstaller1 
   // 
   this.serviceInstaller1.ServiceName = "MyNewService"; 
   this.serviceInstaller1.StartType = 
     System.ServiceProcess.ServiceStartMode.Automatic;

   // 
   // ProjectInstaller 
   // 
   this.Installers.AddRange
     (new System.Configuration.Install.Installer[] 
   { 
       this.serviceInstaller1, 
       this.serviceInstaller1});
   }
}

To build your service project

  1. In Solution Explorer, right-click your project and select Properties from the shortcut menu. The project's Property Pages dialog box appears.
  2. In the left pane, select the General tab in the Common Properties folder.
  3. From the Startup object list, choose MyNewService. Click OK.
  4. Press Ctrl+Shift+B to build the project. 

Service Project Property Page

Now that the project is built, it can be deployed. A setup project will install the compiled project files and run the installers needed to run the Windows service. To create a complete setup project, you will need to add the project output, MyNewService.exe, to the setup project and then add a custom action to have MyNewService.exe installed.

To create a setup project for your service

  1. On the File menu, point to Add Project, and then choose New Project.
  2. In the Project Types pane, select the Setup and Deployment Projects folder.
  3. In the Templates pane, select Setup Project. Name the project MyServiceSetup.

A setup project is added to the solution. Next you will add the output from the Windows service project, MyNewService.exe, to the setup.

Service Setup Project

To add MyNewService.exe to the setup project

  1. In Solution Explorer, right-click MyServiceSetup, point to Add, then choose Project Output. The Add Project Output Group dialog box appears.
  2. MyNewService is selected in the Project box.
  3. From the list box, select Primary Output, and click OK.

    A project item for the primary output of MyNewService is added to the setup project. Now add a custom action to install the MyNewService.exe file.

To add a custom action to the setup project

  1. In Solution Explorer, right-click the setup project, point to View, then choose Custom Actions. The Custom Actions editor appears.
  2. In the Custom Actions editor, right-click the Custom Actions node and choose Add Custom Action. The Select Item in Project dialog box appears.
  3. Double-click the application folder in the list box to open it, select primary output from MyNewService (Active), and click OK. The primary output is added to all four nodes of the custom actions — Install, Commit, Rollback, and Uninstall.
  4. Build the setup project.

To install the Windows Service

Browse to the directory where the setup project was saved, and run the .msi file to install MyNewService.exe.

Service Setup

To start and stop your service

  1. Open the Services Control Manager by doing one of the following:
    • In Windows 2000 Professional, right-click My Computer on the desktop, then click Manage. In the Computer Management console, expand the Services and Applications node.

      - Or -

    • In Windows 2000 Server, click Start, point to Programs, click Administrative Tools, and then click Services.

      Note: In Windows NT version 4.0, you can open this dialog box from Control Panel.

  2. You should now see MyNewService listed in the Services section of the window.
  3. Select your service in the list, right-click it, and then click Start.

Right-click the service, and then click Stop.

Admin tools Services

To verify the event log output of your service

  1. Open Server Explorer and access the Event Logs node. For more information, see Working with Event Logs in Server Explorer.

    Note: The Servers node of Server Explorer is not available in the Standard Edition of Visual Basic and Visual C# .NET.

    Sample screenshot

To uninstall your service

  • On the Start menu, open Control Panel and click Add/Remove Programs, and then locate your service and click Uninstall.
  • You can also uninstall the program by right-clicking the program icon for the .msi file and selecting Uninstall.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Saudi Arabia Saudi Arabia
i've been with .net for about 5 years since the beta 1.0 ver. along with ASP.net and windows services..
am experienced in Java, C, C++, Prolog, Assembly, ASP, VB, VB.net, C# and ASP.net

am very fond of Web Development and Graphics Libraries Programming like Open GL,CSGL and SDGL

worked in Microsoft Egypt Co., Delta Software and now am working in Al-Alamiah Sakhr Co., Riyadh, saudi arabia.

+966-508969725

Comments and Discussions

 
QuestionNo way to build a setup project Pin
Kansai Robot8-Feb-18 22:35
Kansai Robot8-Feb-18 22:35 
GeneralThanks for sharing useful article Pin
Mark devid21-Sep-16 4:00
Mark devid21-Sep-16 4:00 
QuestionRuntime error on VS2013 Community Pin
SBGTrading29-May-15 15:56
SBGTrading29-May-15 15:56 
Questionhow can i update my windows service? Pin
haifa20105-May-15 0:46
haifa20105-May-15 0:46 
AnswerRe: how can i update my windows service? Pin
Devil Faizan4-Aug-15 20:29
professionalDevil Faizan4-Aug-15 20:29 
QuestionSame service in java Pin
Member 1088501327-Jul-14 6:11
Member 1088501327-Jul-14 6:11 
QuestionNice head start for new bees to windows service Pin
Member 972113312-Jun-14 22:42
Member 972113312-Jun-14 22:42 
QuestionThe timer1 dont work ? Pin
atisah19-May-14 22:04
atisah19-May-14 22:04 
AnswerRe: The timer1 dont work ? Pin
gue.shindu14-Dec-14 21:05
gue.shindu14-Dec-14 21:05 
QuestionAccess to apps through windows environment variables Pin
Member 1081854414-May-14 12:57
Member 1081854414-May-14 12:57 
AnswerRe: Access to apps through windows environment variables Pin
Member 1081854414-May-14 13:11
Member 1081854414-May-14 13:11 
Questionnic Pin
MojtabaKojouri5-Apr-14 20:39
MojtabaKojouri5-Apr-14 20:39 
QuestionWindows Service Vs WCF Pin
vamforvamsi24-Sep-13 23:28
vamforvamsi24-Sep-13 23:28 
GeneralMy vote of 5 Pin
berezov6-Jul-13 10:44
berezov6-Jul-13 10:44 
GeneralMy vote of 5 Pin
Altaf N Patel27-Jun-13 3:27
Altaf N Patel27-Jun-13 3:27 
QuestionThank You! Pin
Member 98041045-Jun-13 10:04
Member 98041045-Jun-13 10:04 
GeneralMy vote of 4 Pin
oopsMike4-Jun-13 3:17
oopsMike4-Jun-13 3:17 
GeneralMy vote of 5 Pin
dippaul10-Mar-13 23:07
dippaul10-Mar-13 23:07 
GeneralMy vote of 5 Pin
Atiq Rehman6-Mar-13 23:23
Atiq Rehman6-Mar-13 23:23 
GeneralMy vote of 3 Pin
Ricco Eschelund16-Nov-12 0:42
Ricco Eschelund16-Nov-12 0:42 
GeneralMy vote of 5 Pin
Praneet Rane7-Oct-12 6:53
Praneet Rane7-Oct-12 6:53 
QuestionNice Article Pin
naraayanan2-Oct-12 23:00
naraayanan2-Oct-12 23:00 
QuestionProblem while Installing the window service on the internal server using the setup Pin
E-ChaitanyaMalli30-Sep-12 19:39
professionalE-ChaitanyaMalli30-Sep-12 19:39 
Hi,
Using the above article i succeeded in creating a Windows Service,now i am facing a problem in executing the setup file in the server.
I copied the setup file to the server location and tried to execute it.I am getting a message like
'Error:1001 Source service already exists on local machine'. By seeing this i looked up in services as well as Add/Remove programms too but i couldn't see the service name...

What could be the reason.
The below is code implemented in the service
C#
#region Page Header
/* -----------------------------------------------------------------------------------------------------------
   Name         : MailNotificationServices.cs
   Purpose      : Service to trigger Mails
   Created By   : Chaitanya.E
   Created Date : 14Sep2012      
 
   Modification Log Begins Here 
   -----------------------------------------------------------------------------------------------------------
    Sl          Date            Person              Modification Details  
   -----------------------------------------------------------------------------------------------------------
   ----------------------------------------------------------------------------------------------------------- */
#endregion


#region References

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Timers;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Data.Sql;
using System.Configuration;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Net.Mail;
using System.IO;
using System.Net.Mime;
#endregion

#region Namespace

namespace MailNotificationService
{
    #region Class Declaration
    partial class MailNotificationServices : ServiceBase
    {
        #region Variable Declaration

        private Timer _timer = null;
        private IContainer objcomponents = null;

        private SqlConnection connection = null;
        private SqlCommand command = null;
        private string strConnectionString = null;
        private string strCommandText = string.Empty;
        private SqlDataAdapter adapter = null;
        private DataSet dsDataset = new DataSet();

        private string strUsercode;
        private string strUserMailID;
        private string strUserName;
        private string strSubmitterMsgHeader;
        private string strDefectMessageHeading;
        private string strSubmitterFinalMsg;
        private string strOwnerMsgHeader;
        private string strOwnerFinalMsg;
        private string strAssignedToMsgHeader;
        private string strAssignedToFinalMsg;
        private string strFromMailID;
        private int intProjectId;
        private int intProjectIdDefects;
        private string strProjectName;
        private string strProjectCode;
        private string strOtherMailIDs;
        private string strMailToSubmitter;
        private string strMailToOwner;
        private string strMailToAssignee;
        private string strDuration;
        private int intEntitytypeID;
        private string strCurrentDayOfTheWeek = Convert.ToString(DateTime.Now.DayOfWeek.ToString());
        private string strCurrentDateOfTheMonth = Convert.ToString(DateTime.Now.Day.ToString());
        DataSet objDatasetSysPara;
        Boolean boolSendMailSubmitter = false;
        Boolean boolSendMailOwner = false;
        Boolean boolSendMailAssignee = false;
        int intSubmitterCount = 0;
        int intOwnerCount = 0;
        int intAssigneeCount = 0;
        private bool boolSendMail;

        #endregion

        #region Constructor
        public MailNotificationServices()
        {
            InitializeComponent();
            if (!System.Diagnostics.EventLog.SourceExists("EmailSource"))
            {
                System.Diagnostics.EventLog.CreateEventSource("EmailSource", "MailNotificationServices");
            }
            MailLog.Source = "EmailSource";
            MailLog.Log = "EmailLog";
            this._timer = new Timer();
            ((ISupportInitialize)_timer).BeginInit();
            this._timer.Interval = 60000;
            this._timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
            this.ServiceName = "MailNotificationServices";
            ((ISupportInitialize)_timer).EndInit();
        }

        void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            try
            {
                MailLog.WriteEntry("Service Running");
                string currenttime = DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString();
                if (currenttime.ToUpper().Equals("11:15"))
                {
                    MailLog.WriteEntry("Started Fetching Data");
                    connection = new SqlConnection();
                    command = new SqlCommand();
                    MailLog.WriteEntry("Started to create connection");
                    GetMailData();
                }
            }
            catch (Exception ec) { }
        }

        private SqlConnection GetConnection()
        {
            strConnectionString = "Data Source=cosmonet2k3;Initial Catalog=TopqmGMR;Integrated Security=True;";
            if (connection != null && connection.State == ConnectionState.Open)
            {
                return connection;
            }
            else
            {
                connection = new SqlConnection(strConnectionString);
                connection.Open();
                return connection;
            }
        }
        private void GetMailData()
        {
            //To Fetch the MailNotification records From Notification Table
            if (command != null)
            {
                try
                {
                    strCommandText = "spFetchNotificationInfo";
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandText = strCommandText;
                    command.Connection = GetConnection();
                    MailLog.WriteEntry("Connection object created");
                    adapter = new SqlDataAdapter(command);
                    adapter.Fill(dsDataset);
                    if (dsDataset != null && dsDataset.Tables.Count > 0 && dsDataset.Tables.Count > 2)
                    {
                        for (int intIndex = 0; intIndex <= dsDataset.Tables[1].Rows.Count - 1; intIndex++)
                        {
                            intEntitytypeID = Convert.ToInt32(dsDataset.Tables[1].Rows[intIndex].ItemArray[1].ToString());
                            strDuration = dsDataset.Tables[1].Rows[intIndex].ItemArray[7].ToString();
                            intProjectId = Convert.ToInt32(dsDataset.Tables[1].Rows[0].ItemArray[0].ToString());
                            strFromMailID = dsDataset.Tables[1].Rows[intIndex].ItemArray[2].ToString();
                            strOtherMailIDs = dsDataset.Tables[1].Rows[intIndex].ItemArray[3].ToString();
                            strProjectCode = dsDataset.Tables[1].Rows[intIndex].ItemArray[8].ToString();
                            strProjectName = dsDataset.Tables[1].Rows[intIndex].ItemArray[9].ToString();
                            strMailToSubmitter = dsDataset.Tables[1].Rows[intIndex].ItemArray[4].ToString();
                            strMailToOwner = dsDataset.Tables[1].Rows[intIndex].ItemArray[5].ToString();
                            strMailToAssignee = dsDataset.Tables[1].Rows[intIndex].ItemArray[6].ToString();

                            int intTableCount;
                            if (strMailToSubmitter.Trim() == "Y" || strMailToOwner.Trim() == "Y" || strMailToAssignee.Trim() == "Y" || strOtherMailIDs.Trim() != "")
                            {
                                intTableCount = intIndex + 2;
                                if (strDuration.Length > 10)
                                {
                                    string strDurationMonthDate;
                                    strDurationMonthDate = strDuration.Substring(10);
                                    if (strDurationMonthDate.Trim() == strCurrentDateOfTheMonth.Trim())
                                    { SendDefectMail(intTableCount); MailLog.WriteEntry("Monthly Mails sent successfully"); }
                                }
                                else if (strDuration.Length > 5)
                                {
                                    if (strDuration.Trim() != "never")
                                    {
                                        string strDurationDayWeek;
                                        strDurationDayWeek = strDuration.Substring(5);
                                        switch (strDurationDayWeek.Trim())
                                        {
                                            case "1":
                                                strDurationDayWeek = "Sunday";
                                                break;
                                            case "2":
                                                strDurationDayWeek = "Monday";
                                                break;
                                            case "3":
                                                strDurationDayWeek = "Tuesday";
                                                break;
                                            case "4":
                                                strDurationDayWeek = "Wednesday";
                                                break;
                                            case "5":
                                                strDurationDayWeek = "Thursday";
                                                break;
                                            case "6":
                                                strDurationDayWeek = "Friday";
                                                break;
                                            case "7":
                                                strDurationDayWeek = "Saturday";
                                                break;
                                            default:
                                                break;
                                        }
                                        if (strDurationDayWeek.Trim() == strCurrentDayOfTheWeek.Trim())
                                        { SendDefectMail(intTableCount); MailLog.WriteEntry("Weekly Mails sent successfully"); }
                                    }
                                }
                                else if (strDuration.Trim() == "day")
                                {
                                    SendDefectMail(intTableCount); MailLog.WriteEntry("Daily Mails sent successfully");
                                }
                            }
                        }
                    }
                    else
                    {
                        MailLog.WriteEntry("No Records Found");
                        this.OnStop();
                    }
                }
                catch (Exception ec)
                {
                    MailLog.WriteEntry(ec.Message);
                }
            }
        }


        #endregion

        #region Service Start Method
        protected override void OnStart(string[] args)
        {
            // TODO: Add code here to start your service.
            this._timer.Enabled = true;
            MailLog.WriteEntry("Service Started");
        }
        #endregion

        #region Service Stop
        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
            this._timer.Enabled = false;
            MailLog.WriteEntry("Service Stopped");
        }
        #endregion

        #region Defined Methods
        public void SendDefectMail(int intTableIndex)
        {
            objDatasetSysPara = FetchMailParameter();

            if (dsDataset.Tables[intTableIndex].Rows.Count > 0)
            {
                intProjectIdDefects = Convert.ToInt32(dsDataset.Tables[intTableIndex].Rows[0].ItemArray[0].ToString());

                if (intProjectId == intProjectIdDefects)
                {
                    strUsercode = "";
                    strUserMailID = "";
                    strUserName = "";
                    for (int intlIndex = 0; intlIndex <= dsDataset.Tables[0].Rows.Count - 1; intlIndex++)
                    {
                        //Step1:  Collect the mailid
                        strUsercode = dsDataset.Tables[0].Rows[intlIndex].ItemArray[0].ToString();
                        strUserMailID = dsDataset.Tables[0].Rows[intlIndex].ItemArray[1].ToString();
                        strUserName = dsDataset.Tables[0].Rows[intlIndex].ItemArray[2].ToString();

                        //Step2:  Check the mailid, if not exist then
                        if (strUserMailID.Trim() != "")
                        {
                            boolSendMailSubmitter = false;
                            boolSendMailOwner = false;
                            boolSendMailAssignee = false;
                            boolSendMail = false;
                            strSubmitterFinalMsg = "";
                            intSubmitterCount = 0;
                            strOwnerFinalMsg = "";
                            intOwnerCount = 0;
                            strAssignedToFinalMsg = "";
                            intAssigneeCount = 0;
                            strAssignedToMsgHeader = "";
                            strOwnerMsgHeader = "";
                            strSubmitterMsgHeader = "";

                            for (int intRowIndexUser = 0; intRowIndexUser <= dsDataset.Tables[intTableIndex].Rows.Count - 1; intRowIndexUser++)
                            {
                                if (strUsercode.Trim() == dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[9].ToString().Trim())
                                {
                                    intSubmitterCount++;

                                    strSubmitterFinalMsg = strSubmitterFinalMsg + Convert.ToString(intSubmitterCount) +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[1].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[2].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[4].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[8].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[6].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[7].ToString() +
                                    "|";
                                }
                                if (strUsercode.Trim() == dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[10].ToString().Trim())
                                {
                                    intOwnerCount++;
                                    strOwnerFinalMsg = strOwnerFinalMsg + Convert.ToString(intOwnerCount) +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[1].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[2].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[4].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[8].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[6].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[7].ToString() +
                                    "|";
                                }

                                if (strUsercode.Trim() == dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[11].ToString().Trim())
                                {
                                    intAssigneeCount++;

                                    strAssignedToFinalMsg = strAssignedToFinalMsg + Convert.ToString(intAssigneeCount) +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[1].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[2].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[4].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[8].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[6].ToString() +
                                    ", " + dsDataset.Tables[intTableIndex].Rows[intRowIndexUser].ItemArray[7].ToString() +
                                    "|";
                                }

                                if (intSubmitterCount > 0)
                                {
                                    boolSendMailSubmitter = true;
                                    if (intEntitytypeID == 22)
                                    {
                                        strSubmitterMsgHeader = "Number of Review defects Submitted by " + strUserName.Trim() + ": " + Convert.ToString(intSubmitterCount);
                                    }
                                    else if (intEntitytypeID == 24)
                                    {
                                        strSubmitterMsgHeader = "Number of Test defects Submitted by " + strUserName.Trim() + ": " + Convert.ToString(intSubmitterCount);
                                    }
                                }

                                if (intOwnerCount > 0)
                                {
                                    boolSendMailOwner = true;
                                    if (intEntitytypeID == 22)
                                    {
                                        strOwnerMsgHeader = "Number of Review Defects Owned by " + strUserName.Trim() + ": " + Convert.ToString(intOwnerCount);
                                    }
                                    else if (intEntitytypeID == 24)
                                    {
                                        strOwnerMsgHeader = "Number of Tests Defects Owned by " + strUserName.Trim() + ": " + Convert.ToString(intOwnerCount);
                                    }
                                }
                                if (intAssigneeCount > 0)
                                {
                                    boolSendMailAssignee = true;
                                    if (intEntitytypeID == 22)
                                    {
                                        strAssignedToMsgHeader = "Number of Review Defects Assigned to " + strUserName.Trim() + ": " + Convert.ToString(intAssigneeCount);
                                    }
                                    else if (intEntitytypeID == 24)
                                    {
                                        strAssignedToMsgHeader = "Number of Tests Defects Assigned to " + strUserName.Trim() + ": " + Convert.ToString(intAssigneeCount);
                                    }
                                }
                            }
                        }
                        if ((boolSendMailSubmitter == true) || (boolSendMailOwner == true) || (boolSendMailAssignee == true))
                        {
                            boolSendMail = true;
                        }

                        if (boolSendMail == true)
                        {
                            if (intEntitytypeID == 22)
                            {
                                strDefectMessageHeading = "SlNo, ReviewName, DefectNo., DefectTitle, Status  , Priority  , Severity  ";
                                PDFDocumentForAttachment();
                            }
                            else if (intEntitytypeID == 24)
                            {
                                strDefectMessageHeading = "SlNo, TestsName, TestDefectNo., TestDefectTitle, Status  , Priority  , Severity  ";
                                PDFDocumentForAttachment();
                            }

                        }
                    }
                }
            }
        }

        private DataSet FetchMailParameter()
        {
            command = new SqlCommand();
            command.CommandText = "spFetchMailParameters";
            command.CommandType = CommandType.StoredProcedure;
            command.Connection = GetConnection();
            adapter = new SqlDataAdapter(command);
            DataSet ds = new DataSet();
            adapter.Fill(ds);
            return ds;
        }

        public void PDFDocumentForAttachment()
        {
            string strSUBMMsgBodyPart;
            string strOWNMsgBodyPart;
            string strASSGMsgBodyPart;
            string strReportTitle;
            string strBodyMain;
            string strBodyEnd;
            string strEntity;
            string strToMailID;
            strReportTitle = "";
            strEntity = "";
            strBodyEnd = "";
            MailMessage mm = new MailMessage();
            strToMailID = "Y";
            if (strMailToSubmitter.Trim() == "N" && strMailToOwner.Trim() == "N" && strMailToAssignee.Trim() == "N")
            {
                if (strOtherMailIDs.Trim() != "")
                {
                    strToMailID = "N";
                    string[] strArrCCAddresses = strOtherMailIDs.Trim().Split(new Char[] { ';' });
                    for (int intCount = 0; intCount < strArrCCAddresses.Length; intCount++)
                    {
                        if (strArrCCAddresses[intCount].Trim() != "")
                            mm.To.Add((new MailAddress(strArrCCAddresses[intCount].Trim())));
                    }
                }
            }
            else
            {
                mm.To.Add(strUserMailID.Trim());
            }

            if (intEntitytypeID == 22)
            {
                strReportTitle = "RADAR - Defects Report";
                strEntity = "Review";
                mm.Subject = "RADAR - Defects - " + strUserName.Trim();
            }
            else if (intEntitytypeID == 24)
            {
                strReportTitle = "RADAR - TestDefects Report";
                strEntity = "Tests";
                mm.Subject = "RADAR - TestDefects - " + strUserName.Trim();
            }

            strBodyMain = "                " +
                strEntity.Trim().ToUpper() + " DEFECT SUMMARY" + "<br><br> Project: " + strProjectCode.Trim()
            + " - " + strProjectName.Trim() + "<br> User: " + strUsercode.Trim() + " - " + strUserName.Trim();


            if (strOtherMailIDs.Trim() != "" && strToMailID.Trim() == "Y")
            {
                string[] strArrCCAddresses = strOtherMailIDs.Trim().Split(new Char[] { ';' });
                for (int intCount = 0; intCount < strArrCCAddresses.Length; intCount++)
                {
                    if (strArrCCAddresses[intCount].Trim() != "")
                        mm.CC.Add(new MailAddress(strArrCCAddresses[intCount].Trim()));
                }
            }
            mm.From = new MailAddress(strFromMailID.Trim());
            mm.IsBodyHtml = true;
            //Creates the PDF report with A4 size and specified margins
            Document pdfReport = new Document(PageSize.A4, 25, 25, 40, 25);
            MemoryStream msReport = new MemoryStream();

            strSUBMMsgBodyPart = "";
            strOWNMsgBodyPart = "";
            strASSGMsgBodyPart = "";
            try
            {
                // step 2: we set the ContentType and create an instance of the Writer
                PdfWriter writer = PdfWriter.GetInstance(pdfReport, msReport);
                writer.CloseStream = false;

                //Register the Verdana Fonts

                FontFactory.RegisterVerdana();

                // Sets the Header with logo and Date

                iTextSharp.text.Image imgLogo = iTextSharp.text.Image.GetInstance(AppDomain.CurrentDomain.BaseDirectory + "Images//Others//cosmologo.gif");
                imgLogo.ScalePercent(50);
                Chunk cLogo = new Chunk(imgLogo, 0, 0);
                Paragraph phHeaderLogo = new Paragraph(cLogo);


                PdfPTable ptHeaderDate = new PdfPTable(1);
                ptHeaderDate.SetWidths(new float[] { 100 });
                ptHeaderDate.WidthPercentage = 100;
                ptHeaderDate.DefaultCell.BorderWidth = 0;
                ptHeaderDate.HorizontalAlignment = Element.ALIGN_RIGHT;
                ptHeaderDate.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
                ptHeaderDate.DefaultCell.VerticalAlignment = Element.ALIGN_BOTTOM;
                ptHeaderDate.AddCell(new Phrase("Date|Time: " + DateTime.Now.ToLongDateString() + "|" + DateTime.Now.ToLongTimeString(), FontFactory.GetFont("Verdana", BaseFont.WINANSI, 8, Font.UNDERLINE)));

                PdfPTable ptHeader = new PdfPTable(2);
                ptHeader.SetWidths(new float[] { 50, 50 });
                ptHeader.WidthPercentage = 100;
                ptHeader.DefaultCell.BorderWidth = 0;
                ptHeader.AddCell(phHeaderLogo);
                ptHeader.AddCell(ptHeaderDate);

                Paragraph phHeader = new Paragraph();
                phHeader.Add(ptHeader);

                HeaderFooter header = new HeaderFooter(phHeader, false);
                header.Border = 0;
                header.BorderWidthBottom = .1f;
                pdfReport.Header = header;

                // Sets the Footer with Page No

                HeaderFooter footer = new HeaderFooter(new Phrase("Page ", FontFactory.GetFont("Verdana", BaseFont.WINANSI, 8)), true);
                footer.Border = 0;
                footer.BorderWidthTop = .1f;
                footer.Alignment = Element.ALIGN_CENTER;
                pdfReport.Footer = footer;

                // Sets the Metadata of Report 

                pdfReport.AddTitle("DEFECTS");
                pdfReport.AddSubject("Report Created by RADAR");
                pdfReport.AddCreationDate();
                pdfReport.AddProducer();

                // Opens the Document 

                pdfReport.Open();

                // Insert the Title


                Paragraph phReportTitle = new Paragraph(strReportTitle, FontFactory.GetFont("Verdana", 8.5f, Font.BOLD, new Color(0, 0, 96)));
                phReportTitle.Alignment = Element.ALIGN_CENTER;
                pdfReport.Add(phReportTitle);

                Paragraph phProjectandUserName = new Paragraph("Project: " + strProjectCode.Trim() + " - " + strProjectName.Trim(), FontFactory.GetFont("Verdana", 8.5f, Font.BOLD, new Color(0, 0, 96)));
                phProjectandUserName.Alignment = Element.ALIGN_LEFT;
                pdfReport.Add(phProjectandUserName);

                Paragraph phUserName = new Paragraph("User: " + strUsercode.Trim() + " - " + strUserName.Trim(), FontFactory.GetFont("Verdana", 8.5f, Font.BOLD, new Color(0, 0, 96)));
                phUserName.Alignment = Element.ALIGN_LEFT;
                pdfReport.Add(phUserName);


                // Creates the Tables for SubmittedBy 

                PdfPTable ptSubmitterHeaderData = new PdfPTable(1);
                ptSubmitterHeaderData.SpacingBefore = 8;
                ptSubmitterHeaderData.DefaultCell.Padding = 1;
                float[] ptheaderwidths = new float[1]; // percentage       
                ptheaderwidths[0] = 20;
                ptSubmitterHeaderData.SetWidths(ptheaderwidths);
                ptSubmitterHeaderData.WidthPercentage = 100;
                ptSubmitterHeaderData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                ptSubmitterHeaderData.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                PdfPTable ptSubmitterData = new PdfPTable(7);
                ptSubmitterData.SpacingBefore = 8;
                ptSubmitterData.DefaultCell.Padding = 1;
                float[] headerwidths = new float[7]; // percentage
                for (int intColIndex = 0; intColIndex < 7; intColIndex++)
                {
                    headerwidths[intColIndex] = 20;
                }
                ptSubmitterData.SetWidths(headerwidths);
                ptSubmitterData.WidthPercentage = 100;
                ptSubmitterData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                ptSubmitterData.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;

                // Creates the Tables for OwnedBy

                PdfPTable ptOwnerHeaderData = new PdfPTable(1);
                ptOwnerHeaderData.SpacingBefore = 8;
                ptOwnerHeaderData.DefaultCell.Padding = 1;
                float[] ptOwnheaderwidths = new float[1]; // percentage       
                ptOwnheaderwidths[0] = 20;
                ptOwnerHeaderData.SetWidths(ptOwnheaderwidths);
                ptOwnerHeaderData.WidthPercentage = 100;
                ptOwnerHeaderData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                ptOwnerHeaderData.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                PdfPTable ptOwnerData = new PdfPTable(7);
                ptOwnerData.SpacingBefore = 8;
                ptOwnerData.DefaultCell.Padding = 1;
                float[] Ownheaderwidths = new float[7]; // percentage
                for (int intColIndex = 0; intColIndex < 7; intColIndex++)
                {
                    Ownheaderwidths[intColIndex] = 20;
                }
                ptOwnerData.SetWidths(Ownheaderwidths);
                ptOwnerData.WidthPercentage = 100;
                ptOwnerData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                ptOwnerData.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;

                // Creates the Tables for AssignedTo

                PdfPTable ptAssignedToHeaderData = new PdfPTable(1);
                ptAssignedToHeaderData.SpacingBefore = 8;
                ptAssignedToHeaderData.DefaultCell.Padding = 1;
                float[] ptAssignedToheaderwidths = new float[1]; // percentage       
                ptAssignedToheaderwidths[0] = 20;
                ptAssignedToHeaderData.SetWidths(ptAssignedToheaderwidths);
                ptAssignedToHeaderData.WidthPercentage = 100;
                ptAssignedToHeaderData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                ptAssignedToHeaderData.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                PdfPTable ptAssignedToData = new PdfPTable(7);
                ptAssignedToData.SpacingBefore = 8;
                ptAssignedToData.DefaultCell.Padding = 1;
                float[] AssignedToheaderwidths = new float[7]; // percentage
                for (int intColIndex = 0; intColIndex < 7; intColIndex++)
                {
                    AssignedToheaderwidths[intColIndex] = 20;
                }
                ptAssignedToData.SetWidths(AssignedToheaderwidths);
                ptAssignedToData.WidthPercentage = 100;
                ptAssignedToData.DefaultCell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
                ptAssignedToData.DefaultCell.VerticalAlignment = Element.ALIGN_MIDDLE;

                if ((strSubmitterMsgHeader.Trim() != "" && strMailToSubmitter.Trim() == "Y") ||
                    (strSubmitterMsgHeader.Trim() != "" && strOtherMailIDs.Trim() != "" &&
                    strMailToAssignee.Trim() == "N" && strMailToOwner.Trim() == "N" && strMailToSubmitter.Trim() == "N"))
                {
                    //Insert the Table Headers
                    PdfPCell HeaderSubmCell = new PdfPCell();
                    HeaderSubmCell.BorderWidth = 0.001f;
                    HeaderSubmCell.BackgroundColor = new Color(156, 207, 255);
                    HeaderSubmCell.BorderColor = new Color(100, 100, 100);
                    HeaderSubmCell.Phrase = new Phrase(strSubmitterMsgHeader, FontFactory.GetFont("Verdana", BaseFont.WINANSI, 8, Font.BOLD));
                    HeaderSubmCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    ptSubmitterHeaderData.AddCell(HeaderSubmCell);
                    strSUBMMsgBodyPart = "<br><br>" + strSubmitterMsgHeader + "";

                    //Insert the Table Data
                    string[] arrMsg = strDefectMessageHeading.Split(',');
                    for (int intColIndex = 0; intColIndex < 7; intColIndex++)
                    {
                        PdfPCell DataSubmCellColumn = new PdfPCell();
                        DataSubmCellColumn.BorderWidth = 0.001f;
                        DataSubmCellColumn.BackgroundColor = new Color(255, 255, 156);
                        DataSubmCellColumn.BorderColor = new Color(100, 100, 100);
                        DataSubmCellColumn.Phrase = new Phrase(arrMsg[intColIndex].ToString(), FontFactory.GetFont("Verdana", BaseFont.WINANSI, 8, Font.BOLD));
                        ptSubmitterData.AddCell(DataSubmCellColumn);
                    }

                    int intRowCount;
                    string[] arrRowCount = strSubmitterMsgHeader.Split(':');
                    intRowCount = Convert.ToInt32(arrRowCount[1].ToString());

                    string[] arrFinalMsg = strSubmitterFinalMsg.Split('|');
                    for (int intRCount = 0; intRCount < intRowCount; intRCount++)
                    {
                        string[] arrFinalMsg1 = arrFinalMsg[intRCount].Split(',');
                        for (int intColIndex = 0; intColIndex < 7; intColIndex++)
                        {
                            PdfPCell cell = new PdfPCell();
                            cell.BorderWidth = 0.001f;
                            cell.BorderColor = new Color(100, 100, 100);
                            cell.BackgroundColor = new Color(250, 250, 250);
                            cell.Phrase = new Phrase(arrFinalMsg1[intColIndex].ToString(), FontFactory.GetFont("Verdana", BaseFont.WINANSI, 8));
                            ptSubmitterData.AddCell(cell);
                        }
                    }
                    //Insert the Table For Submitter
                    pdfReport.Add(ptSubmitterHeaderData);
                    pdfReport.Add(ptSubmitterData);
                }
                if (strOwnerMsgHeader.Trim() != "" && strMailToOwner.Trim() == "Y" ||
                    (strOwnerMsgHeader.Trim() != "" && strOtherMailIDs.Trim() != "" &&
                    strMailToAssignee.Trim() == "N" && strMailToOwner.Trim() == "N" && strMailToSubmitter.Trim() == "N"))
                {
                    PdfPCell HeaderOwnCell = new PdfPCell();
                    HeaderOwnCell.BorderWidth = 0.001f;
                    HeaderOwnCell.BackgroundColor = new Color(156, 207, 255);
                    HeaderOwnCell.BorderColor = new Color(100, 100, 100);
                    HeaderOwnCell.Phrase = new Phrase(strOwnerMsgHeader, FontFactory.GetFont("Verdana", BaseFont.WINANSI, 8, Font.BOLD));
                    HeaderOwnCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    ptOwnerHeaderData.AddCell(HeaderOwnCell);
                    strOWNMsgBodyPart = "<br><br>" + strOwnerMsgHeader + "";

                    //Insert the Table Data
                    string[] arrMsg = strDefectMessageHeading.Split(',');
                    for (int intColIndex = 0; intColIndex < 7; intColIndex++)
                    {
                        PdfPCell DataOwnCellColumn = new PdfPCell();
                        DataOwnCellColumn.BorderWidth = 0.001f;
                        DataOwnCellColumn.BackgroundColor = new Color(255, 255, 156);
                        DataOwnCellColumn.BorderColor = new Color(100, 100, 100);
                        DataOwnCellColumn.Phrase = new Phrase(arrMsg[intColIndex].ToString(), FontFactory.GetFont("Verdana", BaseFont.WINANSI, 8, Font.BOLD));
                        ptOwnerData.AddCell(DataOwnCellColumn);
                    }

                    int intRowCount;
                    string[] arrRowCount = strOwnerMsgHeader.Split(':');
                    intRowCount = Convert.ToInt32(arrRowCount[1].ToString());

                    string[] arrFinalMsg = strOwnerFinalMsg.Split('|');
                    for (int intRCount = 0; intRCount < intRowCount; intRCount++)
                    {
                        string[] arrFinalMsg1 = arrFinalMsg[intRCount].Split(',');
                        for (int intColIndex = 0; intColIndex < 7; intColIndex++)
                        {
                            PdfPCell cell = new PdfPCell();
                            cell.BorderWidth = 0.001f;
                            cell.BorderColor = new Color(100, 100, 100);
                            cell.BackgroundColor = new Color(250, 250, 250);
                            cell.Phrase = new Phrase(arrFinalMsg1[intColIndex].ToString(), FontFactory.GetFont("Verdana", BaseFont.WINANSI, 8));
                            ptOwnerData.AddCell(cell);
                        }
                    }

                    //Insert the Table
                    pdfReport.Add(ptOwnerHeaderData);
                    pdfReport.Add(ptOwnerData);
                }
                if (strAssignedToMsgHeader.Trim() != "" && strMailToAssignee.Trim() == "Y" ||
                    (strAssignedToMsgHeader.Trim() != "" && strOtherMailIDs.Trim() != "" &&
                    strMailToAssignee.Trim() == "N" && strMailToOwner.Trim() == "N" && strMailToSubmitter.Trim() == "N"))
                {
                    ////Insert the Table Headers
                    PdfPCell HeaderAssgCell = new PdfPCell();
                    HeaderAssgCell.BorderWidth = 0.001f;
                    HeaderAssgCell.BackgroundColor = new Color(156, 207, 255);
                    HeaderAssgCell.BorderColor = new Color(100, 100, 100);
                    HeaderAssgCell.Phrase = new Phrase(strAssignedToMsgHeader, FontFactory.GetFont("Verdana", BaseFont.WINANSI, 8, Font.BOLD));
                    HeaderAssgCell.HorizontalAlignment = Element.ALIGN_CENTER;
                    ptAssignedToHeaderData.AddCell(HeaderAssgCell);
                    strASSGMsgBodyPart = "<br><br>" + strAssignedToMsgHeader + "";

                    //Insert the Table Data
                    string[] arrMsg = strDefectMessageHeading.Split(',');
                    for (int intColIndex = 0; intColIndex < 7; intColIndex++)
                    {
                        PdfPCell DataAssgCellColumn = new PdfPCell();
                        DataAssgCellColumn.BorderWidth = 0.001f;
                        DataAssgCellColumn.BackgroundColor = new Color(255, 255, 156);
                        DataAssgCellColumn.BorderColor = new Color(100, 100, 100);
                        DataAssgCellColumn.Phrase = new Phrase(arrMsg[intColIndex].ToString(), FontFactory.GetFont("Verdana", BaseFont.WINANSI, 8, Font.BOLD));
                        ptAssignedToData.AddCell(DataAssgCellColumn);
                    }

                    int intRowCount;
                    string[] arrRowCount = strAssignedToMsgHeader.Split(':');
                    intRowCount = Convert.ToInt32(arrRowCount[1].ToString());

                    string[] arrFinalMsg = strAssignedToFinalMsg.Split('|');
                    for (int intRCount = 0; intRCount < intRowCount; intRCount++)
                    {
                        string[] arrFinalMsg1 = arrFinalMsg[intRCount].Split(',');
                        for (int intColIndex = 0; intColIndex < 7; intColIndex++)
                        {
                            PdfPCell cell = new PdfPCell();
                            cell.BorderWidth = 0.001f;
                            cell.BorderColor = new Color(100, 100, 100);
                            cell.BackgroundColor = new Color(250, 250, 250);
                            cell.Phrase = new Phrase(arrFinalMsg1[intColIndex].ToString(), FontFactory.GetFont("Verdana", BaseFont.WINANSI, 8));
                            ptAssignedToData.AddCell(cell);
                        }
                    }
                    //Insert the Table
                    pdfReport.Add(ptAssignedToHeaderData);
                    pdfReport.Add(ptAssignedToData);
                }
            }

            catch (DocumentException ex)
            {
                Console.Error.WriteLine(ex.StackTrace);
                Console.Error.WriteLine(ex.Message);
            }
            // step 5: Close document
            pdfReport.Close();

            //Make a contentType indicating that the log data
            //that is attached is plain text.
            msReport.Seek(0, SeekOrigin.Begin);
            ContentType ct = new ContentType(MediaTypeNames.Application.Pdf);
            // Attach the log file stream to the e-mail message.
            System.Net.Mail.Attachment data = new System.Net.Mail.Attachment(msReport, ct);
            ContentDisposition disposition = data.ContentDisposition;
            // Suggest a file name for the attachment.
            disposition.FileName = "Defect.Pdf";
            //Add the attachment to the message.  

            strBodyEnd = "<br><br>Please find the details of Defects in the Attachment<br><br><font size='2'>Regards,";
            strBodyEnd = strBodyEnd + "<br>RADAR ADMIN</font>";
            strBodyEnd = strBodyEnd + "<br> " + "<font size='1'>This is an auto generated mail. Do not reply to this mail</font>";

            mm.Body = strBodyMain + strSUBMMsgBodyPart + strOWNMsgBodyPart + strASSGMsgBodyPart + strBodyEnd;
            mm.Attachments.Add(data);
            SmtpClient smtp = new SmtpClient();
            try
            {
                smtp.Host = objDatasetSysPara.Tables[0].Rows[0].ItemArray[0].ToString();
                smtp.Port = Convert.ToInt32(objDatasetSysPara.Tables[0].Rows[1].ItemArray[0].ToString());
                string strSMTPUserName = string.Empty;
                string strSMTPPassword = string.Empty;
                string strSSL = string.Empty;
                if (objDatasetSysPara.Tables[0].Rows.Count > 4)
                {
                    strSMTPUserName = objDatasetSysPara.Tables[0].Rows[5].ItemArray[0].ToString().Trim();
                    strSMTPPassword = objDatasetSysPara.Tables[0].Rows[6].ItemArray[0].ToString().Trim();
                    strSSL = objDatasetSysPara.Tables[0].Rows[7].ItemArray[0].ToString().Trim();

                }
                if (strSSL.ToUpper().Equals("TRUE"))
                {
                    smtp.EnableSsl = true;
                    smtp.Credentials = new System.Net.NetworkCredential(strSMTPUserName, strSMTPPassword);
                }
                smtp.Send(mm);
            }

            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                pdfReport.Close();
                pdfReport = null;
                ct = null;
                data = null;
                disposition = null;
                mm = null;
                smtp = null;
            }
        }


        #endregion
    }
    #endregion
}

#endregion

Please let me know the reason asap
Thank You
Chaitanya.E
GeneralMy vote of 5 Pin
Mallika Palaniappan27-Aug-12 23:39
Mallika Palaniappan27-Aug-12 23:39 
Questionemails are not not send to users Pin
NaniCh9-Jul-12 22:38
NaniCh9-Jul-12 22:38 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.