Compartilhar via


Crie tipos de conteúdo do SharePoint usando CSOM

Você pode usar o exemplo Core.SPD para criar programaticamente colunas de sites e tipos de conteúdo e vinculá-los.

Você também pode usar as APIs do CSOM do SharePoint, disponíveis no SDK de Componentes do Cliente do SharePoint Server 2013 para adicionar um identificador de tipo de conteúdo específico e localizar tipos de conteúdo, listas e títulos de sites.

Antes de começar

Para começar, faça o download do exemplo Core.SPD no projeto Padrões e Práticas de Desenvolvedores do Office 365 no GitHub.

Observação

The code in this article is provided as-is, without warranty of any kind, either express or implied, including any implied warranties of fitness for a particular purpose, merchantability, or non-infringement.

Criar tipos de conteúdo e colunas de site

O exemplo de código a seguir mostra como criar um tipo de conteúdo usando a classe ContentTypeCreationInformation, incluindo a maneira de configurar a ID.

ContentTypeCollection contentTypes = web.ContentTypes;
cc.Load(contentTypes);
cc.ExecuteQuery();

foreach (var item in contentTypes)
{
  if (item.StringId == "0x0101009189AB5D3D2647B580F011DA2F356FB2")
    return;
}

// Create a Content Type Information object.
ContentTypeCreationInformation newCt = new ContentTypeCreationInformation();
// Set the name for the content type.
newCt.Name = "Contoso Document";
// Inherit from oob document - 0x0101 and assign. 
newCt.Id = "0x0101009189AB5D3D2647B580F011DA2F356FB2";
// Set content type to be available from specific group.
newCt.Group = "Contoso Content Types";
// Create the content type.
ContentType myContentType = contentTypes.Add(newCt);
cc.ExecuteQuery();

Using AddFieldAsXml you can add fields to the FieldCollection of a site collection:
FieldCollection fields = web.Fields;
cc.Load(fields);
cc.ExecuteQuery();

string FieldAsXML = @"<Field ID='{4F34B2ED-9CFF-4900-B091-4C0033F89944}' Name='ContosoString' DisplayName='Contoso String' Type='Text' Hidden='False' Group='Contoso Site Columns' Description='Contoso Text Field' />";
Field fld = fields.AddFieldAsXml(FieldAsXML, true, AddFieldOptions.DefaultValue);
cc.Load(fields);
cc.Load(fld);
cc.ExecuteQuery();


Vincule os campos ao tipo de conteúdo usando as classes FieldLinkCollection e FieldLinkCreationInformation.

FieldCollection fields = web.Fields;
Field fld = fields.GetByInternalNameOrTitle("ContosoString");
cc.Load(fields);
cc.Load(fld);
cc.ExecuteQuery();

FieldLinkCollection refFields = myContentType.FieldLinks;
cc.Load(refFields);
cc.ExecuteQuery();

foreach (var item in refFields)
{
  if (item.Name == "ContosoString")
    return;
  }

FieldLinkCreationInformation link = new FieldLinkCreationInformation();
link.Field = fld;
myContentType.FieldLinks.Add(link);
myContentType.Update(true);
cc.ExecuteQuery();

Traduzir tipos de conteúdo, listas e títulos de sites

Use o seguinte código para traduzir o título e a descrição do site.

web.TitleResource.SetValueForUICulture("fi-FI", "Kielikäännä minut");
web.DescriptionResource.SetValueForUICulture("fi-FI", "Kielikäännetty saitti");


Para obter uma lista, use a mesma abordagem de um site.

list.TitleResource.SetValueForUICulture("fi-FI", "Kielikäännä minut");
list.DescriptionResource.SetValueForUICulture("fi-FI", "Tämä esimerkki näyttää miten voit kielikääntää listoja.");


Para tipos de conteúdo, você tem a opção de localizar o nome e a descrição. Para campos, você pode localizar os valores de título e descrição.

myContentType.NameResource.SetValueForUICulture("fi-FI", "Contoso Dokumentti");
myContentType.DescriptionResource.SetValueForUICulture("fi-FI", "Tämä on geneerinen Contoso dokumentti.");

fld.TitleResource.SetValueForUICulture("fi-FI", "Contoso Teksti");
fld.DescriptionResource.SetValueForUICulture("fi-FI", "Tää on niiku Contoso metadatalle.");

Criar colunas de site e tipos de conteúdo de documento

O exemplo a seguir mostra como criar tipos de conteúdo de documento e, em seguida, associar um modelo de documento ao tipo de conteúdo.

Este exemplo adiciona um novo tipo de conteúdo chamado Contoso Document ao conjunto de sites. Esse tipo de conteúdo tem um modelo personalizado associado a ele quando um novo documento é criado.

ContentType ct = web.ContentTypes.GetById("0x0101009189AB5D3D2647B580F011DA2F356FB2");
            cc.Load(ct); cc.ExecuteQuery();
            string ctFolderServerRelativeURL = "_cts/" + ct.Name;
            Folder ctFolder = web.GetFolderByServerRelativeUrl(ctFolderServerRelativeURL);
            cc.Load(ctFolder);
            cc.ExecuteQuery();

            string path = @"C:\Data\Test Documents\Doc CT File.docx";
            string fileName = System.IO.Path.GetFileName(path);
            byte[] filecontent = System.IO.File.ReadAllBytes(path);

            using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.Open))
            {
                FileCreationInformation newFile = new FileCreationInformation();
                newFile.Content = filecontent;
                newFile.Url = ctFolderServerRelativeURL + "/" + fileName;

                Microsoft.SharePoint.Client.File uploadedFile = ctFolder.Files.Add(newFile);
                cc.Load(uploadedFile);
                cc.ExecuteQuery();
                //Microsoft.SharePoint.Client.File.SaveBinaryDirect(clientContext, ctFolderServerRelativeURL + "/" + fileName, fs, true);

                
                cc.Load(ct); cc.ExecuteQuery();
                ct.DocumentTemplate = fileName;
                ct.Update(false);
                cc.Load(ct); cc.ExecuteQuery();
                Console.WriteLine("Content type updates");
            }

Confira também