Share via


SPWeb.GetChanges method (SPChangeQuery)

Obtém as alterações do log de alterações filtrado pela consulta especificada.

Namespace:  Microsoft.SharePoint
Assembly:  Microsoft.SharePoint (in Microsoft.SharePoint.dll)

Syntax

'Declaração
Public Function GetChanges ( _
    query As SPChangeQuery _
) As SPChangeCollection
'Uso
Dim instance As SPWeb
Dim query As SPChangeQuery
Dim returnValue As SPChangeCollection

returnValue = instance.GetChanges(query)
public SPChangeCollection GetChanges(
    SPChangeQuery query
)

Parâmetros

Valor retornado

Type: Microsoft.SharePoint.SPChangeCollection
As alterações que ocorreram no site com base na consulta específica. Especifique o número máximo de alterações para retornar, definindo a propriedade FetchLimit do parâmetro de consulta.

Comentários

Use este método para obter alterações em objetos específicos, em vez de todos os objetos ou somente para ações selecionadas em objetos específicos. Para obter mais informações, consulte a classe SPChangeQuery .

Dica

Por padrão, o log de alterações retém dados por 60 dias. Para alterar o período de retenção padrão, defina a propriedade ChangeLogRetentionPeriod .

Examples

O exemplo a seguir é um aplicativo de console que cria um arquivo de texto com informações sobre itens de lista que foi adicionado, excluído ou atualizado. O aplicativo chama o método GetChanges em um loop, buscando alterações em lotes até que todas as alterações foram recuperadas.

using System;
using System.IO;
using Microsoft.SharePoint;

namespace Test
{
   class ConsoleApp
   {
      static void Main(string[] args)
      {
         using (SPSite siteCollection = new SPSite("https://localhost"))
         {
            using (SPWeb webSite = siteCollection.RootWeb)
            {

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

               // object type 
               query.Item = true;

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

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

               string fileName = "ItemChanges.txt";
               StreamWriter writer = File.AppendText(fileName);

               while (true)
               {

                  SPChangeCollection changes = webSite.GetChanges(query);
                  total += changes.Count;

                  foreach (SPChangeItem change in changes)
                  {
                     // Get the list title
                     string listTitle = String.Empty;
                     string itemName = String.Empty;
                     SPList list = null;
                     try
                     {
                        list = webSite.Lists[change.ListId];
                        listTitle = list.Title;
                     }
                     catch (SPException)
                     {
                        listTitle = "Unknown";
                     }

                     // Get the item title
                     if (list != null)
                     {
                        SPListItem item = null;
                        try
                        {
                           item = list.GetItemByUniqueId(change.UniqueId);
                           itemName = item.Name;
                        }
                        catch (ArgumentException)
                        {
                           itemName = "Unknown";
                        }

                     }

                     // Write to the log
                     writer.WriteLine("\r\nDate: {0}",
                        timeZone.UTCToLocalTime(change.Time).ToString());
                     writer.WriteLine("Change: {0} item", change.ChangeType);
                     writer.WriteLine("List: {0}", listTitle);
                     writer.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;
               }

               writer.WriteLine("\r\nTotal changes = {0:#,#}", total);
               writer.Flush();
               writer.Close();

               Console.WriteLine("{0} changes written to {1}", total, fileName);
            }
         }
         Console.Write("\nPress ENTER to continue...");
         Console.ReadLine();
      }
   }
}
Imports System
Imports System.IO
Imports Microsoft.SharePoint

Module ConsoleApp
   Sub Main()
      Using siteCollection As SPSite = New SPSite("https://localhost")
         Using webSite As SPWeb = siteCollection.RootWeb

            ' Construct a query
            Dim query As New SPChangeQuery(False, False)

            ' object type
            query.Item = True

            ' change types 
            query.Add = True
            query.Delete = True
            query.Update = True

            Dim timeZone As SPTimeZone = webSite.RegionalSettings.TimeZone
            Dim total As Long = 0

            Dim fileName As String = "ItemChanges.txt"
            Dim writer As StreamWriter = File.AppendText(fileName)

            While True

               Dim changes As SPChangeCollection = webSite.GetChanges(query)
               total += changes.Count

               For Each change As SPChangeItem In changes
                  ' Get the list title
                  Dim listTitle As String = String.Empty
                  Dim itemName As String = String.Empty
                  Dim list As SPList = Nothing
                  Try
                     list = webSite.Lists(change.ListId)
                     listTitle = list.Title
                  Catch ex As SPException
                     listTitle = "Unknown"
                  End Try

                  ' Get the item title
                  If list IsNot Nothing Then
                     Dim item As SPListItem = Nothing
                     Try
                        item = list.GetItemByUniqueId(change.UniqueId) 
                        itemName = item.Name
                     Catch ex As ArgumentException
                        itemName = "Unknown"
                     End Try
                  End If

                  ' Write to the log
                  writer.WriteLine(vbCrLf + "Date: {0}", _
                                   timeZone.UTCToLocalTime(change.Time).ToString())
                  writer.WriteLine("Change: {0} item", change.ChangeType)
                  writer.WriteLine("List: {0}", listTitle)
                  writer.WriteLine("Item: {0}", itemName)
               Next change

               ' Break out of the loop when we fetch the last batch of changes
               If changes.Count < query.FetchLimit Then
                  Exit While
               End If

               ' Go get another batch of changes starting where we left off
               query.ChangeTokenStart = changes.LastChangeToken

            End While

            writer.WriteLine(vbCrLf + "Total changes = {0:#,#}", total)
            writer.Flush()
            writer.Close()

            Console.WriteLine("{0} changes written to {1}", total, fileName)

         End Using
      End Using

      Console.Write(vbCrLf + "Press ENTER to continue...")
      Console.ReadLine()

   End Sub
End Module

Ver também

Referência

SPWeb class

SPWeb members

GetChanges overload

Microsoft.SharePoint namespace

Outros recursos

Using the Change Log