Как добавлять в записи упоминания, теги и ссылки на сайты и документы в SharePoint
Узнайте, как добавлять в записи микроблога объекты SocialDataItem, которые обрабатываются в веб-каналах социальных медиа SharePoint как упоминания, теги или ссылки.
В социальных веб-канал простейшей формой post контента содержит только текст, но также можно добавлять ссылки, которые отображаются в виде упоминания теги и ссылки на веб-сайты, сайты SharePoint и документы. Для этого добавьте объекты SocialDataItem в свойство ContentItems объекта SocialPostCreationData , определяющего запись. Публикации о может содержать несколько ссылок.
Примечание.
Чтобы добавить внедренные изображения, видео или документы в содержимое публикации, добавьте объект SocialAttachment в свойство SocialPostCreationData.Attachment . Дополнительные сведения см. в статье Практическое руководство. Внедрение изображений, видео и документов в записи в SharePoint.
API, описанных в этой статье от клиентской объектной модели .NET. Тем не менее если вы используете другой API, такие как JavaScript объектной модели, имена объектов или соответствующий интерфейс API может отличаться. Ссылки на документацию по связанным API см. в разделе Дополнительные ресурсы .
Предварительные требования для использования примеров кода для добавления ссылок на публикацию в SharePoint
Примеры кода в этой статье показано, как добавлять ссылки на микроблога публикации. В этих примерах: от консольных приложений, использующих на следующие сборки SharePoint:
Microsoft.SharePoint.Client;
Microsoft.SharePoint.Client.Runtime
Microsoft.SharePoint.Client.UserProfilies
Инструкции по настройке среды разработки и созданию консольного приложения см. в статье Практическое руководство. Создание и удаление записей и получение веб-канала социальных сетей с помощью клиентской объектной модели .NET в SharePoint.
Пример. Включение ссылок на веб-сайты, сайты SharePoint и документы в публикацию в SharePoint
В следующем примере кода публикует сообщение, которое содержит ссылки на веб-сайт, сайт SharePoint и документа. В нем показано, как:
Создание объектов SocialDataItem , представляющих ссылки. Каждый экземпляр задает поле SocialDataItemType типа связи, отображаемый текст для ссылки и связи URI.
Добавьте заполнители текста post, чтобы указать, где должны отображаться отображаемый текст.
Добавьте объекты ссылки в свойство ContentItems объекта SocialPostCreationData , используемого для создания записи.
Примечание.
В настоящее время SharePoint обрабатывает ссылки на веб-сайты, сайты SharePoint и документы аналогичным образом, но рекомендуется выбрать тип сайта и тип документа для сайтов и документов SharePoint.
Социальные веб-канала щелкнув ссылку на веб-сайта, сайт SharePoint или документ откроется элемента в отдельном окне браузера.
Примечание.
[!Примечание] Изменение значений заполнитель для переменных URL-адрес, прежде чем запускать код.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Social;
namespace IncludeLinksInPost
{
class Program
{
static void Main(string[] args)
{
// Replace the following placeholder values with the actual values.
const string serverUrl = "http://serverName/siteName/";
const string websiteLinkUrl = "http://bing.com";
const string siteLinkUrl = "http://serverName/siteName/";
const string docLinkUrl = "http://serverName/Shared%20Documents/docName.txt";
// Define the link to a website that you want to include in the post.
SocialDataItem websiteLink = new SocialDataItem
{
ItemType = SocialDataItemType.Link,
Text = "link to a website",
Uri = websiteLinkUrl
};
// Define the link to a SharePoint site that you want to include in the post.
SocialDataItem siteLink = new SocialDataItem
{
ItemType = SocialDataItemType.Site,
Text = "link to a SharePoint site",
Uri = siteLinkUrl
};
// Define the link to a document that you want to include in the post.
SocialDataItem docLink = new SocialDataItem
{
ItemType = SocialDataItemType.Document,
Text = "link to a document",
Uri = docLinkUrl
};
// Add the links to the post's creation data.
// Put placeholders ({n}) where you want the links to appear in the post text,
// and then add the links to the post's content items.
SocialPostCreationData postCreationData = new SocialPostCreationData();
postCreationData.ContentText = "Check out this {0}, {1}, and {2}.";
postCreationData.ContentItems = new SocialDataItem[3] {
websiteLink,
siteLink,
docLink
};
try
{
// Get the context and the SocialFeedManager instance.
ClientContext clientContext = new ClientContext(serverUrl);
SocialFeedManager feedManager = new SocialFeedManager(clientContext);
// Publish the post. This is a root post to the user's feed, so specify
// null for the targetId parameter.
feedManager.CreatePost(null, postCreationData);
clientContext.ExecuteQuery();
Console.Write("The post was published.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.Write("Error publishing the post: " + ex.Message);
Console.ReadLine();
}
}
}
}
Пример. Упоминание пользователя в публикации в SharePoint
В следующем примере кода публикует post, в котором упомянут пользователь. В нем показано, как:
Создайте объект SocialDataItem для представления упоминания, которое является ссылкой на пользователя. SocialDataItem указывает поле SocialDataItemType.User и имя учетной записи упомянутый человека. Имя учетной записи можно задать с помощью для входа пользователя или адрес электронной почты.
Добавьте заполнитель текста post, чтобы указать, которой должен отображаться отображаемое имя упомянутый контакта.
Добавьте SocialDataItem в свойство ContentItems объекта SocialPostCreationData , используемого для создания записи.
Социальные веб-канала нажав кнопку упоминание перенаправляет страницы упомянутый пользователя о.
Примечание.
[!Примечание] Изменение значений заполнитель для переменных serverURL и accountName, прежде чем запускать код.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Social;
namespace IncludeMentionInPost
{
class Program
{
static void Main(string[] args)
{
// Replace the following placeholder values with the actual values.
const string serverUrl = "http://serverName/siteName/";
const string accountName = @"domain\\name or email address";
// Define the mention link that you want to include in the post.
SocialDataItem userMentionLink = new SocialDataItem
{
ItemType = SocialDataItemType.User,
AccountName = accountName
};
// Add the mention to the post's creation data.
// Put a placeholder ({0}) where you want the mention to appear in the post text,
// and then add the mention to the post's content items.
SocialPostCreationData postCreationData = new SocialPostCreationData();
postCreationData.ContentText = "{0} does great work!";
postCreationData.ContentItems = new SocialDataItem[1] { userMentionLink, };
try
{
// Get the context and the SocialFeedManager instance.
ClientContext clientContext = new ClientContext(serverUrl);
SocialFeedManager feedManager = new SocialFeedManager(clientContext);
// Publish the post. This is a root post to the user's feed, so specify
// null for the targetId parameter.
feedManager.CreatePost(null, postCreationData);
clientContext.ExecuteQuery();
Console.Write("The post was published.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.Write("Error publishing the post: " + ex.Message);
Console.ReadLine();
}
}
}
}
Пример. Добавление тега в публикацию в SharePoint
В следующем примере кода публикует сообщение, которое содержит тег. В нем показано, как:
Создайте объект SocialDataItem для представления тега. SocialDataItem указывает поле SocialDataItemType.Tag и имя тега, который должен содержать # символов.
Добавьте заполнитель текста post, чтобы указать, где должны отображаться тега.
Добавьте SocialDataItem в свойство ContentItems объекта SocialPostCreationData , используемого для создания записи.
Социальные веб-канала нажав кнопку тега будет перенаправлять тег о страницу. Если тег еще не существует, сервер создает его.
Примечание.
[!Примечание] Изменение значений заполнитель для переменных serverURL и tagName, прежде чем запускать код.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Social;
namespace IncludeTagInPost
{
class Program
{
static void Main(string[] args)
{
// Replace the following placeholder values with the actual values.
const string serverUrl = "http://serverName/siteName/";
const string tagName = "#" + "tagName";
// Define the link to a tag that you want to include in the post. If the tag is new, the
// server adds it to the tags collection.
SocialDataItem tagLink = new SocialDataItem
{
ItemType = SocialDataItemType.Tag,
Text = tagName
};
// Add the tag to the post's creation data.
// Put a placeholder ({0}) where you want the tag to appear in the post text,
// and then add the tag to the post's content items.
SocialPostCreationData postCreationData = new SocialPostCreationData();
postCreationData.ContentText = "I like {0}.";
postCreationData.ContentItems = new SocialDataItem[1] { tagLink };
try
{
// Get the context and the SocialFeedManager instance.
ClientContext clientContext = new ClientContext(serverUrl);
SocialFeedManager feedManager = new SocialFeedManager(clientContext);
// Publish the post. This is a root post to the user's feed, so specify
// null for the targetId parameter.
feedManager.CreatePost(null, postCreationData);
clientContext.ExecuteQuery();
Console.Write("The post was published.");
Console.ReadLine();
}
catch (Exception ex)
{
Console.Write("Error publishing the post: " + ex.Message);
Console.ReadLine();
}
}
}
}
См. также
SocialPostCreationData и SocialDataItem в клиентской объектной модели
SocialPostCreationData и SocialDataItem в объектной модели JavaScript
Справочные материалы по REST API каналов социальных сетей для SharePoint
SPSocialPostCreationData и SPSocialDataItem в серверной объектной модели