Friday, 11 January 2013

Move List Items from one List to Other in SharePoint 2010



We cannot move the list items from one list to other directly. Hence to do achieve this we need to first copy the list item to the destination list & then delete the same from the source list. The following code shows how to move list items from one list to other.

/// MoveToList is a method to move Item from Source List to Destination List
/// <param name="siteUrl">Pass Site url of SiteCollection</param>
/// <param name="Source">Pass Source List Name</param>
/// <param name="Destination">Pass Destination List Name</param>

public void MoveToList(string siteUrl, string Source, string Destination)
{

  SPQuery qry = new SPQuery();    //To query the item
  string camlquery = string.Empty;
  SPListItemCollection Srccollitem;
  SPList destlib;
  SPListItem item;
  SPListItem targetItem;
  try
  {
    using (SPSite rootSite = new SPSite(siteUrl))    //siteUrl is the URL of the site
    {
      using (SPWeb spWeb = rootSite.OpenWeb())
      {
        //The below query gets all the items whose Expiry Date column contains Date Today’s Date or previous date

        camlquery = "<Where>"
                                + "<Lt>"
                                + "<FieldRef Name='Expiry_x0020_Date' />"
                                + "<Value IncludeTimeValue='FALSE' Type='DateTime' ><Today /></Value>"
                                + "</Lt>"
                                + "</Where>";

        qry.Query = camlquery;

        ///Get the Collection of SourceListItem by Caml Query
        Srccollitem = spWeb.Lists[Source].GetItems(qry);

        ///Get the Destination List
        destlib = spWeb.Lists[Destination];

        ///Start of For Loop to move items one by one from Source List to Destination List
        for (int i = Srccollitem.Count - 1; i >= 0; i--)
        {
          item = Srccollitem[i];

        ///First add item to the destination list
          targetItem = destlib.Items.Add();
          ///Start of ForEach Loop to add value of each Field from Source to Destionation
          foreach (SPField f in item.Fields)
          {
             //Copy all except attachments.
             if (!f.ReadOnlyField && f.InternalName != "Attachments"
&& null != item[f.InternalName])
             {
                 targetItem[f.InternalName] = item[f.InternalName];
             }
          }
          ///End of ForEach Loop
          spWeb.AllowUnsafeUpdates = true;

        ///Update The Destination List
          targetItem.Update();

        ///Now once the Destination list is updated, Delete the item from the source list
          item.Delete();
          spWeb.AllowUnsafeUpdates = false;
        }
        ///End of For Loop.
      }
    }
  }
  catch (Exception ex)
  {

  }
}

Move Documents from one Library to Other in SharePoint 2010



The following code shows how to move documents from one Document Library to Other.

/// MoveToDocLib is a method to move Document from Source Library to Destination Library
/// <param name="siteUrl">Pass Site url of SiteCollection</param>
/// <param name="Source">Pass Source Library Name</param>
/// <param name="Destination">Pass Destination Library Name</param>

public void MoveToDocLib(string siteUrl, string Source, string Destination)
{
  SPQuery qry = new SPQuery();    //To query the item
  string camlquery = string.Empty;
  string destlibUrl = string.Empty;
  SPListItemCollection Srccollitem;
  SPList destlib;
  SPFile moveFile;
  try
  {
    using (SPSite rootSite = new SPSite(siteUrl)) //siteUrl is the URL of the site
    {
      using (SPWeb spWeb = rootSite.OpenWeb())
      {
        //The below query gets all the items whose Expiry Date column contains Date Today’s Date or previous date
        camlquery = "<Where>"
                     + "<Lt>"
                     + "<FieldRef Name='Expiry_x0020_Date' />"
                     + "<Value IncludeTimeValue='FALSE' Type='DateTime' ><Today /></Value>"
                     + "</Lt>"
                     + "</Where>";
         qry.Query = camlquery;
         qry.ViewAttributes = "<View Scope=\'RecursiveAll\'>";
        ///Get the Collection of SourceLibraryDocument by Caml Query
        Srccollitem = spWeb.Lists[Source].GetItems(qry);

        ///Get the Destination Library
        destlib = (SPDocumentLibrary)spWeb.Lists[Destination];
        ///Get the URL of the Destination Library
        destlibUrl = destlib.RootFolder.Url;

        ///Start of ForEach Loop to Move Document one by one from Source Library to Destination Library.
        foreach (SPListItem item in Srccollitem)
        {
          moveFile = item.File;
          moveFile.MoveTo(destlibUrl + "/" + moveFile.Name, true);
        }
        ///End of ForEach Loop
      }
    }

  }
  catch (Exception ex)
  {

  }
          
}

Read values from XML file using c# .net in SharePoint 2010

I had a requirement to get values from the XML file & perform further operation.
The following code shows how to read a XML file & populate the data from XML to data table & perform further operations.
Add the xml file to the SharePoint solution in C#.Net. Right Click Project – Select Add New Item – Select XML File.
Give the Proper name to the XML File & add the below xml code in the XML file.
<Items>

  <Field Url="http://site-name" Source="List-Library-name" Destination="List-Library-name" Type="Library"></Field>

  <Field Url="http://site-name" Source="List-Library-name" Destination="List-Library-name" Type="List"></Field>

</Items>


Now after adding the XML file to fetch the data from the XML file add the path of the XML file in the app.config to let the user access the XML file. Add the below key & value in the appSettings tag of the app.congif file.

<appSettings>

    <add key="RecordListXML" value="SiteNListDetails.xml" />

</appSettings>


private static string SiteNListDetails = ConfigurationManager.AppSettings["RecordListXML"];



///Method to get Data from XML.
public void GetDetails()
{
  DataTable dt;
  string url = string.Empty;
  string source = string.Empty;
  string destination = string.Empty;
  string type = string.Empty;
  try
  {
    ///Call Method to get the data from XML
     dt = ReadXML();
     ///Start of For Loop to get parameter to perform operation.
     for (int i = 0; i < dt.Rows.Count; i++)
    {
       ///Perform Operation.
    }
    ///End of for Loop.
   }
  catch (Exception ex)
  {
   }
}
 /// ReadXMl is a method to read values from XML File & Add values in DataTable
///Returns DataTable with values
 public DataTable ReadXML()
{
  string url = string.Empty;
  string source = string.Empty;
  string destination = string.Empty;
  string type = string.Empty;
  DataRow row;
  DataTable XMLTable= CreateXMLTableStructure();
   string xmlPath = Path.GetFullPath(Environment.CurrentDirectory) + "\\" + SiteNListDetails;
  XDocument groupsXml = XDocument.Load(xmlPath);
  try
  {
    var fields = from fieldsGroup in groupsXml.Root.Elements("Field")
    select new
    {
      url = fieldsGroup.Attribute("Url").Value,
      source = fieldsGroup.Attribute("Source").Value,
      destination = fieldsGroup.Attribute("Destination").Value,
      type = fieldsGroup.Attribute("Type").Value
    };
     ///Start of For Loop: Add row with values from xml to DataTable
     foreach (var fieldsGroup in fields)
    {
       row = XMLTable.NewRow();
      row["Url"] = fieldsGroup.url;
      row["Source"] = fieldsGroup.source;
      row["Destination"] = fieldsGroup.destination;
      row["Type"] = fieldsGroup.type;
      XMLTable.Rows.Add(row);
     }
    ///End of For Loop
  }
  catch (Exception ex)
  {
  }
  return XMLTable;
}
/// CreateXMLTableStructure is  a method to Create DataTable Structure.
///Returns DataTable Structure
public DataTable CreateXMLTableStructure()
{
  DataTable XMLTable = new DataTable();
  DataColumn url = new DataColumn("Url");
  DataColumn source = new DataColumn("Source");
  DataColumn destination = new DataColumn("Destination");
  DataColumn type = new DataColumn("Type");
  try
  {
    /// Add Columns to DataTable.
    url.DataType = System.Type.GetType("System.String");
    source.DataType = System.Type.GetType("System.String");
    destination.DataType = System.Type.GetType("System.String");
    type.DataType = System.Type.GetType("System.String");
    XMLTable.Columns.Add(url);
    XMLTable.Columns.Add(source);
    XMLTable.Columns.Add(destination);
    XMLTable.Columns.Add(type);
   }
  catch (Exception ex)
  {
   }
  return XMLTable;
}