Tuesday, August 24, 2010

SharePoint - Populating list data during deployments

Usual requirement in SharePoint or in any deployments, is to preconfigure the destination environments with required data. For example, there could be a master list which is being used by other web parts. During the development we put all the data into the list manually and test our web parts. So if these web parts are moved to either Test,Stage or Production environments, we need to make sure the lists are provisioned along with the necessary data for web parts to function. Recently, we had a similar requirement and we had to move about 200 list items. So I thought of using a FeatureActivated event to provision the list and also to populate the list. The following the sequence of steps used for to achieve this.

  1. Export the list data from source environment as a CSV (Comma Seperated Value) file.
  2. Using Feature's elements.xml upload the file to masterpage gallery. We need to write a module which has Url="_catalogs/masterpage" to provision the CSV file into the master page gallery. This is shown below
  3. <Module Name="MasterPages" Url="_catalogs/masterpage" Path="" RootWebOnly="TRUE">
        <!--Assets into master page gallery-->
        <File Url="ListData.csv" name="[folder]/ListData.csv" Type="GhostableInLibrary" />
  4. Write FeatureActivated event, to get access to the file and create list items.
    1. Get access to the RootWeb using SPSite.RootWeb
    2. Get access to the file and loop through each CSV file in the file as below
      SPFile file = web.GetFile("_catalogs/masterpage/[folder]/ListData.csv");
      using (StreamReader reader = new StreamReader(file.OpenBinaryStream()))
          string line;
          char[] splitter = { ',' };
          SPList list1 = web.Lists["ListName"];
          SPListItem listItem1;
          while ((line = reader.ReadLine()) != null)
                  string[] itemValues = line.Split(splitter);
                  if (itemValues[0].ToString().Trim().Length != 0)
                      //If data needs to be changed in the destination list, this is the place.
                      //For example, from test url to production url
                      listItem1["ColumnName"] = itemValues[0].ToString();
                  listItem1 = list1.Items.Add();
              catch (Exception ex)
                  //Ignore error and continue to process next item

NOTE: Please note that this code does not verify, nor create the list. We need to provision the list first before this code can be executed. Also, ideally we should delete the list, which is not done in the above code.

No comments:

Post a Comment