HOW TO – (MOSS 2007) Crear nuestro propio ToolPart

Desarrollando unos WebPart para el proyecto en el que estoy actualmente, necesitaba añadir una propiedad a un WebPart para permitir sólo su visibilidad a ciertos perfiles. Estos perfiles los suministra una aplicación que se encarga de la seguridad de las aplicaciones.

Para otros caso me vale una Enum como fuente de datos (Veáse Tipo de Objeto, Tipo de Barra…) pero para este caso no, así que tuve que crearme mi propio ToolPart como se muestra en la imagen:

toolpart1

En concreto el desplegable en cuestión es el de Perfil Permitido.

Para crearnos nuestro propio ToolPart, lo primero es crearnos una clase que herede de ToolPart (Microsoft.SharePoint.WebPartPages.ToolPart):

   public class ExtendedWorkLoadToolPart : ToolPart

Lo siguiente será sobreescribir los métodos CreateChildControls y RenderToolPart:

protected override void CreateChildControls()
{
    base.CreateChildControls();
 
    /// Añadir nuestros controles  
}

 

 
/// <summary>
/// Sends the tool part content to the specified HtmlTextWriter object, 
/// which writes the content to be rendered on the client.
/// </summary>
/// <param name="output">The HtmlTextWriter object that receives the tool part content.</param>
protected override void RenderToolPart(System.Web.UI.HtmlTextWriter output)
{
    // Establish a reference to the Web Part.
    WorkLoadWebPart workLoadWebPart =
        (WorkLoadWebPart)this.ParentToolPane.SelectedWebPart;
 
    output.Write("<table width=\"100%\" cellspacing=\"0\" cellpadding=\"2\"><tr><td colspan=\"2\">");
    _lblDataHeader.Text = SPUtility.GetLocalizedString("$Resources:webpart_lblDataHeader_text", "company", SPContext.Current.Web.Language);
    _lblDataHeader.Font.Bold = true;
    _lblDataHeader.RenderControl(output);
    output.Write("<hr></td></tr><tr><td>");
    _lblObjectType.Text = SPUtility.GetLocalizedString("$Resources:webpart_lblObjectType_text", "company", SPContext.Current.Web.Language);
    _lblObjectType.RenderControl(output);
    output.Write("</td><td>");
    _ddlObjectType.SelectedValue = Enum.GetName(typeof(EnumObjectType), workLoadWebPart.TipoObjeto);
    _ddlObjectType.RenderControl(output);
    output.Write("</td></tr><tr><td>");
    _lblActiveUser.Text = SPUtility.GetLocalizedString("$Resources:webpart_lblActiveUser_text", "company", SPContext.Current.Web.Language);
    _lblActiveUser.RenderControl(output);
    output.Write("</td><td>");
    _chkActiveUser.Checked = workLoadWebPart.UsuarioActivo;
    _chkActiveUser.RenderControl(output);
    output.Write("</td></tr><tr><td>");
    _lblDelimerChar.Text = SPUtility.GetLocalizedString("$Resources:webpart_lblDelimerChar_text", "company", SPContext.Current.Web.Language);
    _lblDelimerChar.RenderControl(output);
    output.Write("</td><td>");
    _txtDelimiterChar.Text = workLoadWebPart.DelimitadorUsurios.ToString();
    _txtDelimiterChar.RenderControl(output);
    output.Write("</td></tr><tr><td colspan=\"2\">");
    _lblVariosHeader.Text = SPUtility.GetLocalizedString("$Resources:webpart_lblVariosHeader_text", "company", SPContext.Current.Web.Language);
    _lblVariosHeader.Font.Bold = true;
    _lblVariosHeader.RenderControl(output);
    output.Write("<hr></td></tr><tr><td>");
    _lblBarType.Text = SPUtility.GetLocalizedString("$Resources:webpart_lblBarType_text", "company", SPContext.Current.Web.Language);
    _lblBarType.RenderControl(output);
    output.Write("</td><td>");
    _ddlBarType.SelectedValue = Enum.GetName(typeof(EnumBarType), workLoadWebPart.TipoBarra);
    _ddlBarType.RenderControl(output);
    output.Write("</td></tr><tr><td>");
    _lblShowLabels.Text = SPUtility.GetLocalizedString("$Resources:webpart_lblShowLabels_text", "company", SPContext.Current.Web.Language);
    _lblShowLabels.RenderControl(output);
    output.Write("</td><td>");
    _chkShowLabels.Checked = workLoadWebPart.MostrarEtiquetas;
    _chkShowLabels.RenderControl(output);
    output.Write("</td></tr><tr><td>");
    _lblPlacePecentage.Text = SPUtility.GetLocalizedString("$Resources:webpart_lblPlacePecentage_text", "company", SPContext.Current.Web.Language);
    _lblPlacePecentage.RenderControl(output);
    output.Write("</td><td>");
    _ddlPlacePercentage.SelectedValue = Enum.GetName(typeof(EnumPlacePercentage), workLoadWebPart.UbicacionPorcentaje);
    _ddlPlacePercentage.RenderControl(output);
    output.Write("</td></tr><tr><td>");
    output.Write("</td></tr><tr><td colspan=\"2\">");
    _lblSecurityHeader.Text = SPUtility.GetLocalizedString("$Resources:webpart_lblSecurityHeader_text", "company", SPContext.Current.Web.Language);
    _lblSecurityHeader.Font.Bold = true;
    _lblSecurityHeader.RenderControl(output);
    output.Write("<hr></td></tr><tr><td>");
    _lblProfiles.Text = SPUtility.GetLocalizedString("$Resources:webpart_lblProfiles_text", "company", SPContext.Current.Web.Language);
    _lblProfiles.RenderControl(output);
    output.Write("</td><td>");
    _ddlProfiles.SelectedValue = workLoadWebPart.PerfilPermitido;
    _ddlProfiles.RenderControl(output);
    output.Write("</td></tr></table>");
 
}

Vamos a fijarnos en esta línea:

// Establish a reference to the Web Part.
WorkLoadWebPart customWebPartEx1 =
        (WorkLoadWebPart)this.ParentToolPane.SelectedWebPart;

 

En ella lo que hacemos es obtener la referencia al WebPart que está usando la ToolPart, para acceder a sus propiedades y poder cargar los datos en los controles antes de renderizarlos.

Para finzalizar nuestra ToolPart, nos falta almacenar los valores de los controles de la ToolPart en las propiedades de nuestro WebPart. Para ellos sobreescribimos el método ApplyChanges, que será llamado cuando se pulse el botón OK o Aplicar, cuando modificamos las propiedades del WebPart:

/// <summary>
/// Called when the user clicks the OK or the Apply button in the tool pane.
/// </summary>
public override void ApplyChanges()
{
    // Establish a reference to the Web Part.
    WorkLoadWebPart workLoadWebPart =
        (WorkLoadWebPart)this.ParentToolPane.SelectedWebPart;
 
    workLoadWebPart.UbicacionPorcentaje = (EnumPlacePercentage)Enum.Parse(typeof(EnumPlacePercentage), _ddlPlacePercentage.SelectedValue);
    workLoadWebPart.TipoBarra = (EnumBarType)Enum.Parse(typeof(EnumBarType), _ddlBarType.SelectedValue);
    workLoadWebPart.PerfilPermitido = _ddlProfiles.SelectedValue;
    workLoadWebPart.TipoObjeto = (EnumObjectType)Enum.Parse(typeof(EnumObjectType), _ddlObjectType.SelectedValue);
    workLoadWebPart.MostrarEtiquetas = _chkShowLabels.Checked;
    workLoadWebPart.UsuarioActivo = _chkActiveUser.Checked;
    workLoadWebPart.DelimitadorUsurios = _txtDelimiterChar.Text.ToCharArray()[0];
 
}

Por último, falta que nuestro WebPart utilice la ToolPart que acabamos de crear. En el código de nuestro WebPart sobreescribimos el método GetToolParts:

/// <summary>
/// Determines which tool parts are displayed in the tool pane of the Web-based Web Part design user interface, and the order in which they are displayed.
/// </summary>
/// <returns>
/// An array of type <see cref="T:Microsoft.SharePoint.WebPartPages.ToolPart"></see> that determines which tool parts will be displayed in the tool pane. If a Web Part that implements one or more custom properties does not override the <see cref="M:Microsoft.SharePoint.WebPartPages.WebPart.GetToolParts"></see> method, the base class method will return an instance of the <see cref="T:Microsoft.SharePoint.WebPartPages.WebPartToolPart"></see> class and an instance of the <see cref="T:Microsoft.SharePoint.WebPartPages.CustomPropertyToolPart"></see> class. An instance of the <see cref="T:Microsoft.SharePoint.WebPartPages.WebPartToolPart"></see> class displays a tool part for working with the properties provided by the WebPart base class. An instance of the <see cref="T:Microsoft.SharePoint.WebPartPages.CustomPropertyToolPart"></see> class displays a built-in tool part for working custom Web Part properties, as long as the custom property is of one of the types supported by that tool part. The supported types are: String, Boolean, Integer, DateTime, or Enum.
/// </returns>
[SharePointPermission(SecurityAction.Demand, ObjectModel = true)]
public override ToolPart[] GetToolParts()
{
    return new ToolPart[] { new WebPartToolPart(), new ExtendedWorkLoadToolPart() };
}

 

Añadimos a parte de la ToolPart por defecto, nuestra ToolPart (ExtendedWorkLoadToolPart).

Y esto es todo!!!

PD: He añadido un código de ejemplo aunque no es del artículo ;)

Published 9/2/2009 15:30 por Luis Ruiz Pavón
Comparte este post:
http://geeks.ms/blogs/lruiz/archive/2009/02/09/how-to-moss-2007-crear-nuestro-propio-toolpart.aspx

Comentarios

# re: HOW TO – (MOSS 2007) Crear nuestro propio ToolPart

Muy bien explicado Luis, enhorabuena.

Monday, February 09, 2009 3:35 PM por Isaac Fernandez

# re: HOW TO – (MOSS 2007) Crear nuestro propio ToolPart

Genial ... y como pedir es gratis, ¿sería posible que dejes una solución con el código completo de ejemplo? (siempre que no sea código cerrado de algún proyecto)

Gracias :D

Monday, February 09, 2009 3:43 PM por El Bruno

# re: HOW TO – (MOSS 2007) Crear nuestro propio ToolPart

Gracias ;)

Preparo un ejemplo y subo el código ;)

Saludos

Monday, February 09, 2009 3:47 PM por Luis Ruiz Pavón

# re: HOW TO – (MOSS 2007) Crear nuestro propio ToolPart

Estimado Luis, y en este caso la funcionalida por defecto de Audiencia no cubria tu requeriminto

Monday, February 09, 2009 5:23 PM por Juan

# re: HOW TO – (MOSS 2007) Crear nuestro propio ToolPart

No, como he comentado todas las aplicaciones del cliente trabajan con una aplicación que es la que otorga los permisos, pefiles.... Existe un mapeo del usuario Windows con el usuario de dicha aplicación ;)

Salu2

Monday, February 09, 2009 5:27 PM por Luis Ruiz Pavón

# Fugas de agua

El control del consumo de agua es muy importante hoy en dia no solo por el ahorro del agua si no por el ahorro economico..Detectamos cualquier tipo de Fuga de Agua en piscinas, viviendas, calefaccion, fugas ocultas...Los PRECIOS MAS ECONOMICOS DEL MERCADO con la tecnologia mas moderna.24Horas a Toda España: 913920202

Thursday, August 19, 2010 6:01 PM por Fugas de agua