Clase SPChangeTokenCollection

Representa una colección de objetos SPChangeToken .

Jerarquía de la herencia

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

Espacio de nombres:  Microsoft.SharePoint
Ensamblado:  Microsoft.SharePoint (en Microsoft.SharePoint.dll)

Sintaxis

'Declaración
Public NotInheritable Class SPChangeTokenCollection _
    Inherits SPBaseCollection
'Uso
Dim instance As SPChangeTokenCollection
public sealed class SPChangeTokenCollection : SPBaseCollection

Comentarios

Esta colección se proporciona para que puede administrar fácilmente los registros de cambios en el nivel de aplicación Web. Cada base de datos de contenido en una aplicación Web mantiene su propio registro de cambios. Si desea un informe de cambio consolidado para varias bases de datos de contenido, puede usar un objeto SPChangeTokenCollection para almacenar los tokens de cambio para todas las bases de datos en una sola colección. Una vez que haya una colección de tokens de cambio, puede enumerar la colección y pida a su vez cada base de datos para que sus cambios llamando al método GetChanges(SPChangeToken) . También puede serializar una colección mediante el método ToString() y guardarla en el disco. Más adelante, cuando desea revisar los registros de cambios, puede reconstruir la colección mediante una variación del constructor que acepta un argumento de cadena y, a continuación, use la colección de token de cambio serializar para consultar el cambio de los registros de nuevo.

Ejemplos

En el siguiente ejemplo es una aplicación de consola que consulta el registro de cambios para cada base de datos de contenido en una aplicación Web. En la primera ejecución del programa, se recuperan todos los cambios de cada registro. Después de procesar cada colección de cambios, el programa guarda el último token de cambio de la colección de cambio a una colección de SPChangeTokenCollection . Cuando se han procesado todos los registros, se serializa el objeto SPChangeTokenCollection y la cadena resultante se almacena en un archivo en el disco.

En ejecuciones subsiguientes del programa, se lee el archivo de datos, se recupera la representación de cadena de la colección y es reconstruir el objeto SPChangeTokenCollection . Los tokens de cambio en la colección, a continuación, se usan para recuperar los cambios realizados desde la última ejecución del programa.

En este ejemplo se realiza ningún intento para guardar la información que recupera de los registros de cambios. Simplemente imprime el resultado en la consola. Una mejora útil sería agregar código para consolidar los cambios en un archivo o una base de datos, donde podría ser sometidos a su análisis ulterior.

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

Seguridad para subprocesos

Los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para subprocesos. No se garantiza que los miembros de instancias sean seguros para los subprocesos.

Vea también

Referencia

Miembros SPChangeTokenCollection

Espacio de nombres Microsoft.SharePoint

ContentDatabases

SPContentDatabase

GetChanges(SPChangeToken)