Как подписываться на пользователей, применяя клиентскую объектную модель .NET в SharePoint
Узнайте, как применять возможности подписки на пользователей, используя клиентскую объектную модель .NET в SharePoint.
Зачем использовать следующие функции Люди в SharePoint?
В SharePoint, когда пользователь следит за людьми, в канале новостей пользователя отображаются записи и действия отслеживаемых пользователей. С помощью функции следующие сотрудники сосредоточиться на пользователей, которые важны пользователей, можно улучшить релевантности приложений или решений. В клиентской объектной модели .NET люди, на которых вы подписаны, представлены объектами SocialActor . Для выполнения основных задач следующие сотрудники в клиентской объектной модели .NET, используйте объект SocialFollowingManager . В этой статье описывается использование клиентской объектной модели .NET для работы с функциями следующие сотрудники.
Примечание.
Мы сосредоточимся на SocialFollowingManager , так как он объединяет основные функции для следующих пользователей и содержимого. Тем не менее объект PeopleManager содержит дополнительные функции для следующих пользователей, таких как метод AmIFollowedBy(String) и методы, которые получить следующие состояния другим пользователям.
Предварительные требования для настройки среды разработки для работы со следующими функциями Люди с помощью клиентской объектной модели SharePoint .NET
Создание консольного приложения, использующего клиентской объектной модели .NET для работы с функциями следующие сотрудники, необходимо следующее:
SharePoint с настроенным личным сайтом и профилями пользователей и личными сайтами, созданными для текущего пользователя и целевого пользователя
Visual Studio 2012
Полный доступ к приложению-службе профилей пользователей для пользователя, вошедшего в систему
Примечание.
Если вы не разрабатываете разработку на компьютере под управлением SharePoint, получите скачивание клиентских компонентов SharePoint , содержащих клиентские сборки SharePoint.
Создание консольного приложения в Visual Studio 2012
Откройте Visual Studio и в меню Файл последовательно выберите элементы Создать и Проект.
В верхней части диалогового окна Новый проект выберите .NET Framework 4.5 в раскрывающемся списке.
В списке шаблонов выберите Windows и затем выберите шаблон Консольное приложение.
Назовите проект FollowPeopleCSOMи затем нажмите кнопку ОК.
Добавьте ссылки на следующие сборки:
- Microsoft.SharePoint.Client
- Microsoft.SharePoint.ClientRuntime
- Microsoft.SharePoint.Client.UserProfiles
- Замените содержимое класса Program в примере кода на класс из следующих сценариев:
- Тестирование консольного приложения в строке меню выберите команду Отладка, Начать отладку.
Пример кода: запуск или остановка следовать за пользователями с помощью клиентской объектной модели SharePoint .NET
В следующем примере кода делает текущего пользователя запустить следующие или остановить после конечного пользователя. В нем показано, как:
Проверьте, следует ли текущий пользователь за целевым пользователем с помощью метода IsFollowed .
Получите количество пользователей, за которыми следит текущий пользователь, с помощью метода GetFollowedCount .
Начните следовать за целевым пользователем с помощью метода Follow .
Остановите подписку на целевого пользователя с помощью метода StopFollowing .
В этом примере кода используется объект SocialFollowResult , возвращаемый методом Follow , чтобы определить, следует ли начинать или прекращать подписку на целевого пользователя.
Примечание.
[!Примечание] Изменение значений заполнитель для переменных serverUrl и targetUser, прежде чем запускать код.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Social;
namespace FollowPeopleCSOM
{
class Program
{
static ClientContext clientContext;
static SocialFollowingManager followingManager;
static void Main(string[] args)
{
// Replace the following placeholder values with the target
// server URL and target user.
const string serverUrl = "http://serverName";
const string targetUser = "domainName\\\\userName";
// Get the client context.
clientContext = new ClientContext(serverUrl);
// Get the SocialFeedManager instance.
followingManager = new SocialFollowingManager(clientContext);
// Create a SocialActorInfo object to represent the target user.
SocialActorInfo actorInfo = new SocialActorInfo();
actorInfo.AccountName = targetUser;
// Find out whether the current user is following the target user.
ClientResult<bool> isFollowed = followingManager.IsFollowed(actorInfo);
// Get the information from the server.
clientContext.ExecuteQuery();
Console.WriteLine("Was the current user following the target user? {0}\\n", isFollowed.Value);
Console.Write("Initial count: ");
// Get the current count of followed people.
WriteFollowedCount();
// Try to follow the target user. 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 user.
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 people.
Console.Write("Updated count: ");
WriteFollowedCount();
Console.ReadKey();
}
// Get the count of the people who the current user is following.
static void WriteFollowedCount()
{
ClientResult<int> followedCount = followingManager.GetFollowedCount(SocialActorTypes.Users);
clientContext.ExecuteQuery();
Console.WriteLine("The current user is following {0} people.", followedCount.Value);
}
}
}
Пример кода: получение подписчиков и последующих пользователей с помощью клиентской объектной модели SharePoint .NET
Следующий пример возвращает код пользователей, которые следующие текущего пользователя, получает пользователей, которые следуют текущего пользователя и получает сведения о состоянии следующие сотрудники текущего пользователя. В нем показано, как:
Проверьте, следует ли текущий пользователь за целевым пользователем с помощью метода IsFollowed .
Получите количество пользователей, за которыми следит текущий пользователь, с помощью метода GetFollowedCount .
Получите пользователей, на которых следит текущий пользователь, с помощью метода GetFollowed .
Получение пользователей, которые следят за текущим пользователем, с помощью метода GetFollowers .
Выполните итерацию по группам людей и получить отображаемое имя каждого контакта, личные URI и рисунков URI.
Примечание.
[!Примечание] Изменение значений заполнитель для переменных serverUrl и targetUser, прежде чем запускать код.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Social;
namespace FollowPeopleCSOM
{
class Program
{
static void Main(string[] args)
{
// Replace the following placeholder values with the target
// server URL and target user.
const string serverUrl = "http://serverName";
const string targetUser = "domainName\\\\userName";
// Get the client context.
ClientContext clientContext = new ClientContext(serverUrl);
// Get the SocialFeedManager instance.
SocialFollowingManager followingManager = new SocialFollowingManager(clientContext);
// Create a SocialActorInfo object to represent the target user.
SocialActorInfo actorInfo = new SocialActorInfo();
actorInfo.AccountName = targetUser;
// Find out whether the current user is following the target user.
ClientResult<bool> isFollowed = followingManager.IsFollowed(actorInfo);
// Get the count of people who the current user is following.
ClientResult<int> followedCount = followingManager.GetFollowedCount(SocialActorTypes.Users);
// Get the people who the current user is following.
ClientResult<SocialActor[]> followedResult = followingManager.GetFollowed(SocialActorTypes.Users);
// Get the people who are following the current user.
ClientResult<SocialActor[]> followersResult = followingManager.GetFollowers();
// Get the information from the server.
clientContext.ExecuteQuery();
// Write the results to the console window.
Console.WriteLine("Is the current user following the target user? {0}\\n", isFollowed.Value);
Console.WriteLine("People who the current user is following: ({0} count)", followedCount.Value);
IterateThroughPeople(followedResult.Value);
Console.WriteLine("\\nPeople who are following the current user:");
IterateThroughPeople(followersResult.Value);
Console.ReadKey();
}
// Iterate through the people and get each person's display
// name, personal URI, and picture URI.
static void IterateThroughPeople(SocialActor[] actors)
{
foreach (SocialActor actor in actors)
{
Console.WriteLine(" - {0}", actor.Name);
Console.WriteLine("\\tPersonal URI: {0}", actor.PersonalSiteUri);
Console.WriteLine("\\tPicture URI: {0}", actor.ImageUri);
}
}
}
}