Compartilhar via


Incluir menções, marcas e links para sites e documentos em postagens no SharePoint

Saiba como adicionar objetos SocialDataItem a postagens de microblog, que são processadas como menções, marcas ou links nos feeds sociais do SharePoint.

Em um feed social, o formulário mais simples do conteúdo de postagem contém somente texto, mas você também pode adicionar links que são processados como menções, marcas ou links para documentos, sites do SharePoint e sites. Para fazer isso, você adiciona objetos SocialDataItem à propriedade ContentItems do objeto SocialPostCreationData que define a postagem. Postagens podem conter vários links.

Observação

Para adicionar imagens, vídeos ou documentos inseridos ao conteúdo de uma postagem, adicione um objeto SocialAttachment à propriedade SocialPostCreationData.Attachment . Para obter mais informações, consulte Como inserir imagens, vídeos e documentos em postagens no SharePoint.

A API descrita neste artigo é de modelo de objeto do cliente .NET. No entanto, se você estiver usando outro API, como o JavaScript do modelo de objeto, os nomes de objeto ou a API correspondente pode ser diferente. Consulte Recursos adicionais para links para documentação para APIs relacionadas.

Pré-requisitos para usar os exemplos de código para adicionar links a uma postagem no SharePoint

Os exemplos de código deste artigo mostram como adicionar links para as postagens de microblog. Esses exemplos são de aplicativos de console que usam os seguintes assemblies do SharePoint:

  • Microsoft.SharePoint.Client

  • Microsoft.SharePoint.Client.Runtime

  • Microsoft.SharePoint.Client.UserProfilies

Para obter instruções sobre como configurar seu ambiente de desenvolvimento e criar um aplicativo de console, confira Como criar e excluir postagens e recuperar o feed social usando o modelo de objeto cliente .NET no SharePoint.

Exemplo: incluir links para sites, sites do SharePoint e documentos em uma postagem no SharePoint

O exemplo de código a seguir publica uma postagem que contém links para um site da Web, um site do SharePoint e um documento. Ele mostra como:

  • Crie objetos SocialDataItem que representam os links. Cada instância define o campo SocialDataItemType para o tipo de link, o texto exibido para o link e o URI do link.

  • Adicione espaços reservados para o texto de postagem para indicar onde o texto de exibição do link deve aparecer.

  • Adicione os objetos de link à propriedade ContentItems do objeto SocialPostCreationData usado para criar a postagem.

Observação

Atualmente, o SharePoint manipula links para sites, sites do SharePoint e documentos da mesma maneira, mas, como uma prática recomendada, escolha o tipo site e o tipo de documento para sites e documentos do SharePoint.

No feed social, clicando em um link para um site da Web, site do SharePoint ou documento abre o item em uma janela separada do navegador.

Observação

[!OBSERVAçãO] Altere os valores de espaço reservado para as variáveis de URL antes de executar o código.


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();
            }
        }
    }
}

Exemplo: mencionar alguém em uma postagem no SharePoint

O exemplo de código a seguir publica uma postagem mencionando um usuário. Ele mostra como:

  • Crie um objeto SocialDataItem para representar uma menção, que é um link para um usuário. O SocialDataItem Especifica o campo SocialDataItemType.User e o nome da conta da pessoa mencionado. Você pode definir o nome da conta usando o logon da pessoa ou o endereço de email.

  • Adicione um espaço reservado para o texto de postagem para indicar onde o nome para exibição da pessoa mencionado deve aparecer.

  • Adicione o SocialDataItem à propriedade ContentItems do objeto SocialPostCreationData usado para criar a postagem.

No feed social, clicando em um mencionam redireciona para a página sobre o da pessoa mencionado.

Observação

[!OBSERVAçãO] Altere os valores de espaço reservado para as variáveis $ serverURL e accountName antes de executar o código.


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();
            }
        }
    }
}

Exemplo: incluir uma marca em uma postagem no SharePoint

O exemplo de código a seguir publica uma postagem que inclui uma marca. Ele mostra como:

No feed social, clicando em uma marca redireciona para a página sobre o da marca. Se a marca já não existir, o servidor cria a ele.

Observação

[!OBSERVAçãO] Altere os valores de espaço reservado para as variáveis $ serverURL e tagName antes de executar o código.


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();
            }
        }
    }
}

Confira também