Share via


SPChangeTokenCollection class

Representa uma coleção de objetos SPChangeToken .

Inheritance hierarchy

System.Object
  Microsoft.SharePoint.Administration.SPAutoSerializingObject
    Microsoft.SharePoint.SPBaseCollection
      Microsoft.SharePoint.SPChangeTokenCollection

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

Syntax

'Declaração
Public NotInheritable Class SPChangeTokenCollection _
    Inherits SPBaseCollection
'Uso
Dim instance As SPChangeTokenCollection
public sealed class SPChangeTokenCollection : SPBaseCollection

Comentários

Essa coleção é fornecida para que você pode facilmente gerenciar logs de alterações no nível de aplicativo da Web. Cada banco de dados de conteúdo em um aplicativo Web mantém seu próprio log de alteração. Se você desejar um relatório consolidado de alteração para vários bancos de dados de conteúdo, você pode usar um objeto SPChangeTokenCollection para armazenar alterar tokens para todos os bancos de dados em uma única coleção. Depois que você tiver uma coleção de tokens de alteração, você pode enumerar a coleção e solicite sucessivamente suas alterações cada banco de dados chamando o método GetChanges(SPChangeToken) . Você também pode serializar uma coleção usando o método ToString() e armazená-lo em disco. Posteriormente, quando desejar rever os logs de alterações, você pode reconstruir a coleção usando uma variação do construtor que aceita um argumento de seqüência de caracteres e, em seguida, usar a coleção de token de alteração desserializado para consultar a alteração fizer novamente.

Examples

O exemplo a seguir é um aplicativo de console que consulta o log de alteração para cada banco de dados de conteúdo em um aplicativo da Web. Na primeira execução do programa, todas as alterações são recuperadas das cada log. Depois de processar cada conjunto de alterações, o programa salva o último token de alteração na coleção de alteração para uma coleção de SPChangeTokenCollection . Quando todos os logs foram processados, o objeto SPChangeTokenCollection é serializado e a cadeia de caracteres resultante é armazenada em um arquivo no disco.

Em execuções subseqüentes do programa, o arquivo de dados é lida, a representação de seqüência de caracteres da coleção é recuperada e o objeto SPChangeTokenCollection é reconstruído. Os tokens de alteração na coleção são usados para buscar as alterações feitas desde a última execução do programa.

Este exemplo não faz nenhuma tentativa de salvar as informações que ele recupera de logs de alterações. Ele simplesmente imprime a saída para o console. Uma melhoria útil seria adicionar código para consolidar as alterações em um arquivo ou banco de dados, onde pode estar sujeito a análise adicional.

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

namespace Test
{
   class ConsoleApp
   {
      private const string DATA_FILE_PATH = "ChangeTokens.dat";

      static void Main(string[] args)
      {
         // Get a collection of content databases
         SPWebApplication wa = SPWebApplication.Lookup(new Uri("https://localhost"));
         SPContentDatabaseCollection dbs = wa.ContentDatabases;

         // Get a collection of change tokens
         SPChangeTokenCollection tokens = GetTokens();

         // Process the changes for each database
         foreach (SPContentDatabase db in dbs)
         {
            // Get an Id for the current database
            SPPersistedObject o = db as SPPersistedObject;
            Guid id = o.Id;
            Console.WriteLine("\nContent database ID = {0}", id.ToString());

            // Create a query.
            SPChangeQuery query = new SPChangeQuery(true, true);

            /* Get the starting token. 
             * Note that if the token is not
             * found, the indexer returns null.
             * Passing a null token fetches changes
             * from the beginning of the log.
             */
            query.ChangeTokenStart = tokens[id];

            while (true)
            {
               // Get a batch of changes
               SPChangeCollection changes = db.GetChanges(query);

               // Process them
               foreach (SPChange change in changes)
               {
                  Console.WriteLine("Date: {0}  Type of object: {1}  Type of change: {2}",
                     change.Time.ToShortDateString(), change.GetType().ToString(), change.ChangeType);
               }

               // If this is the last batch, exit
               if (changes.Count < query.FetchLimit)
               {
                  // Save the last token as a starting point for the next run
                  tokens.Add(changes.LastChangeToken, true);
                  break;
               }
               else
               {                
                  // Starting point for next batch
                  query.ChangeTokenStart = changes.LastChangeToken;
               }
            }
         }

         // Persist the token collection
         SaveTokens(tokens);

         Console.Write("\nPress ENTER to continue...");
         Console.ReadLine();
      }

      static SPChangeTokenCollection GetTokens()
      {
         SPChangeTokenCollection tokens = new SPChangeTokenCollection();

         // If we have tokens from the last run, use them
         if (File.Exists(DATA_FILE_PATH))
         {
            using (FileStream fs = File.OpenRead(DATA_FILE_PATH))
            {
               BinaryReader br = new BinaryReader(fs);
               try
               {
                  string s = br.ReadString();
                  // Construct a change token from string
                  tokens = new SPChangeTokenCollection(s);
               }
               catch (EndOfStreamException e)
               {
                  // No serialized string, so do nothing
               }
               finally
               {
                  br.Close();
               }
            }
         }

         return tokens;
      }

      static void SaveTokens(SPChangeTokenCollection tokens)
      {
         using (FileStream fs = File.Create(DATA_FILE_PATH))
         {
            // Serialize the tokens
            BinaryWriter bw = new BinaryWriter(fs);
            string s = tokens.ToString();
            bw.Write(s);

            // flush and close
            bw.Flush();
            bw.Close();
         }
      }
   }
}
Imports System
Imports System.IO
Imports Microsoft.SharePoint
Imports Microsoft.SharePoint.Administration

Module ConsoleApp

   Private Const DATA_FILE_PATH As String = "ChangeTokens.dat"

   Sub Main()

      ' Get a collection of content databases
      Dim wa As SPWebApplication = SPWebApplication.Lookup(New Uri("https://localhost"))
      Dim dbs As SPContentDatabaseCollection = wa.ContentDatabases

      ' Get a collection of change tokens
      Dim tokens As SPChangeTokenCollection = GetTokens()

      ' Process the changes for each database
      Dim db As SPContentDatabase
      For Each db In dbs
         ' Get an Id for the current database
         Dim o As SPPersistedObject = CType(db, SPPersistedObject)
         Dim id As Guid = o.Id
         Console.WriteLine(vbCrLf + "Content database ID = {0}", id.ToString())

         ' Create a query
         Dim query As New SPChangeQuery(True, True)

         ' Get the starting token. 
         ' Note that if the token is not
         ' found, the indexer returns a null value.
         ' Passing a null token fetches changes
         ' from the beginning of the log.
         query.ChangeTokenStart = tokens(id)

         While (True)
            ' Get a batch of changes
            Dim changes As SPChangeCollection = db.GetChanges(query)

            ' Process them
            Dim change As SPChange
            For Each change In changes
               Console.WriteLine("Date: {0}  Type of object: {1}  Type of change: {2}", _
                     change.Time.ToShortDateString(), change.GetType().ToString(), change.ChangeType)
            Next change

            ' If this is the last batch, exit
            If changes.Count < query.FetchLimit Then
               ' Save the last token as a starting point for the next run
               tokens.Add(changes.LastChangeToken, True)
               Exit While
            Else
               ' Starting point for next batch
               query.ChangeTokenStart = changes.LastChangeToken
            End If

         End While

      Next db

      'Persist the token collection
      SaveTokens(tokens)

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

   End Sub

   Function GetTokens() As SPChangeTokenCollection

      Dim tokens As SPChangeTokenCollection = New SPChangeTokenCollection()

      ' If we have tokens from the last run, use them
      If File.Exists(DATA_FILE_PATH) Then
         Using fs As FileStream = File.OpenRead(DATA_FILE_PATH)
            Dim br As BinaryReader = New BinaryReader(fs)
            Try
               Dim s As String = br.ReadString()
               ' Construct a change token from string
               tokens = New SPChangeTokenCollection(s)
            Catch e As EndOfStreamException
               ' No serialized string, so do nothing
            Finally
               br.Close()
            End Try
         End Using
      End If

      Return tokens
   End Function

   Sub SaveTokens(ByRef tokens As SPChangeTokenCollection)
      Using fs As FileStream = File.Create(DATA_FILE_PATH)
         ' Serialize the tokens
         Dim bw As BinaryWriter = New BinaryWriter(fs)
         Dim s As String = tokens.ToString()
         bw.Write(s)

         ' flush and close
         bw.Flush()
         bw.Close()
      End Using
   End Sub

End Module

Thread safety

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Ver também

Referência

SPChangeTokenCollection members

Microsoft.SharePoint namespace

ContentDatabases

SPContentDatabase

GetChanges(SPChangeToken)