Tuesday, October 11, 2011

SPChangeQuery Class in SharePoint

Gets the changes to the list from the change log as filtered by the specified query.



using (SPSite siteCollection = new SPSite("http://localhost"))
         {
            using (SPWeb webSite = siteCollection.OpenWeb())
            {
               // Get a list.
               SPList list = webSite.Lists[0];

               // Construct a query.
               SPChangeQuery query = new SPChangeQuery(false,  // limit object types
                                                       false); // limit change types

               // Specify the object type. 
               query.Item = true;

               // Specify change types. 
               query.Add = true;
               query.Delete = true;
               query.Update = true;

               SPTimeZone timeZone = webSite.RegionalSettings.TimeZone;
               int total = 0;

               // Loop until we reach the end of the log.
               while (true)
               {
                  SPChangeCollection changes = list.GetChanges(query);

                  total += changes.Count;

                  // Print info about each change to the console.
                  foreach (SPChangeItem change in changes)
                  {
                     // Get the item name.
                     string itemName = String.Empty;
                     SPListItem item = null;
                     try
                     {
                        item = list.GetItemByUniqueId(change.UniqueId);
                        itemName = item.Name;
                     }
                     catch (ArgumentException)
                     {
                        itemName = "Unknown";
                     }

                     Console.WriteLine("\nDate: {0}",
                         timeZone.UTCToLocalTime(change.Time).ToString());
                     Console.WriteLine("Change: {0}", change.ChangeType);
                     Console.WriteLine("Item: {0}", itemName);

                  }

                  // Break out of loop if we have the last batch.
                  if (changes.Count < query.FetchLimit)
                     break;

                  // Otherwise, go get another batch.
                  query.ChangeTokenStart = changes.LastChangeToken;
               }

               Console.WriteLine("\nTotal of {0} changes to {1} list", total, list.Title);
            }
         }
         Console.Write("\nPress ENTER to continue...");
         Console.ReadLine();

No comments: