Crear tipos de contenido de Sharepoint con CSOM
Puede usar la muestra Core.SPD para crear columnas de sitio y tipos de contenido mediante programación y vincularlos conjuntamente.
También puede usar las API CSOM de SharePoint, disponibles en el SDK de componentes de cliente de SharePoint Server 2013, para agregar un identificador de tipo de contenido específico y localizar tipos de contenido, listas y títulos de los sitios.
Antes de empezar
Para empezar, descargue el ejemplo Core.SPD desde el proyecto Modelos y prácticas de desarrollo de Office 365 en GitHub.
Nota:
El código de este artículo se proporciona tal cual, sin garantía de ningún tipo, expresa o implícita, incluidas las garantías implícitas de aptitud para un propósito particular, comerciabilidad o ausencia de infracción.
Crear tipos de contenido y columnas de sitio
En el siguiente ejemplo se muestra cómo crear un tipo de contenido mediante la clase ContentTypeCreationInformation, incluida la configuración del 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 los campos con el tipo de contenido mediante las clases FieldLinkCollection y 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();
Localice tipos de contenido, listas y títulos de los sitios
Use el código siguiente para localizar el título y la descripción del sitio.
web.TitleResource.SetValueForUICulture("fi-FI", "Kielikäännä minut");
web.DescriptionResource.SetValueForUICulture("fi-FI", "Kielikäännetty saitti");
Use el mismo enfoque para una lista y para un sitio.
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 contenido, tiene la opción de traducir el nombre y la descripción. Para los campos, puede localizar los valores de título y descripción.
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.");
Crear tipos de contenido y columnas de sitio de documento
En este ejemplo, se muestra cómo crear tipos de contenido de documento y, después, asociar una plantilla de documento al tipo de contenido.
En este ejemplo se agrega un nuevo tipo de contenido denominado Contoso Document
a la colección de sitios. Este tipo de contenido tiene una plantilla personalizada asociada cuando se crea un nuevo documento.
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");
}