ASP.NET Web Parts: crear un EditorPart y desplegar el Web Part en SharePoint

by Nicolás Ferreira 30. June 2008 00:00

Todo desarrollo Web Part que tenga como objetivo WSS 3.0/MOSS 2007 debería utilizar como clase base "System.Web.UI.WebControls.WebParts.WebPart". "Microsoft.SharePoint.WebPartPages.WebPart" se mantiene principalmente por un tema de compatibilidad con versiones anteriores de SharePoint. En este artículo vamos a crear un simple Web Part que tendrá una propiedad que el usuario establecerá para recibir respuesta. El despliegue del ensamblado y su configuración lo haremos manualmente.

Abrimos Visual Studio y creamos un nuevo proyecto de tipo Biblioteca de clases al que llamaremos "WebPartSaludo". Antes de empezar a codificar:

1 – Agregamos una referencia al ensamblado "System.Web". Esta referencia es necesaria para hacer que nuestro Web Part herede de "System.Web.UI.WebControls.WebParts.WebPart".
2 – Renombramos "Class1.cs" por "SaludoWebPart.cs" que automáticamente debería cambiar el nombre de la clase. Si no es así cambiamos el nombre de la clase.
3 – Hacemos heredar la clase "SaludoWebPart" de "System.Web.UI.WebControls.WebParts.WebPart".

Nuestro Web Part pedirá al usuario un nombre y mostrará por ejemplo "Hola Nicolás. Buenos días.". Vamos a la vista de código de "SaludoWebPart.cs" y creamos una propiedad llamada "Nombre" de tipo string. También tenemos que crear un campo que será el que realmente almacenará la información:

        private string _Nombre;

        public string Nombre
        {
            get { return _Nombre; }
            set { _Nombre = value; }
        }

Tenemos que aplicar a la propiedad "Nombre" los siguientes atributos:
- "System.Web.UI.WebControls.WebParts.Personalizable". Se utiliza para que el "Web Part Manager" persista el valor de la propiedad. Si especificamos un "PersonalizationScope" de "Shared" los cambios que se hagan a la propiedad "Nombre" serán vistos por todos los usuarios (todos compartirán el mismo valor). Si especificamos "User" cada usuario podrá especificar un valor y ese valor será visto sólo por el usuario que lo especificó.
- "System.Web.UI.WebControls.WebParts.WebBrowsable". Si especificamos un valor de "true" la propiedad se mostrará utilizando una interfaz de usuario de edición genérica. La interfaz se crea basándose en el tipo de la propiedad. El objetivo de este artículo es mostrar nuestro propio EditorPart y presentar la propiedad al usuario como nos parezca mejor, por lo que al atributo "WebBrowsable" le vamos a especificar "false".

        private string _Nombre;
        [Personalizable(PersonalizationScope.User)]
        [WebBrowsable(false)]
        public string Nombre
        {
            get { return _Nombre; }
            set { _Nombre = value; }
        }

Para proveer al usuario de una interfaz para que pueda ingresar un nombre tenemos que crear una clase que herede de "System.Web.UI.WebControls.WebParts.EditorPart". Un "EditorPart" se utiliza para editar controles Web Part una vez que el usuario puso el Web Part en modo de edición. Puede haber más de un "EditorPart" por Web Part y estarán en una colección de tipo "EditorPartCollection".

1 – Creamos una clase llamada "SaludoEditorPart".
2 – Cambiamos la declaración de la clase "SaludoEditorPart" para que sea pública.
3 – La hacemos heredar de "System.Web.UI.WebControls.WebParts.EditorPart".

Hay tres métodos principales que tenemos que sobrescribir/implementar:
- "CreateChildControls" – Lo utilizamos para agregar controles al "EditorPart". Los controles que agreguemos aquí le aparecerán al usuario para que pueda editar el Web Part.
- "SyncChanges" (abstract) – El propósito del método es recuperar los valores actuales del control "WebPart" al que se hace referencia en la propiedad "WebPartToEdit" y actualizar los campos del control "EditorPart" con dichos valores para que un usuario pueda editarlos.
- "ApplyChanges" (abstract) – El propósito del método es guardar los valores que ha especificado un usuario para un control "EditorPart" en las propiedades correspondientes del control "WebPart" al que se hace referencia en la propiedad "WebPartToEdit".

using System.Web.UI.WebControls.WebParts;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace WebPartSaludo
{
    public class SaludoEditorPart : EditorPart
    {
        private TextBox _Nombre = null;
        public SaludoWebPart SaludoWebPart
        {
            get { return ((SaludoWebPart)this.WebPartToEdit); }
        }
        public override bool ApplyChanges()
        {
            this.EnsureChildControls();
            this.SaludoWebPart.Nombre = this._Nombre.Text;
            return true;
        }
        public override void SyncChanges()
        {
            this.EnsureChildControls();
            this._Nombre.Text = this.SaludoWebPart.Nombre;
        }
        protected override void CreateChildControls()
        {
            this.Controls.Add(new LiteralControl("Ingrese su nombre:"));
            this._Nombre = new TextBox();
            this._Nombre.Width = new Unit("100%");
            this.Controls.Add(this._Nombre);
        }
    }
}

Una vez que tenemos nuestro "SaludoEditorPart" vamos a la vista de código para "SaludoWebPart.cs". Tenemos que sobrescribir el método "CreateEditorParts" y especificar nuestro "SaludoEditorPart". Además, tenemos que mostrar el saludo al usuario (sobrescribiremos el método CreateChildControls). Toda la clase quedaría así:

using System.Collections.Generic;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI;

namespace WebPartSaludo
{
    public class SaludoWebPart : WebPart
    {
        private string _Nombre;
        [Personalizable(PersonalizationScope.User)]
        [WebBrowsable(false)]
        public string Nombre
        {
            get { return _Nombre; }
            set { _Nombre = value; }
        }
        public override EditorPartCollection CreateEditorParts()
        {
            List<EditorPart> lEditorParts = new List<EditorPart>(1);
            EditorPart lSaludoEditorPart = new SaludoEditorPart();
            lSaludoEditorPart.ID = string.Concat(this.ID, "_SaludoEditorPart");
            lEditorParts.Add(lSaludoEditorPart);
            EditorPartCollection lBaseEditorParts = base.CreateEditorParts();
            return new EditorPartCollection(lBaseEditorParts, lEditorParts);
        }
        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            if (!string.IsNullOrEmpty(this.Nombre))
            {
                this.Controls.Add(new LiteralControl(string.Format("Hola {0}. Buenos días.", this.Nombre)));
            }
        }
    }
}

Desplegar el ensamblado

1 – Compilamos y copiamos "WebPartSaludo.dll" y lo pegamos en la carpeta "Bin" de nuestro directorio virtual de SharePoint para la aplicación a la que le queremos agregar el Web Part (en mi caso "C:\Inetpub\wwwroot\wss\VirtualDirectories\2667\bin").
2 – Abrimos el archivo "web.config" de nuestro directorio virtual de SharePoint para la aplicación a la que le queremos agregar el Web Part (en mi caso "C:\Inetpub\wwwroot\wss\VirtualDirectories\2667\web.config") y bajo "SafeControls" agregamos la siguiente entrada:

<SafeControl Assembly="WebPartSaludo, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" Namespace="WebPartSaludo" TypeName="*" Safe="True" />

3 – Ejecutamos "IISRESET".

Mostrando el Web Part

1 – Vamos al sitio Web y en el menú "Acciones del sitio" seleccionamos "Configuración del sitio". Bajo la sección "Galerías" elegimos "Elementos Web". En "Galería de elementos Web" hacemos clic en "Nuevo" y buscamos "WebPartSaludo.SaludoWebPart". Lo marcamos y hacemos clic en "Llenar galería".
2 – Volvemos a la página principal y en el menú "Acciones del sitio" seleccionamos "Editar Página". En la zona que nos interese agregar el Web Part seleccionamos la opción de "Agregar elemento Web". Esto abrirá el catálogo con los Web Parts que tenemos disponibles. Buscamos "SaludoWebPart" que generalmente aparece bajo la sección "Varios" y lo marcamos. Luego hacemos clic en "Agregar".
3 – Una vez que quedó agregado el Web Part a la página, en el menú "editar" seleccionamos "Modificar elemento Web compartido". En el panel "SaludoWebPart" que se abrió a la derecha vamos a ver nuestro "EditorPart". Ingresamos un nombre y hacemos clic en "Aceptar". Salimos del modo edición.

ASP.NET Web Parts: crear un EditorPart y desplegar el Web Part en SharePoint: Agregar elemento Web

ASP.NET Web Parts: crear un EditorPart y desplegar el Web Part en SharePoint: Ingrese su nombre

ASP.NET Web Parts: crear un EditorPart y desplegar el Web Part en SharePoint

Tags:

WSS 3.0/MOSS 2007

Comments

7/19/2010 10:41:02 PM #

Liposculpture

Google is superb, it's the heart of all the information! Laughing We can ask no matter we would like, and google will reply them. Like proper now, I'm surfing, in search of entertainment and data, and at last found your posting. It give me what I wanting for. Thank you in your posts, this is very useful.

Liposculpture United States | Reply

8/5/2010 1:44:10 AM #

garden bridge

Appreciate what we have, that's what my mother always said to me.

garden bridge United States | Reply

8/7/2010 1:12:38 PM #

jasmin live

Well, the post is actually the freshest topic on this registry related issue. I fit in with your conclusions and will thirstily look forward to your coming updates. Just saying thanks will not just be sufficient, for the phenomenal lucidity in your writing. I will right away grab your rss feed to stay abreast of any updates.

jasmin live United States | Reply

8/11/2010 9:32:37 AM #

NAB

I wanted to follow your RSS however it seems to be broken.  I'll try again tomorrow.

NAB United States | Reply

8/20/2010 7:27:57 PM #

Consignment

Can I just say what a relief to find someone who actually knows what theyre talking about on the internet. You definitely know how to bring an issue to light and make it important. More people need to read this and understand this side of the story. I cant believe youre not more popular because you definitely have the gift.

Consignment United States | Reply

8/23/2010 2:14:04 PM #

porter cable battery

I know you are using Microsofts BlogEngine.NET but can you please tell me which version that you are using?  I've been looking all over and wanted one like the one here at %BLOGSITE% I came from wordpress and am trying to figure out BlogEngine.

porter cable battery United States | Reply

8/27/2010 6:05:28 PM #

NHL 11 Slide

Hi,
I agree with your post "Have You Had Enough Of Mine" | ASP.NET Web Parts: crear un EditorPart y desplegar el Web Part en SharePoint. I will make sure to be reading your website more.
Have fun!

NHL 11 Slide United States | Reply

8/29/2010 10:59:58 PM #

Buy Smokeless Cigarette

Recently, I did not give so much thought to writing comments on weblog entries and have left comments even less. Checking out your powerful content, may very well encourage me to do this often.

Buy Smokeless Cigarette United States | Reply

8/30/2010 9:22:41 PM #

Bethann Critchlow

Going to see Mark Knight Tonight. Its gonna be excellent. There playing with Bob Sinclar. Then next weekend ill be seeing Judge Jules. amazing nights ahead

Bethann Critchlow Ireland | Reply

8/31/2010 11:09:13 PM #

Lemonade Diet Recipe

goodto see you make postings on this issue, I should bookmark this web site. Just keep up the good job.

Lemonade Diet Recipe United States | Reply

9/1/2010 7:26:08 AM #

Camgirls

Funny, I actually had this on my mind a few days ago and now I come across your blog.

Camgirls United States | Reply

9/1/2010 4:29:12 PM #

gold overmantle mirror

Right away, the article is actually the greatest on that worthy topic. I agree with your conclusions and also will eagerly look forward to your forthcoming updates. Saying thanks will certainly not simply just be enough, for the fantasti c clarity in your writing. I definitely will right away grab your rss feed to stay privy of any updates. Admirable work and much success in your business endeavors!

gold overmantle mirror United States | Reply

9/1/2010 8:57:35 PM #

Jaynell

Merely want to say your article is astounding. The lucidity in your post is simply striking and i can take for granted you are an expert on this subject. Well with your permission allow me to grab your rss feed to keep up to date with succeeding post. Thanks a million and please keep up the gratifying work.

Jaynell United States | Reply

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading