Search code examples
c#sql-serveroffice-interopms-project

Task export on MSProject with error on blank/empty tasks


I created an Addin in C# VSTO to export tasks from MSProject to a SQLServer. My code works fine until the tasks in MSProject have an empty/blank entry.

I have no idea for a workaround. It seems, that die foreach isn't working here.

    MsProject.Tasks tasks = Globals.ThisAddIn.Application.ActiveProject.Tasks;

    using (SqlConnection cnn = new SqlConnection(connectionString))
    {

    try
    {
        // Open the connection to the database.
        cnn.Open();

        foreach (Microsoft.Office.Interop.MSProject.Task t in tasks)
        {
                DateTime start = (DateTime)t.Start;
                DateTime finish = (DateTime)t.Finish;
                
                using (SqlCommand cmd = new SqlCommand(sql, cnn))
                {
                    // Create and set the parameters values 

                    cmd.Parameters.Add("@id", SqlDbType.Int).Value = t.ID;
                    cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = t.Name;
                    cmd.Parameters.Add("@start", SqlDbType.DateTime).Value = start;
                    cmd.Parameters.Add("@finish", SqlDbType.DateTime).Value = finish;
                    
                    int rowsAdded = cmd.ExecuteNonQuery();   
                }
            }
        
        MessageBox.Show("Data transfered" );


    }

            

In MSProject it looks like:

enter image description here

Does anyone have an idea how to loop over or include the blank/empty tasks?

Currently i only get NullPointerReference of the object as Error and the Third task won't be export to SQL Server.


Solution

  • This is a common problem. Whenever looping through tasks, check to see that the task object is not null before using it:

    foreach (Microsoft.Office.Interop.MSProject.Task t in tasks)
    {
        if (t != null)
        {
            DateTime start = (DateTime)t.Start;
            DateTime finish = (DateTime)t.Finish;
            // rest of code...