Error copying temporary solution file to solutions gallery

My first dig at SharePoint 2010..nah..I have been working on it for some time ..and am sure better posts on 2010 are en route

Let me start off with this one.

Well.. this one is not exactly about SharePoint 2010, except the error message and that sites can now be saved as .wsp packages (which you already must be aware of if you are getting this error), which is :

[System.InvalidOperationException] = {"Error copying temporary solution file to solutions gallery: _catalogs/solutions/site16.wsp"}

….at Microsoft.SharePoint.SPSolutionExporter.ExportWebToGallery(SPWeb web, String solutionFileName, String title, String description, ExportMode exportMode, Boolean includeContent, String workflowTemplateName, String destinationListUrl)

at Microsoft.SharePoint.SPWeb.SaveAsTemplate(String strTemplateName, String strTemplateTitle, String strTemplateDescription, Boolean fSaveData) at….

All I am trying is SPWeb.SaveAsTemplate method to save a site as template (.wsp) from code that runs in a custom Application page.The same code runs fine from a console application though.I checked the ULS logs and found that the actual exception is :

SPSolutionExporter: Microsoft.SharePoint.SPException: The security validation for this page is invalid. Click Back in your Web browser, refresh the page, and try your operation again

Through reflector, I was able to track that SPWeb.SaveAsTemplate internally calls Microsoft.SharePoint.SPSolutionExporter.ExportWebToGallery

From here, I analyzed that the code fails while adding the .wsp file (which has already been generated by now in the code of ExportWebToGalleryMethod and stored as a .TMP file in %temp% directory) to the User Solutions Gallery (_catalogs/solutions). The InvalidOperationException, though is raised in this method with the custom message string - SPResource.GetString("SitePackaging_ErrorCopyingTemporarySolutionFileToSolutionsGallery"…

So good for analysis and exploring new APIs, but as it turns out that the actual exception is the good old “The security validation for this page is invalid” SPException and I probably missed some basic stuff ….like AllowUnsafeUpdates. Huh, but I did make sure I set it correctly. But not for the correct objects.Since I was running the custom application page from a subsite, while the solutions gallery is on the RootSite, I added the statement web.Site.RootWeb.AllowUnsafeUpdates = false and the error was gone.

     protected void Page_Load(object sender, EventArgs e)
        {
            SPWeb web = SPContext.Current.Web;
            try
            {
                //SPUtility.ValidateFormDigest();
                web.AllowUnsafeUpdates = true;
                web.Site.RootWeb.AllowUnsafeUpdates = true;
                //Error here: “Error copying temporary solution file to solutions gallery: _catalogs/solutions/site16.wsp” 
                web.SaveAsTemplate(web.Title, web.Title, "", false);
                 //SPSolutionExporter.ExportWebToGallery(web, "solutionFileName", "templateTitle", "templateDescription", SPSolutionExporter.ExportMode.FullReuse, false);

                web.AllowUnsafeUpdates = false;
                web.Site.RootWeb.AllowUnsafeUpdates = false;
                result = "Success";
            }
            catch (Exception Ex)
            {
                result = Ex.StackTrace;
            }
            finally
            {
                Label1.Text = result;
            }
            
        }

Other way would be to use SPUtility.ValidateFormDigest() as the first thing on the custom application page. For a comprehensive understanding on all things 
 AllowUnsafeUpdates, two part series by Hristo Pavlov is a great place :
 https://hristopavlov.wordpress.com/2008/05/16/what-you-need-to-know-about-allowunsafeupdates/

Happy Investigating SharePoint !!