miércoles, 12 de octubre de 2011

Creando Site Columns y Content Types programáticamente

El día de hoy quiero compartir con ustedes un ejemplo de cómo crear columnas de sitio y tipos de contenido programáticamente. El objetivo final es crear un tipo de contenido que herede del tipo de contenido WorkflowTask (el que se utiliza para las tareas que se asignan en los flujos de trabajo), utilizando dos columnas de sitio, la primera será una columna que permitirá al usuario capturar su respuesta (Aprobar | Rechazar), la segunda permitirá capturar comentarios acerca de su respuesta.

Sin mucho preámbulo comencemos creando un proyecto en blanco con un elemento Feature con scope Site, al cual agregaremos un Event Receiver
Inmediatamente después comenzamos a tirar un poco de código en el método FeatureActivated para crear en primera instancia las dos columnas de sitio que utilizaremos:
SPWeb web = null;
if (properties.Feature.Parent is SPSite)
{
    SPSite sites = (SPSite)properties.Feature.Parent;
    web = sites.RootWeb;
}
else
{
    web = (SPWeb)properties.Feature.Parent;
}
if (web == null)
    return;
                
//Nombre del grupo de Content Types que crearemos
string contentTypeGroupName = "Blog - Content Types";
//Nombre del tipo de contenido que crearemos
string contentTypeName = "Blog - Response Workflow Content Type";
//Nombre del grupo de columnas de sitio que crearemos
string columnGroupName = "Blog - Site Columns";
//nombre de la columna de sitio que permitira al usuario seleccionar su respuesta (Approve | Reject)
string choiceFieldName = "ChoiceWFResponse";
//nombre de la columna de sitio que permitira al usuario capturar comentarios a cerca de su respuesta
string commentsFieldName = "CommentsWFResponse";


SPFieldMultiLineText approveRejectCommentsField = null;
SPFieldChoice approveRejectChoiceField = null;
                
/*Columna de sitio para seleccionar Aprobar o Rechazar*/
//mucho ojo! Validamos si la columa de sitio ya existe
if (!web.Fields.ContainsField(choiceFieldName))
{
    string approveReject = web.Fields.Add(choiceFieldName, SPFieldType.Choice, true);
    approveRejectChoiceField = (SPFieldChoice)web.Fields.GetFieldByInternalName(approveReject);
    approveRejectChoiceField.Group = columnGroupName;
    approveRejectChoiceField.EditFormat = SPChoiceFormatType.RadioButtons;
    approveRejectChoiceField.Choices.Add("Approve");
    approveRejectChoiceField.Choices.Add("Reject");
    approveRejectChoiceField.DefaultValue = "Approve";
    approveRejectChoiceField.Update();
}
//Si ya existe, solo obtenemos una referencia a la columna
else
{
    approveRejectChoiceField = web.Fields[choiceFieldName] as SPFieldChoice;
}

/*Columna de sitio para permitir al usuario ingresar un comentario*/
if (!web.Fields.ContainsField(commentsFieldName))
{
    string comments = web.Fields.Add(commentsFieldName, SPFieldType.Note, true);
    approveRejectCommentsField = (SPFieldMultiLineText)web.Fields.GetFieldByInternalName(comments);
    approveRejectCommentsField.Group = columnGroupName;
    approveRejectCommentsField.Update();
}
else
{
    approveRejectCommentsField = web.Fields[commentsFieldName] as SPFieldMultiLineText;
}

Una vez que las hemos creado, procedemos a crear el tipo de contenido utilizando las columnas de sitio.
//
//Ahora creamos el tipo de contenido
//

//heredamos del WorkflowTask Content Type
SPContentType workflowTaskCType = web.AvailableContentTypes[SPBuiltInContentTypeId.WorkflowTask];
SPContentType approvalRejectCType = null;
bool isUpdating = false;

//validamos si el tipo de contenido ya existe
if (web.AvailableContentTypes[contentTypeName] == null)
{
    approvalRejectCType = new SPContentType(workflowTaskCType, web.ContentTypes, contentTypeName);
    approvalRejectCType = web.ContentTypes.Add(approvalRejectCType);
    approvalRejectCType.Group = contentTypeGroupName;
}
else
{
    approvalRejectCType = web.ContentTypes[contentTypeName];
    isUpdating = true;
}

if (!isUpdating)
{
    //agregamo la columna de Seleccion
    SPFieldLink approveRejectFieldRef = new SPFieldLink(approveRejectChoiceField);
    approveRejectFieldRef.Required = true;
    approveRejectFieldRef.DisplayName = "Approve or Reject the task";
    approvalRejectCType.FieldLinks.Add(approveRejectFieldRef);

    //agregamo la columna de Comentarios
    SPFieldLink commentsFieldRef = new SPFieldLink(approveRejectCommentsField);
    commentsFieldRef.DisplayName = "Comments";
    approvalRejectCType.FieldLinks.Add(commentsFieldRef);
}
else
{
    //Actualizamos la columna de Seleccion
    SPFieldLink approveRejectFieldRef = approvalRejectCType.FieldLinks[approveRejectChoiceField.Id];
    approveRejectFieldRef.Required = true;
    approveRejectFieldRef.DisplayName = "Approve or Reject the task";

    //Actualizamos la columna de Comentarios
    SPFieldLink commentsFieldRef = approvalRejectCType.FieldLinks[approveRejectCommentsField.Id];
    commentsFieldRef.DisplayName = "Comments";
}

//actualizamos el tipo de contenido
approvalRejectCType.Update(true);

Hacemos Deploy de nuestro proyecto y validamos que se hayan creado las columnas de sitio y el tipo de contenido


Listo!

Pueden descargar el código de aquí

Happy Coding!

0 comentarios:

Etiquetas

SharePoint 2010 (38) Microsoft (32) Desarrollo SharePoint (31) Gerardo Reyes Ortiz (27) SharePoint (20) SharePoint 2013 (18) Errores SharePoint (12) México (10) PowerShell (9) Silverlight (8) Visio Services (7) Features (6) MVP (6) Silverlight 3 (6) WebCast (6) Workflows (6) Configuracion SharePoint 2010 (5) D.F. (5) API REST (4) Configuracion SharePoint 2010; (4) Troubleshooting (4) Visual Studio 2010 (4) Visual studio (4) WSS (4) Web parts (4) Apps (3) Comunidad SharePoint (3) Configuración SharePoint 2013 (3) ODATA (3) SharePoint Server (3) SharePoint; Instalación SharePoint; Troubleshooting; Search Service (3) Silverlight 3.0 (3) Silverlight Toolkit (3) WebParts (3) javascript (3) jquery (3) Eventos SharePoint (2) Office 2010 (2) PeoplePicker (2) REST (2) SQL Server (2) Scripting (2) Search Service Application (2) SharePoint Designer (2) UPA (2) UPS (2) Workflows SharePoint (2) host header (2) Apps Development (1) Big Bang (1) CAS (1) CSOM (1) Codeplex (1) CompartiMOSS (1) Configuracion SharePoint 2010; Errores SharePoint (1) Configuracion SharePoint 2010; SharePoint 2010 (1) Custom Actions (1) Custom Editor Parts (1) Delegate Controls (1) Deployment (1) DisableLoopbackCheck (1) Document Library (1) Entrevista (1) Examenes de Certificación (1) Extract WSP (1) FBA (1) FS4SP (1) Fakes (1) Fast Search Server 2010 For SharePoint (1) Fiddler (1) HTTP.SYS (1) HTTPS (1) JSON (1) Language Pack's (1) Latam (1) MAXDOP (1) MCSM (1) MSExpertos (1) MVC (1) Microsoft México (1) Microsoft; Codeplex; Screencast; (1) My Sites (1) SQL Server 2012 (1) SQL Server Reporting Services (1) Screencast (1) Screencast; (1) Service Applications (1) Service Pack (1) SharePoint 2007 (1) SharePoint 2010 SP 1 (1) SharePoint API (1) SharePoint Conference (1) SharePoint Emulators (1) SharePoint Farm (1) SharePoint Health Analyzer (1) SharePoint Magazine (1) SharePoint Online (1) SharePoint Search (1) SharePoint Test (1) SharePoint; Desarrollo SharePoint (1) Shims (1) Simposio (1) Simposio Latinoamericano (1) SkyDrive Pro (1) Soporte Microsoft (1) Templates (1) Tip (1) VSeWSS (1) Virtual Machine (1) Visual Studio 2012 (1) WCF (1) WSS; IIS 7 (1) Web API (1) Web Content Management (1) Web Services (1) Windows 8 (1) Windows Live ID (1) Xml (1) appcmd (1) iOS (1) jqGrid (1) onload function (1)