0

I have a c# method in console app X this starts a process; console app Y (written in the same c# solution). App Y then fires a vba macro in an Excel 2010 workbook.

For testing purposes in the wkbook VBA I've added some code to force a runtime error 1004.

The winForm uses a process event, triggered using a Forms timer, to kill the Process. It is working as programmed I'd just like to try to make it do a little more. Why, when I kill the process, is the instance of XL staying open at the point when it finds the error? How do I find a way of getting rid of the instance of XL, if it still exists, when it kills the process, and then posting an error message back to my winForm?

(ps the following code is familiar but the question is not a duplicate)

    private int elapsedTime;
    private Process p;
    private System.Windows.Forms.Timer myTimer;
    const int SLEEP_AMOUNT = 1000;//1s
    const int MAXIMUM_EXECUTION_TIME = 5000;//5s


    private void btRunReport_Click(object sender, EventArgs e) {
        btRunReport.Enabled = false;
        lbStatusUpdate.Text = "Processing..";

        //instantiate a new process and set up an event for when it exits
        p = new Process();
        p.Exited += new EventHandler(MyProcessExited);
        p.EnableRaisingEvents = true;
        p.SynchronizingObject = this;
        elapsedTime = 0;
        this.RunReportScheduler();

        //add in a forms timer so that the process can be killed after a certain amount of time
        myTimer = new System.Windows.Forms.Timer();
        myTimer.Interval = SLEEP_AMOUNT;
        myTimer.Tick += new EventHandler(TimerTickEvent);
        myTimer.Start();

    }
    private void RunReportScheduler() {
        p.StartInfo.FileName = @"\\fileserve\department$\ReportScheduler_v3.exe";
        p.StartInfo.Arguments = 2;
        p.Start();
    }
    private void MyProcessExited(Object source, EventArgs e){
        myTimer.Stop();
        btRunReport.Enabled = true;
        lbStatusUpdate.Text = "Start";
    }
    void TimerTickEvent(Object myObject, EventArgs myEventArgs) {
        myTimer.Stop();
        elapsedTime += SLEEP_AMOUNT;
        if (elapsedTime > MAXIMUM_EXECUTION_TIME)
        {p.Kill();}
        else
        {myTimer.Start();}
    }
whytheq
  • 34,466
  • 65
  • 172
  • 267

2 Answers2

1

it might be the issue with report scheduler which does not have the proper method which closes Excel.

This is such method:

private void releaseObject(object obj)
{
    try
    {
        System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
        obj = null;
    }
    catch (Exception ex)
    {
        obj = null;
        MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
    }
    finally
    {
        GC.Collect();
    }
}
Andrew
  • 7,619
  • 13
  • 63
  • 117
  • 1
    thanks Andrew - not near code at present but I'll start playing around with this tomorrow. My friend has also suggested that the code I presented above is ok and the problem is more likely with ReportScheduler_v3.exe and the way it is handling xl – whytheq Mar 19 '12 at 21:28
0

I've left the original bit of code unchanged but I've used the help from Andrew but mainly the help of a good friend of mine who unfortunately isn't signed up to SO. Excel seems to be dead!. Plus he's coded it in such a way that it passes back an indicator telling the form if it had problems with excel or not. Also gives us the option of building in maximum run times for each excel process.

He used the following SO answer to help get rid of Excel

1.In scheduler program

  • Move timer there
  • Implement excel cleaning code in the case there is no errors in vba and in the opposite case when maximum execution time reached (use Kill method)
  • From the scheduler return 0 to the forms application if excel finished normally or 1 if it was killed

2.In the forms application analyse return value from the scheduler in the ProcessExited event handler and enable button, etc

So, the new scheduler:

 using System;
 using System.Text;
 using System.Runtime.InteropServices;
 using System.Diagnostics;
 using Excel = Microsoft.Office.Interop.Excel;
 using System.Timers;


class Program
{
   private const int SLEEP_AMOUNT = 1000;
   private const int MAXIMUM_EXECUTION_TIME = 10000;
   private Excel.Application excelApp =null;
   private Excel.Workbook book =null;
   private Timer myTimer;
   private int elapsedTime;
   private int exitCode=0;

   [DllImport("user32.dll", SetLastError =true)]
   static extern uint GetWindowThreadProcessId(IntPtr hWnd,out uint lpdwProcessId);

   static int Main(string[] args)
    {
       Program myProgram = newProgram();
       myProgram.RunExcelReporting(1);
       return myProgram.exitCode;
    }


   void myTimer_Elapsed(object sender,ElapsedEventArgs e)
    {
       myTimer.Stop();
       elapsedTime += SLEEP_AMOUNT;
       if (elapsedTime > MAXIMUM_EXECUTION_TIME)
        {
            //error in vba or maximum time reached. abort excel and return 1 to the calling windows forms application
           GC.Collect();
           GC.WaitForPendingFinalizers();
           if (book != null)
            {
               book.Close(false,Type.Missing, Type.Missing);
               Marshal.FinalReleaseComObject(book);
               book =null;
            }

           if (excelApp != null)
            {
               int hWnd = excelApp.Hwnd;
               uint processID;
               GetWindowThreadProcessId((IntPtr)hWnd,out processID);
               if (processID != 0)
                   Process.GetProcessById((int)processID).Kill();
                excelApp =null;
                exitCode = 1;
            }
        }
       else
        {
            myTimer.Start();
        }
    }


   void RunExcelReporting(int x)
    {
        myTimer =new Timer(SLEEP_AMOUNT);
        elapsedTime = 0;
        myTimer.Elapsed +=new ElapsedEventHandler(myTimer_Elapsed);
        myTimer.Start();

       try{
            excelApp =new Excel.Application();
            excelApp.Visible =true;
            book = excelApp.Workbooks.Open(@"c:\jsauto.xlsm");
            excelApp.Run("ThisWorkbook.rr");
            book.Close(false,Type.Missing, Type.Missing);
        }
        catch (Exception ex){
           Console.WriteLine(ex.ToString());
        }

       finally
        {
           //no error in vba and maximum time is not reached. clear excel normally
           GC.Collect();
           GC.WaitForPendingFinalizers();

           if (book != null)
            {
               try {
                    book.Close(false,Type.Missing, Type.Missing);
                }
                catch { }
               Marshal.FinalReleaseComObject(book);
            }

           if (excelApp != null)
            {
               excelApp.Quit();
               Marshal.FinalReleaseComObject(excelApp);
               excelApp =null;
            }
        }
    }
}

And the new forms application:

public partial class Form1 : Form

{
   SqlDataAdapter myAdapt = null; 
   DataSet mySet =null; 
   DataTable myTable =null; 

   public Form1()
    { InitializeComponent();}

    privatevoid Form1_Load(object sender,EventArgs e){ 
        InitializeGridView();
    }

   private Process myProcess;

   private void btRunProcessAndRefresh_Click(object sender,EventArgs e)
    {
        myProcess =new Process();
        myProcess.StartInfo.FileName =@"c:\VS2010Projects\ConsoleApplication2\ConsoleApplication4\bin\Debug\ConsoleApplication4.exe";
        myProcess.Exited +=new EventHandler(MyProcessExited);
        myProcess.EnableRaisingEvents =true;
        myProcess.SynchronizingObject =this;
        btRunProcessAndRefresh.Enabled =false;
        myProcess.Start();
    }

    privatevoid MyProcessExited(Object source,EventArgs e)
    {
        InitializeGridView();
        btRunProcessAndRefresh.Enabled =true;
       if (((Process)source).ExitCode == 1)
        {
           MessageBox.Show("Excel was aborted");
        }
       else
        {
           MessageBox.Show("Excel finished normally");
        }
    }

   private void btnALWAYSWORKS_Click(object sender,EventArgs e) { 
        InitializeGridView();
    }

    privatevoid InitializeGridView() { 
      using (SqlConnection conn =new SqlConnection(@"Data Source=sqliom3;Integrated Security=SSPI;Initial Catalog=CCL"))
        {
        myAdapt =new SqlDataAdapter("SELECT convert(varchar(25),getdate(),120) CurrentDate", conn);
        mySet =new DataSet();
        myAdapt.Fill(mySet,"AvailableValues"); 
        myTable = mySet.Tables["AvailableValues"];

        this.dataGridViewControlTable.DataSource = myTable;
        this.dataGridViewControlTable.AllowUserToOrderColumns =true;
        this.dataGridViewControlTable.Refresh();
        }
    }
  }
Community
  • 1
  • 1
whytheq
  • 34,466
  • 65
  • 172
  • 267