Fixing NativeHR 0x80070002 Error When Retracting or Deploying SharePoint Apps from Visual Studio

Sometimes when App deployment fails from Visual Studio you will get the following error when trying to retract or redeploy the app:

<nativehr>0x80070002</nativehr><nativestack></nativestack>

There seems to be some issue with the information in the content database.  To fix the problem I just deleted all of the information from the App tables in the content database.  We only have one app in testing at a time so this worked fine for me.  Doing this in a production environment or if you have multiple apps installed is not recommended, so if you are in either of those scenarios you will probably have to dig into those tables to find the offending entries.  You may also have to remove some of the App principal entries from the App Service Application database as well (I’ll try to update this post if we find that to be true).   I’m going to post the SQL to do the full deletion, but be careful when running this:

DO NOT RUN THIS IN A PRODUCTION ENVIRONMENT:

DELETE FROM [dbo].[AppDatabaseMetadata]
DELETE FROM [dbo].[AppInstallationProperty]
DELETE FROM [dbo].[AppInstallations]
DELETE FROM [dbo].[AppJobs]
DELETE FROM [dbo].[AppLifecycleErrors]
DELETE FROM [dbo].[AppPackages]
DELETE FROM [dbo].[AppPrincipalPerms]
DELETE FROM [dbo].[AppPrincipals]
DELETE FROM [dbo].[AppResources]
DELETE FROM [dbo].[AppRuntimeIcons]
DELETE FROM [dbo].[AppRuntimeMetadata]
DELETE FROM [dbo].[AppRuntimeSubstitutionDictionary]
DELETE FROM [dbo].[AppSourceInfo]
DELETE FROM [dbo].[AppSubscriptionCosts]
DELETE FROM [dbo].[AppTaskDependencies]