Как подписываться на документы и сайты, используя клиентскую объектную модель .NET в SharePoint
Узнайте, как применять возможности подписки на контент, используя клиентскую объектную модель .NET в SharePoint.
Использование клиентской объектной модели .NET для подписка на контент
Пользователи SharePoint могут следить за документами, сайтами и тегами, могут следовать за документами, сайтами и тегами, чтобы получать обновления о элементах в своих каналах новостей и быстро открывать отслеживаемые документы и сайты. Клиентская объектная модель .NET можно использовать в вашем приложении или решение, которое требуется запустить следующие материалы, остановите следующие материалы и получить отслеживаемого содержимого от имени текущего пользователя. В этой статье описывается создание консольного приложения, использующего клиентской объектной модели .NET для работы с контента следующие функции для документов и сайтов.
Основные интерфейсы API для контента следующие задачи являются следующие объекты:
SocialFollowingManager предоставляет методы для управления пользовательского списка число субъектов.
SocialActor представляет документ, сайта или тег, сервер возвращает в ответ на запрос на стороне клиента.
SocialActorInfo указывает документ, сайта или тега в запросах со стороны клиента к серверу.
Microsoft.SharePoint.Client.Social.SocialActorType и Microsoft.SharePoint.Client.Social.SocialActorTypes укажите типы контента в запросах со стороны клиента к серверу.
Примечание.
[!Примечание] Также использовать эти API-интерфейсы для задачи следующие сотрудники, но GetSuggestions и GetFollowers методы, доступные из поддерживают только SocialFollowingManager , отслеживаемые пользователи не контента. Дополнительные сведения об использовании SocialFollowingManager см. в разделах Отслеживание содержимого в SharePoint и Подписка на пользователей в SharePoint. Примеры кода, показывающие, как следовать за людьми, см. в статье Практическое руководство. Отслеживание пользователей с помощью клиентской объектной модели .NET в SharePoint.
Предварительные требования для настройки среды разработки для работы с функциями следующего содержимого с помощью клиентской объектной модели SharePoint .NET
Создание консольного приложения, использующего клиентской объектной модели .NET для работы с контента следующие функции для документов и сайты, необходимо следующее:
SharePoint с настроенным моим сайтом, с сайтом личного сайта, созданным для текущего пользователя, и документом, отправленным в библиотеку документов SharePoint
Visual Studio 2012
Полный доступ к приложению-службе профилей пользователей для пользователя, вошедшего в систему
Примечание.
Если вы не выполняете разработку на компьютере с SharePoint, получите скачивание клиентских компонентов SharePoint , содержащего клиентские сборки SharePoint.
Создание консольного приложения для работы с функциями следующего содержимого с помощью клиентской объектной модели SharePoint .NET
В меню Visual Studio выберите пункт Файл, Создать, затем Проект.
В верхней части диалогового окна Новый проект выберите .NET Framework 4.5 в раскрывающемся списке.
В списке шаблонов выберите Windows и затем выберите шаблон Консольное приложение.
Назовите проект FollowContentCSOMи затем нажмите кнопку ОК.
Добавьте ссылки на следующие сборки:
- Microsoft.SharePoint.Client
- Microsoft.SharePoint.ClientRuntime
- Microsoft.SharePoint.Client.UserProfiles
- Замените содержимое класса Program в примере кода на класс из следующих сценариев:
- Тестирование консольного приложения в строке меню выберите команду Отладка, Начать отладку.
Пример кода: запуск и остановка следующего содержимого с помощью клиентской объектной модели SharePoint .NET
В следующем примере кода делает текущего пользователя запустить следующие или остановить после конечного элемента. В нем показано, как:
Проверьте, следует ли текущий пользователь за определенным документом или сайтом с помощью метода IsFollowed .
Начните следить за документом или сайтом с помощью метода Follow .
Остановите подписку на документ или сайт с помощью метода StopFollowing .
Получите количество документов или сайтов, на которые следит текущий пользователь, с помощью метода GetFollowedCount .
В этом примере кода используется объект SocialFollowResult , возвращаемый методом Follow , чтобы определить, следует ли начинать или прекращать отслеживание целевого элемента.
Примечание.
[!Примечание] Изменение значений заполнитель для переменных serverUrl и contentUrl, прежде чем запускать код. Чтобы использовать вместо документ на сайт, используйте переменные, которые закомментированы.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Social;
namespace FollowContentCSOM
{
class Program
{
static ClientContext clientContext;
static SocialFollowingManager followingManager;
static void Main(string[] args)
{
// Replace the following placeholder values with the URL of the target
// server and target document (or site).
const string serverUrl = "http://serverName";
const string contentUrl = @"http://serverName/libraryName/fileName";
const SocialActorType contentType = SocialActorType.Document;
// Do not use a trailing '/' for a subsite.
//const string contentUrl = @"http://serverName/subsiteName";
//const SocialActorType contentType = SocialActorType.Site;
// Get the client context.
clientContext = new ClientContext(serverUrl);
// Get the SocialFeedManager instance.
followingManager = new SocialFollowingManager(clientContext);
// Create a SocialActorInfo object to represent the target item.
SocialActorInfo actorInfo = new SocialActorInfo();
actorInfo.ContentUri = contentUrl;
actorInfo.ActorType = contentType;
// Find out whether the current user is following the target item.
ClientResult<bool> isFollowed = followingManager.IsFollowed(actorInfo);
// Get the information from the server.
clientContext.ExecuteQuery();
Console.WriteLine("Was the current user following the target {0}? {1}\\n",
actorInfo.ActorType.ToString().ToLower(), isFollowed.Value);
Console.Write("Initial count: ");
// Get the current count of followed items.
WriteFollowedCount(actorInfo.ActorType);
// Try to follow the target item. If the result is OK, then
// the request succeeded.
ClientResult<SocialFollowResult> result = followingManager.Follow(actorInfo);
clientContext.ExecuteQuery();
// If the result is AlreadyFollowing, then stop following
// the target item.
if (result.Value == SocialFollowResult.AlreadyFollowing)
{
followingManager.StopFollowing(actorInfo);
clientContext.ExecuteQuery();
}
// Handle other SocialFollowResult return values.
else if (result.Value == SocialFollowResult.LimitReached
|| result.Value == SocialFollowResult.InternalError)
{
Console.WriteLine(result.Value);
}
// Get the updated count of followed items.
Console.Write("Updated count: ");
WriteFollowedCount(actorInfo.ActorType);
Console.ReadKey();
}
// Get the count of the items that the current user is following.
static void WriteFollowedCount(SocialActorType type)
{
// Set the parameter for the GetFollowedCount method, and
// handle the case where the item is a site.
SocialActorTypes types = SocialActorTypes.Documents;
if (type != SocialActorType.Document)
{
types = SocialActorTypes.Sites;
}
ClientResult<int> followedCount = followingManager.GetFollowedCount(types);
clientContext.ExecuteQuery();
Console.WriteLine("{0} followed {1}", followedCount.Value, types.ToString().ToLower());
}
}
}
Пример кода: получение последующего содержимого с помощью клиентской объектной модели SharePoint .NET
В следующем примере кода получает документов и сайтов, что текущий пользователь имеет следующие и получает сведения о следующих контента состояния пользователя. В нем показано, как:
Проверьте, следует ли текущий пользователь целевому документу и сайту с помощью метода IsFollowed .
Получите количество документов и сайтов, на которые следит текущий пользователь, с помощью метода GetFollowedCount .
Получите документы и сайты, на которые следит текущий пользователь, с помощью метода GetFollowed .
Выполните итерацию по группы содержимого и получение каждого элемента имя контента URI и URI.
Примечание.
[!Примечание] Измените значение заполнитель для переменных serverUrl, docContentUrlи siteContentUrl, прежде чем запускать код.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Social;
namespace FollowContentCSOM
{
class Program
{
static void Main(string[] args)
{
// Replace the following placeholder values with the URLs of
// the target server, document, and site.
const string serverUrl = "http://serverName";
const string docContentUrl = @"http://serverName/libraryName/fileName";
const string siteContentUrl = @"http://serverName/subsiteName"; // do not use a trailing '/' for a subsite
// Get the client context.
ClientContext clientContext = new ClientContext(serverUrl);
// Get the SocialFollowingManager instance.
SocialFollowingManager followingManager = new SocialFollowingManager(clientContext);
// Create SocialActorInfo objects to represent the target
// document and site.
SocialActorInfo docActorInfo = new SocialActorInfo();
docActorInfo.ContentUri = docContentUrl;
docActorInfo.ActorType = SocialActorType.Document;
SocialActorInfo siteActorInfo = new SocialActorInfo();
siteActorInfo.ContentUri = siteContentUrl;
siteActorInfo.ActorType = SocialActorType.Site;
// Find out whether the current user is following the target
// document and site.
ClientResult<bool> isDocFollowed = followingManager.IsFollowed(docActorInfo);
ClientResult<bool> isSiteFollowed = followingManager.IsFollowed(siteActorInfo);
// Get the count of documents and sites that the current
// user is following.
ClientResult<int> followedDocCount = followingManager.GetFollowedCount(SocialActorTypes.Documents);
ClientResult<int> followedSiteCount = followingManager.GetFollowedCount(SocialActorTypes.Sites);
// Get the documents and the sites that the current user
// is following.
ClientResult<SocialActor[]> followedDocResult = followingManager.GetFollowed(SocialActorTypes.Documents);
ClientResult<SocialActor[]> followedSiteResult = followingManager.GetFollowed(SocialActorTypes.Sites);
// Get the information from the server.
clientContext.ExecuteQuery();
// Write the results to the console window.
Console.WriteLine("Is the current user following the target document? {0}", isDocFollowed.Value);
Console.WriteLine("Is the current user following the target site? {0}", isSiteFollowed.Value);
if (followedDocCount.Value > 0)
{
IterateThroughContent(followedDocCount.Value, followedDocResult.Value);
} if (followedSiteCount.Value > 0)
{
IterateThroughContent(followedSiteCount.Value, followedSiteResult.Value);
}
Console.ReadKey();
}
// Iterate through the items and get each item's display
// name, content URI, and absolute URI.
static void IterateThroughContent(int count, SocialActor[] actors)
{
SocialActorType actorType = actors[0].ActorType;
Console.WriteLine("\\nThe current user is following {0} {1}s:", count, actorType.ToString().ToLower());
foreach (SocialActor actor in actors)
{
Console.WriteLine(" - {0}", actor.Name);
Console.WriteLine("\\tContent URI: {0}", actor.ContentUri);
Console.WriteLine("\\tURI: {0}", actor.Uri);
}
}
}
}