Manipulating SharePoint 2010 User Solutions Programmatically

In continuance of my last post, I noticed that when I added the SPWeb WSPs (SPWeb.SaveAsTemplate) to the User Solutions Gallery (Top Level Site Settings –> Solutions), they were not activated. Which I later found was because I was using one of the pre-RTM builds. In RTM, Save Site as template will not only add the solution , but activate them as well, so that the site template is available for creation at sub-site create page.

Now in my custom application page, I needed to present a list of such User Solutions(templates, sandbox solutions etc) and be able to activate , deactivate, remove them from this page.

The fact that it’s a Catalog , or in simpler terms a Library, the items need to be treated as SPListItem and WSPs as SPListItem.File

I am sharing the code snippets which I tested successfully in a console application below:

 using (SPSite oSite = new SPSite("https://mss2010"))
            {
                using (SPWeb web = oSite.OpenWeb())
                {

                    SPWeb rootweb = web.Site.RootWeb;

                    // Code to ACtivate solution
                    SPList solGallery  = rootweb.Site.GetCatalog(SPListTemplateType.SolutionCatalog);
                    foreach (SPListItem item in solGallery.Items)
                    {
                        if (item.File.Name.Equals("site1.wsp"))
                        {
                            rootweb.Site.Solutions.Add(item.ID);
                            break;
                        }
                    }
                    // Code to DeACtivate solution
                    foreach (SPUserSolution solution in rootweb.Site.Solutions)
                    {
                        if (solution.Name.Equals("site1.wsp"))
                        {
                            rootweb.Site.Solutions.Remove(solution);
                        }
                    }
                    // Code to Delete solution
                    SPList solGallery1 = rootweb.Site.GetCatalog(SPListTemplateType.SolutionCatalog);
                    foreach (SPListItem item in solGallery1.Items)
                    {
                        if (item.File.Name.Equals("site1.wsp"))
                        {
                            solGallery1.Items.DeleteItemById(item.ID);
                            break;
                        }
                    }

                }
            }