Click here to Skip to main content
15,899,026 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am facing an issue in Windows Service.This service generates excel and then sends it as an attachment in a mail. I have put the start timing for the Windows Service in app.config and set the timer interval as 3 min(3*60*1000)..Dont know where I am goin wrong

It throws the error:

Retrieving the COM class factory for component with CLSID {00024500-0000-0000-C000-000000000046} failed due to the following error: 80080005 Server execution failed (Exception from HRESULT: 0x80080005 (CO_E_SERVER_EXEC_FAILURE)).<br />
Could not find file C:\test\test_16.02.2011 05.43.20.xlsx


Please check in in StartService() and time_elapsed()
Please suggest something on it..

The code is as below:

C#
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.Data.SqlClient;
using System.Windows.Forms;
using System.Web;
using Excel = Microsoft.Office.Interop.Excel;
using System.Net.Mail;
using System.Configuration;
using System.Collections;
using System.Reflection;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
 
namespace AutomationProcess
{
    ///////////////////////////////////////////////////////////////////////
    public partial class Service1 : ServiceBase
    {
        DateTime lastRunDate = DateTime.Today;
        System.Timers.Timer time = new System.Timers.Timer();
 
        //-----------------------------------------------------------------
        public Service1()
        {
            InitializeComponent();
        }
 
        //-----------------------------------------------------------------
        public void automate()
        {
            string filepath, filename, fileExcel,renamedfile;
 
            string ReportCount = "select count(rs.contactID) from tblReportLOg rs inner join tblContact c on c.contactID = rs.contactID where LogDate >= '2011-01-20 00:00:00.000' and c.email like '%micro%' and rs.contactid not in (39287,39286,27546)";
            string UserCount = "select count(distinct(rs.contactID)) from tblReportLOg rs inner join tblContact c on c.contactID = rs.contactID where LogDate >= '2011-01-20 00:00:00.000' and c.email like '%micro%' and rs.contactid not in (39287,39286,27546)";
            Random nRandom = new Random(DateTime.Now.Millisecond);
 
            //Create a random file name.
            fileExcel = "t" + nRandom.Next().ToString() + ".xls";
            filepath = "C:\\test";
            //filename = filepath + "\\" + fileExcel;
            filename = "C:\\Test\\test.xlsx";
            //renamedfile = Path.GetFileNameWithoutExtension(filename);
           // renamedfile = renamedfile += "_" + DateTime.Now.ToShortDateString() + Path.GetExtension(filename);
          //  renamedfile = renamedfile += "_" + DateTime.Now.ToLocalTime() + Path.GetExtension(filepath);
 
            renamedfile = System.IO.Path.GetFileNameWithoutExtension(filename);
            renamedfile = System.IO.Path.GetPathRoot(filename) + "test\\" + renamedfile + "_" + DateTime.Now.ToString("dd.MM.yyyy hh.mm.ss") + System.IO.Path.GetExtension(filename);
            try
            {
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = ConfigurationManager.AppSettings["Connection"];
                SqlCommand cmd = new SqlCommand("select rs.contactID,SurveyType,ModuleName,LogDate from tblReportLOg rs inner join tblContact c on c.contactID = rs.contactID where LogDate >= '2011-01-20 00:00:00.000' and c.email like '%micro%' and rs.contactid not in (39287,39286,27546) order by LogDate ", conn);
                SqlCommand cmd1 = new SqlCommand(ReportCount, conn);
                SqlCommand cmd2 = new SqlCommand(UserCount, conn);
                SqlDataAdapter mySqlDataAdapter = new SqlDataAdapter(cmd);
                DataSet d = new DataSet();
                mySqlDataAdapter.Fill(d, "dataset");
                conn.Open();
                string reports = Convert.ToString(cmd1.ExecuteScalar());
                string users = Convert.ToString(cmd2.ExecuteScalar());
 
                // Create the Excel Application object

                Microsoft.Office.Interop.Excel._Application excelApp = new Microsoft.Office.Interop.Excel.Application();
                // Create a new Excel Workbook
                Excel.Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);
                int sheetIndex = 0;
 
                // Copy each DataTable
                foreach (System.Data.DataTable dt in d.Tables)
                {
                    // Copy the DataTable to an object array
                    object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];
 
                    // Copy the column names to the first row of the object array

                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        rawData[0, col] = dt.Columns[col].ColumnName;
                    }
 
                    // Copy the values to the object array
                    for (int col = 0; col < dt.Columns.Count; col++)
                    {
                        for (int row = 0; row < dt.Rows.Count; row++)
                        {
                            rawData[row + 1, col] = dt.Rows[row].ItemArray[col];
                        }
                    }
 
                    // Calculate the final column letter
                    string finalColLetter = string.Empty;
                    string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                    int colCharsetLen = colCharset.Length;
                    if (dt.Columns.Count > colCharsetLen)
                    {
                        finalColLetter = colCharset.Substring((dt.Columns.Count - 1) / colCharsetLen - 1, 1);
                    }
                    finalColLetter += colCharset.Substring((dt.Columns.Count - 1) % colCharsetLen, 1);
 
                    // Create a new Sheet
                    Excel.Worksheet excelSheet = (Excel.Worksheet)excelWorkbook.Sheets.Add(excelWorkbook.Sheets.get_Item(++sheetIndex), Type.Missing, 1, Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
                    excelSheet.Name = dt.TableName;
 
                    // Fast data export to Excel
                    string excelRange = string.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1);
                    excelSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;
*nbsp;
                    Excel.Range rg;
                    rg = excelSheet.get_Range("D:D", Type.Missing);
                    rg.NumberFormat = "MM-DD-YYYY hh:mm";
                }
 
                // Save and Close the Workbook
                excelWorkbook.SaveCopyAs(renamedfile);
                excelWorkbook.Close(true, Type.Missing, Type.Missing);
                excelWorkbook = null;
                // Release the Application object
                excelApp.Quit();
                excelApp = null;

            }
            catch (Exception ex)
            {
                // writes to log            }
            finally
            {
                // Collect the unreferenced objects
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
            SendEmail(ReportCount, UserCount);
        }
 
        //-----------------------------------------------------------------
        private static void SendEmail(string reports, string users)
        {
            string renamedfile;
            string filename="C:\\Test\\test.xlsx";
            renamedfile = System.IO.Path.GetFileNameWithoutExtension(filename);
            renamedfile = System.IO.Path.GetPathRoot(filename) + "test\\" + renamedfile + "_" + DateTime.Now.ToString("dd.MM.yyyy hh.mm.ss") + System.IO.Path.GetExtension(filename);
            try
            {
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                message.From = new MailAddress("abc@gmail.com");
                message.To.Add("lmn@gmail.com");
                message.Subject = "Statistical Report";
                message.Body = "Please find attached the statistical report " +
                     "\nTotal number of reports downloaded by users is " + reports +
                     "\nTotal number of users who have downloaded reports is " + users;
                Attachment attach = new Attachment(renamedfile);
                message.Attachments.Add(attach);
 
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient("localhost");
                smtp.Send(message);
            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message);
            }
        }
 
        //-----------------------------------------------------------------
        protected override void OnStart(string[] args)
        {
            StartService();
        }
 
        //-----------------------------------------------------------------
        public void StartService()
        {
            try
            {
                TimeSpan ts;
                DateTime startTime;
                string startTimeString = ConfigurationManager.AppSettings["Initiate"].ToString();
 
                if (TimeSpan.TryParse(startTimeString, out ts))
                {
                    startTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, ts.Hours, ts.Minutes, ts.Seconds);
                }
                else
                {
                    startTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 9, 42, 0);
                }
                ts = startTime.Subtract(DateTime.Now);
                if (ts.Milliseconds < 0)
                {
                    startTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day + 1, ts.Hours, ts.Minutes, ts.Seconds);
                }
                ts = startTime.Subtract(DateTime.Now);
                time.Interval = ts.TotalMilliseconds;
                time.Elapsed += new ElapsedEventHandler(time_Elapsed);
                time.Enabled = true;
                time.Start();
                time.Interval = 3 * 60 * 1000;
            }
            catch (Exception ex)
            {
                WriteToLog(ex.Message);
            }
        }
 
        //-----------------------------------------------------------------
        void time_Elapsed(object sender, ElapsedEventArgs e)
        {
            DateTime startTime = DateTime.Today;
 
            if((startTime.DayOfWeek == DayOfWeek.Wednesday) || (startTime.DayOfWeek== DayOfWeek.Friday))
            {
                automate();
            }
        }
 
        //-----------------------------------------------------------------
        protected override void OnStop()
        {
        }
    }
}
Posted
Updated 16-Feb-11 1:50am
v3
Comments
#realJSOP 16-Feb-11 7:50am    
I removed all of the commented out code and calls to WriteToLog, as they are not necessary and add nothing to the question.
Aksh@169 16-Feb-11 7:52am    
Thanks John for making it easy to read..I didnt know how to format it
I am looking for a resolution fr the issue I am facing..changes the start time from app.config with the interval of 3 min..still the same issue:(

You should use a thread instead of a timer. Here's your code rewqorked to use a thread, and to abstract out some of the code into discreet methods (monolithic methods are so 1980's). Keep in mind that I merely typed this into the editor here at CP, so it will probably require a tweak or two to actually compile/run.

The way the code is written in my version, it would be a simple matter to move the code to a console app so it's easier yto debug.

Final note - according to your code, you execute the automate method every three minutes but only process the data on wednesdays and fridays - evry three minutes. I'm almost positive that's not what you really want.


C#
public class MyService...
{
    Thread m_thread = null;
 
    //-------------------------------------------------------------------------
    public void OnStart()
    {
        m_thread = new Thread(new ThreadStart(ThreadProc));
        m_thread.Start();    
    }
 
    //-------------------------------------------------------------------------
    public void ThreadProc()
    {
        int interval = 30000; // 3 minutes
        int elapsed  = 0;
        int waitTime = 1000; // 1 second
        try
        {
            while (true)
            {
                if (interval >= elapsed)
                {
                    elapsed = 0;
                    automate();
                }                
                Thread.Sleep(waitTime);
                // indicate that 1 additional second has passed                
                elapsed += waitTime;
            }
        }
        catch (ThreadAbortException)
        {
            // we want to eat the excetion because we don't care if the
            // thread has aborted since we probably did it on purpose by
            // stopping the service.
        }
    }

    //-------------------------------------------------------------------------
    private bool automate()
    {
        bool automated = false;
        DateTime now = dateTime.Now;
        if (now.DayOfWeek == DayOfWeek.Wednesday && 
            now.DayOfWeek == DayOfWeek.Wednesday)
        {
            MakeFileFromDatabase();
        }
    }

    //-------------------------------------------------------------------------
    private void MakeFileFromDatabase()
    {
        DataSet d = null;
        try
        {
            SqlConnection    conn = new SqlConnection();
            conn.ConnectionString = ConfigurationManager.AppSettings["Connection"];
            SqlCommand       cmd  = new SqlCommand("select rs.contactID, SurveyType, ModuleName, " +
                                                   "LogDate from tblReportLOg rs inner join " + 
                                                   "tblContact c on c.contactID = rs.contactID " + 
                                                   "where LogDate >= '2011-01-20 00:00:00.000' " + 
                                                   "and c.email like '%micro%' and rs.contactid " + 
                                                   "not in (39287,39286,27546) order by LogDate ", 
                                                   conn);
            SqlCommand       cmd1 = new SqlCommand(ReportCount, conn);
            SqlCommand       cmd2 = new SqlCommand(UserCount, conn);
            SqlDataAdapter   mySqlDataAdapter = new SqlDataAdapter(cmd);
 
            d                     = new DataSet();
            mySqlDataAdapter.Fill(d, "dataset");
            conn.Open();
            string reports        = Convert.ToString(cmd1.ExecuteScalar());
            string users          = Convert.ToString(cmd2.ExecuteScalar());
            MakeExcelFile(d);
        }
        catch (Exception ex)
        {
            throw new Exception("Exception will retrieveing Data", ex);
        }
        finally
        {
            conn.Close();
        }
    }

    //-------------------------------------------------------------------------
    private void MakeExcelFile(DataSet d)
    {
        try
        {
            // Create the Excel Application object
            Microsoft.Office.Interop.Excel._Application excelApp = new Microsoft.Office.Interop.Excel.Application();
            // Create a new Excel Workbook
            Excel.Workbook excelWorkbook = excelApp.Workbooks.Add(Type.Missing);
            int sheetIndex = 0;

            // Copy each DataTable
            foreach (System.Data.DataTable dt in d.Tables)
            {
                // Copy the DataTable to an object array
                object[,] rawData = new object[dt.Rows.Count + 1, dt.Columns.Count];
                // Copy the column names to the first row of the object array
                for (int col = 0; col < dt.Columns.Count; col++)
                {
                    rawData[0, col] = dt.Columns[col].ColumnName;
                }
                // Copy the values to the object array
                for (int col = 0; col < dt.Columns.Count; col++)
                {
                    for (int row = 0; row < dt.Rows.Count; row++)
                    {
                        rawData[row + 1, col] = dt.Rows[row].ItemArray[col];
                    }
                }
                // Calculate the final column letter
                string finalColLetter = string.Empty;
                string colCharset = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                int colCharsetLen = colCharset.Length;
                if (dt.Columns.Count > colCharsetLen)
                {
                    finalColLetter = colCharset.Substring((dt.Columns.Count - 1) / colCharsetLen - 1, 1);
                }
                finalColLetter += colCharset.Substring((dt.Columns.Count - 1) % colCharsetLen, 1);
                // Create a new Sheet
                Excel.Worksheet excelSheet = (Excel.Worksheet)excelWorkbook.Sheets.Add
                                              (excelWorkbook.Sheets.get_Item(++sheetIndex), 
                                               Type.Missing, 1, 
                                               Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet);
                excelSheet.Name = dt.TableName;
                // Fast data export to Excel
                string excelRange = string.Format("A1:{0}{1}", finalColLetter, dt.Rows.Count + 1);
                excelSheet.get_Range(excelRange, Type.Missing).Value2 = rawData;
                Excel.Range rg  = excelSheet.get_Range("D:D", Type.Missing);
                rg.NumberFormat = "MM-DD-YYYY hh:mm";
            }
 
            // Save and Close the Workbook
            string fileName = MakeFileName()
            excelWorkbook.SaveCopyAs(fileName);
            excelWorkbook.Close(true, Type.Missing, Type.Missing);
            excelWorkbook = null;
            // Release the Application object
            excelApp.Quit();
            excelApp = null;
        }
        catch (Exception ex)
        {
            throw new Exception("Exception while creating exel file", ex);
        }
    }
 
    //-------------------------------------------------------------------------
    private string MakeFilename()
    {
        //Create a random file name.
        string fileExcel = "t" + nRandom.Next().ToString() + ".xls";
        string filepath = "C:\\test";
        filename = "C:\\Test\\test.xlsx";
        string renamedfile = string.Format("{0}_{1}{2}",
                                           System.IO.Path.GetFileNameWithoutExtension(filename),
                                           DateTime.Now.ToString("yyyyMMdd_HHmm"),
                                           System.IO.Path.GetExtension(filename));
        return renamedfile;
    }
}
 
Share this answer
 
v2
Comments
Aksh@169 16-Feb-11 12:16pm    
My requirement is that i need to fetch data frm database and export it to excel.
Next i need to trigger a mail every Tues anf Friday at 4 pm that has the exported excel as its attachment.I have to build Windows Service fr this task.

Please tell me if I am goin off track

Thanks
#realJSOP 16-Feb-11 13:14pm    
Yes, you're going off track. Have you even verified that a) the data is being retrieved from the database correctly, and b) that the excel file is being created? Further, youtr scheduling code does NOT meet the timing requirements you just stated.
Aksh@169 16-Feb-11 22:26pm    
yes, the data is being retrieved correctly and exported to excel as well. Checked this by implementing the code in windows application. The problem is appearing in Windows service.So it seemed to me that issue is with setting the timer.
Aksh@169 16-Feb-11 22:55pm    
Can u please lemme know how do i achieve the timing requirement i.e triggering at 4 pm on two specified days
Sergey Alexandrovich Kryukov 16-Feb-11 12:40pm    
Good, my 5. Not using timer is important advice.
--SA
Your elapsed_time method will execute the automate method every time it's called on a Wednesday or Friday. EVERY TIME. I'm almost positive that's not what you want. Even if it is what you want, that's a poor approach.

The error message itself tells you what's wrong - it can't find the file you're looking for.

My advice is to move the code to a console app and run that app under the debugger (that's easier than debugging a service). At that point, you can follow the code and see what's happening.
 
Share this answer
 
Hello,
This exeption is due to a long file name that contains spaces, try shorten the file name (test_16.02.2011 05.43.20.xlsx) and i think every think will work fine.
I think eliminating the space in the file name will do too.
 
Share this answer
 
v2
Comments
Aksh@169 17-Feb-11 0:53am    
Hi,
Tried that as well but it didnt help.
While debuggind the same code in windows app its working fine but not in windows service

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900