SPChangeTokenCollection - Classe
Représente une collection d'objets SPChangeToken .
Hiérarchie d’héritage
System.Object
Microsoft.SharePoint.Administration.SPAutoSerializingObject
Microsoft.SharePoint.SPBaseCollection
Microsoft.SharePoint.SPChangeTokenCollection
Espace de noms : Microsoft.SharePoint
Assembly : Microsoft.SharePoint (dans Microsoft.SharePoint.dll)
Syntaxe
'Déclaration
Public NotInheritable Class SPChangeTokenCollection _
Inherits SPBaseCollection
'Utilisation
Dim instance As SPChangeTokenCollection
public sealed class SPChangeTokenCollection : SPBaseCollection
Remarques
Cette collection est fournie afin que vous pouvez facilement gérer les journaux de changement au niveau de l'application Web. Chaque base de données contenu dans une application Web conserve son propre journal des modifications. Si vous souhaitez un rapport de modification consolidé pour plusieurs bases de données de contenu, vous pouvez utiliser un objet SPChangeTokenCollection pour stocker les jetons de modification pour toutes les bases de données dans une collection unique. Une fois que vous avez une collection de jetons de modification, vous pouvez énumérer la collection et demandez à chaque base de données à son tour ses modifications en appelant la méthode GetChanges(SPChangeToken) . Vous pouvez également sérialiser une collection à l'aide de la méthode ToString() et le stocker sur le disque. Ultérieurement, lorsque vous souhaitez revoir les journaux de modification, vous pouvez reconstruire la collection à l'aide d'une variante du constructeur qui accepte un argument de chaîne et ensuite utiliser la collection de jetons de modification désérialisé à interroger la modification ouvre une nouvelle.
Exemples
L'exemple suivant est une application console qui interroge le journal des modifications pour chaque base de données contenu dans une application Web. À la première exécution du programme, toutes les modifications sont récupérées à partir de chaque journal. Après le traitement de chaque ensemble de modifications, le programme enregistre le dernier jeton de modification de la collection de modification à une collection SPChangeTokenCollection . Lorsque tous les journaux ont été traités, la SPChangeTokenCollection l'objet est sérialisé et la chaîne résultante est stockée dans un fichier sur disque.
Lors des exécutions suivantes du programme, le fichier de données est en lecture, la représentation sous forme de chaîne de la collection est récupérée, et l'objet SPChangeTokenCollection est reconstruit. Les jetons de modification de la collection sont ensuite utilisés pour extraire les modifications effectuées depuis la dernière exécution du programme.
Cet exemple ne fait aucune tentative pour enregistrer les informations qu'il récupère à partir des journaux de modification. Il imprime simplement la sortie dans la console. Une amélioration utile consisterait à ajouter du code pour la consolidation des modifications dans un fichier ou une base de données, où qu'ils pourraient être soumis à une analyse plus approfondie.
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
Cohérence de thread
Tous les membres statique (Partagé dans Visual Basic)s publics de ce type sont thread-safe. Cela n’est pas garanti pour les membres d’instance.
Voir aussi
Référence
SPChangeTokenCollection - Membres