How to Determine if a Project isDirty

As previously noted the isDirty property of a project is for “Microsoft Internal Use Only” and does not actually return valid information.  Instead you can determine this by querying for unsaved ProjectItems.  The property MacroProjectSaved below demonstrates how to do this.  Additional code is included to show how to ask a user if they would like to save the macro project when they exit the IDE if the project has unsaved items (some of this code is repeated from previous blogs). 

//determines if there are unsaved project items in the macro project

private bool MacroProjectSaved

{

    get

    {

        if (this.macroProject.Saved)

        {

            int unsavedProjItemCount =

                (from EnvDTE.ProjectItem projItem in

                     this.macroProject.ProjectItems

                where !projItem.Saved

                select projItem).Count();

 

            return unsavedProjItemCount == 0;

        }

        else

        {

            return false;

        }

    }

}


private
void EnsureIDE()

{
     //save this variable in the class scope to prevent unwanted garbage collection

     //get and subscribe to the File.Exit event prior to execution

     EnvDTE.CommandEvents exitCommand =

       dte.Events.get_CommandEvents

       ("{5EFC7975-14BC-11CF-9B2B-00AA00573819}", 229);

                   

     exitCommand.BeforeExecute +=

       new EnvDTE._dispCommandEvents_BeforeExecuteEventHandler

       (exitCommand_BeforeExecute);

}

 

//checks if the user would like to save the project before exiting if the project is dirty

void exitCommand_BeforeExecute(string Guid, int ID, object CustomIn, object CustomOut, ref bool CancelDefault)

{

    //Project.IsDirty is always false, so use the below property MacroProjectSaved

    if (!this.MacroProjectSaved)

    {

        //prompt the user to save the project

        EnvDTE.vsPromptResult promptResult =

            this.dte.ItemOperations.PromptToSave;

 

        if (promptResult == EnvDTE.vsPromptResult.vsPromptResultYes)

            this.MacroProject.Save(this.macroProject.FileName);

    }

}


Posted Mar 19 2010, 01:04 PM by Melody
Filed under: , ,
Copyright Summit Software Company, 2008. All rights reserved.