Problem with SPList.SaveAsTemplate

Charles Lee
  • Problem with SPList.SaveAsTemplate Charles Lee

    I have never really had too much cause to use this method before but I am developing some generic classes to deal with column, content type and list management for use in a series of features.

    My ListHelper class has a method called DeleteList which looks like this:

            Public Shared Function DeleteList(ByVal List As SPList, ByVal Operation As DeleteOperation) As Boolean
    
            If Operation = DeleteOperation.DeleteWithBackup Or Operation = DeleteOperation.ForcedDeleteWithBackup Then
                SaveListAsTemplate(List, True)
            End If
    
            If Operation = DeleteOperation.ForcedDelete Or Operation = DeleteOperation.ForcedDeleteWithBackup Then
                If List.AllowDeletion = False Then
                    List.AllowDeletion = True
                    List.Update()
                End If
            End If
    
            Try
                List.Delete()
            Catch ex As Exception
                Return False
            End Try
    
            Return True
    
        End Function
    

    This is very much a work in progress, but I am having trouble with the SaveListAsTemplate method which looks like this:

            Public Shared Function SaveListAsTemplate(ByVal List As SPList, ByVal SaveContent As Boolean) As String
    
            If HttpContext.Current IsNot Nothing Then
                Dim tmpFileName As String = List.Title & "_saved_" & Now.ToFileTimeUtc & ".stp"
                List.SaveAsTemplate(tmpFileName, List.Title, "list template saved programmatically", SaveContent)
                Return List.ParentWeb.Site.Url & "/_catalogs/lt/" & tmpFileName
            Else
                Throw New Exception("List template cannot be saved unless the code is running in a valid HttpContext")
            End If
    
        End Function
    

    The reason for the check into HttpContext is possibly not required, this is the reason for my post. I cannot get this code to execute from within a console application. Does the SPList.SaveAsTemplate method require a HttpContext? If it does it is not metioned in any of the docs that I have seen.

    As an aside any other comments on this code gratefully received.

    EDIT: Exception and Stack Trace

    System.ArgumentException "Value does not fall within the expected range" at Microsoft.SharePoint.SPGlobal.HandleException(Exception ex) at Microsoft.SharePoint.SPList.SaveAsTemplate(String strFileName, String strName, String strDescription, Boolean bSaveData)
    at XXXXXX.SharePoint.Lists.ListHelper.SaveListAsTemplate(SPList List, Boolean SaveContent) in C:\SharePoint Development Projects\XXXXXX.SharePoint\XXXXXX.SharePoint\Lists\ListHelper.vb:line 145 at XXXXXX.SharePoint.Lists.ListHelper.DeleteList(SPList List, DeleteOperation Operation) in C:\SharePoint Development Projects\XXXXXX.SharePoint\XXXXXX.SharePoint\Lists\ListHelper.vb:line 121 at XXXXXX.SharePoint.Lists.ListHelper.DeleteList(SPWeb Web, String ListName, DeleteOperation Operation) in C:\SharePoint Development Projects\XXXXXX.SharePoint\XXXXXX.SharePoint\Lists\ListHelper.vb:line 111 at XXXXXX_Feature_Receiver.XXXXXXDataStructureFeatureFactory.CreateOrUpdateListInstances(SPWeb Web) in C:\TestBed\XXXXXX Feature Receiver Development\XXXXXX Feature Receiver\XXXXXXDataStructureFeatureFactory.vb:line 37 at XXXXXX_Feature_Receiver.XXXXXXDataStructureFeatureFactory.Initiate(SPWeb Web) in C:\TestBed\XXXXXX Feature Receiver Development\XXXXXX Feature Receiver\XXXXXXDataStructureFeatureFactory.vb:line 14 at XXXXXX_Feature_Receiver.Module1.Main() in C:\TestBed\XXXXXX Feature Receiver Development\XXXXXX Feature Receiver\Module1.vb:line 11 at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart()"

  • Not sure why it would behave differently in a Console App, but I would try saving the template with a very basic filename for the .stp

    Remove the timestamp just for testing purposes, as this could contain characters that are invalid to SharePoint.

  • Do you have the proper permissions to perform a template save to the Site Template Gallery? The identity executing the code must be site collection administrator if it mimics the user experience.

  • You will often get this error if the filename already exists at the location you are trying to save it. SaveListAsTemplate will not override an existing file. Additionally it could be an invalid character in the filename, I found this API is more restricting than the Windows FileSystem for filenames, it does not allow certain characters even though they are valid for the filesystem. In addition if it works fine within a web and not within the console try to add AllowUnsafeUpdates right before the SaveAsTemplate call since a Console app will not have a security context.

Tags
object-model list
Related questions and answers
  • . Update 1 It may be easier for me to show my code (incase of retardation) public void ProcessRequest(HttpContext context) { try { SPList list...I’m trying to write a Http Handler to generate rss xml (based on the CKS code). I want to be able to get the list/library that the end point of the url is referring to. For example if my Url...;"); } catch (Exception ex) { context.Response.Write("Error getting list from spcontext.current.list: " + ex.Message + "<br />"); } try

  • that attribute names are case-sensitive. (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\WebClients\Profile\client.config line 56) --->...\client.config line 56) at System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object... attribute 'allowInsecureTransport'. Note that attribute names are case-sensitive. (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\WebClients\Profile\client.config line 56

  • , Boolean returnStream, String method, DbAsyncResult result) at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream..., ReadOnlyCollection1&amp; activeHostedWorkflowDefinitions, ReadOnlyCollection1&amp; workflowControlMessages, List`1&amp; requestsToRedispatch) at Microsoft.ResourceManagement.Workflow.Hosting.HostActivator.RetrieveWorkflowDataForHostActivator() at Microsoft.ResourceManagement.Workflow.Hosting.HostActivator.ActivateHosts(Object source, ElapsedEventArgs e) .Net SqlClient Data

  • I have a webpart i build using WSpBuilder and it works OK. When i use Deploy from Visual Studio it installs the WSP sharepoint and add the webpart to the webpart gallery. But it seems the feature does activate the webpart but i also want to remove it when deactivating it.(So i know i need to add something to the FeatureDeactivating So i created a Feature With Reciever template and added...) { SPList list = web.Lists["Web Part Gallery"]; // go through the items in reverse //for (int i = list.ItemCount – 1; i >= 0; i–) for(int i=list.ItemCount-1; i >=0

  • In one of my SharePoint apps, I am getting this warning &amp; stacktrace over and over (with different GUIDS): since it's only one of my apps, I assume there's something in my project's code, but SPDisposeCheck returns clean, and there's nothing in the logs that point to my code. Any ideas on how I can track this down? Error I'm getting: Potentially excessive number of SPRequest objects (9) currently unreleased on thread 1. Ensure that this object or its parent (such as an SPWeb or SPSite) is being properly disposed. Allocation Id for this object

  • . The only significant thing to change on the server between yesterday and today was the installation of the Citrix Web Interface for SharePoint webparts. UPDATE: I also receive the following error...\Microsoft\Shared Tools\Web Server Extensions\12.0\WSS registry key. Repair this product by selecting it from the Add/Remove Programs menu. If I access Central Administration via a browser... DirectoryInfo(SPUtility.GetGenericSetupPath("config")).GetFiles("stsadmcommands.*.xml"); in the EnsureExtendedOperationMap() method. The reason being, I believe, because

  • and then return and get the above message. Waiting for a while can help, but it doesn't seem like even SharePoint's inactivity timeout always does the trick. And here's the strangest part - while... is causing this behavior? I can change the code to avoid it if I can figure out why it is happening. Is there any way through the SharePoint UI or APIs to "release" the document so that the original...Scenario: We have an internal application that ties Excel spreadsheets stored in a SharePoint doc lib with specific Opportunities in CRM. The user clicks on a button in the Opportunity and a Web

  • I am testing out Visual Studio 2010. I have created a sandboxed solution with a webpart. It deployed OK. I then tried adding a dll to the solution that would contain the business logic. This dll is signed with it's own strong name key. We I now deploy the solution, I get the following error when the code tries to use the business logic dll: Web Part Error: Unhandled exception was thrown by the user code wrapper's Execute method in the partial trust app domain: System.Security.SecurityException: That assembly does not allow partially trusted callers

  • We recently migrated some applications from SharePoint 2007 to SharePoint 2010. The application uses the SiteData.asmx web service. After the migration there are Access Denied errors, withtout any additional information. The following sample code reproduces the problem: var service = new SiteData(); service.Url = url + "_vti_bin/sitedata.asmx"; string web;string site;string bucket;string list;string item; service.GetURLSegments(url + "Docs/SomeDocumentLibrary/Test/testafterupdate/2007-00152-01-E.doc", out web, out bucket, out list, out item); The point is to get the listId from the url

Data information