CRM 2011 Export Unmanaged Solutions Programatically

A couple of day’s ago I was asked to export all the unmanaged solutions from an environment for the purposes of backup. There was more than a few so to avoid having to do them all manually I hacked out this code; which when given a service and directory will export all the unmanaged from the environment.

static void ExportUnManagedSolutions(IOrganizationService service, String directory)
{
    //Find all the solutions
    QueryExpression query = new QueryExpression
    {
        EntityName = "solution",
        ColumnSet = new ColumnSet("friendlyname", "uniquename", "version"),
        Criteria = new FilterExpression()
        {
            Conditions =
            {
                //Unmanaged solutions only
                new ConditionExpression("ismanaged", ConditionOperator.Equal, false),

                //These are 'special' CRM solutions, which are marked as unmanaged but can't actually be exported
                new ConditionExpression("friendlyname", ConditionOperator.NotEqual, "Active Solution"),
                new ConditionExpression("friendlyname", ConditionOperator.NotEqual, "Default Solution"),
                new ConditionExpression("friendlyname", ConditionOperator.NotEqual, "Basic Solution"),
            }
        }
    };

    EntityCollection solutions = service.RetrieveMultiple(query);

    //For each solution found
    foreach (Entity s in solutions.Entities)
    {
        Console.WriteLine("Exporting " + s["friendlyname"]);

        //Perform a solution export
        ExportSolutionRequest request = new ExportSolutionRequest();
        request.Managed = false;
        request.SolutionName = (String)s["uniquename"];

        ExportSolutionResponse response = (ExportSolutionResponse)service.Execute(request);

        byte[] exportXml = response.ExportSolutionFile;
        string filename = (String)s["uniquename"] + " " + (String)s["version"] + ".zip";

        //This assumes the file directory already exists
        File.WriteAllBytes(directory + filename, exportXml);

        Console.WriteLine("Solution exported to {0}.", directory + filename);
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s