Fixing ‘State code or status code is invalid’ errors when deleting solutions in Dynamics CRM 2011

Working with Dynamics CRM 2011, I started getting an error when attempting to delete a managed solution:

Error deleting a managed solution: State code or status code is invalid
State code is invalid or state code is valid but status code is invalid for a specified state code.

The ErrorDetails.txt file states the following — note the text in bold.

Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: 1 is not a valid status code for state code SavedQueryState.Inactive on savedquery.Detail:

Error Code -2147187704

CallStack
at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
at Microsoft.Crm.Extensibility.ExternalMessageDispatcher.ExecuteInternal(IInProcessOrganizationServiceFactory serviceFactory, IPlatformMessageDispatcherFactory dispatcherFactory, String messageName, String requestName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, ParameterCollection fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId, Guid transactionContextId, Int32 invocationSource, Nullable`1 requestId, Version endpointVersion)
at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Execute(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)

This error came about after we marked some of the out-of-the-box views as Inactive (like “Accounts: Responded to Campaigns in Last 6 Months”). Looking at the database, the statecode (Status) and statuscode (Status Reason) for these views (in table SavedQueryBase) were both “1”. There was a simple workaround to this: change the statuscode to “2”, using the following SQL.

update savedquerybase
set statuscode = 2
where statuscode = 1
and statecode = 1

That allowed the solution to delete without error, and the views I wanted inactivated were still inactive. Seems a bug in Dynamics CRM 2011, but I can’t say for sure.

Of course, use this as your own risk!