Sunteți pe pagina 1din 36

Trabajar con objetos de listas y colecciones

Otras versiones

Personas que lo han encontrado til: 1 de 1 - Valorar este tema Para realizar acciones sobre datos de listas en un sitio web de SharePoint, primero debe obtener un objeto SPWeb que sirva como punto de entrada al modelo de objetos, con lo que tendr acceso a listas, elementos, documentos, usuarios, alertas, etc. Para obtener informacin acerca de la devolucin de sitios web de SharePoint, vea Obtencin de referencias a sitios, aplicaciones web y otros objetos clave.

Objetos
La mayora de las clases de los espacios de nombres Microsoft.SharePoint y Microsoft.SharePoint.Administration empiezan por SP. Por lo general, las clases del ensambladoMicrosoft.SharePoint que no comienzan con este prefijo representan controles de formulario web. SharePoint Foundation normalmente no guarda las modificaciones de las propiedades de objeto en la base de datos hasta que se llama al mtodo Update en el objeto especificado. En el siguiente ejemplo se muestra cmo cambiar el ttulo y la descripcin de la lista Tasks. C# VB SPList oList = oWebsite.Lists["Tasks"]; oList.Title="New_Title"; oList.Description="List_Description"; oList.Update();

Nota
Los metadatos para el documento no pueden modificarse mediante el mtodo Update() del objeto SPListItem biblioteca de documentos.

Colecciones
Al igual que las listas son en el centro de un sitio de SharePoint, las colecciones lo son en el centro de sus modelos de objeto. Puede usar cada coleccin para agregar, eliminar, enumerar y actualizar un tipo de objeto. Las clases de colecciones normalmente comparten las siguientes caractersticas:

Tienen un nombre que termina en "Collection". Implementan la interfaz System.Collections.ICollection. Tienen una propiedad Count de tipo Int32. Tienen un indizador Int32 que puede usarse para obtener el elemento Tienen un indizador que toma un identificador de elemento. Tienen mtodos Add y Delete.

nth de la coleccin.

Al llamar al mtodo Add para una coleccin, normalmente se actualiza la base de datos en el servidor back-end con los datos adecuados, excepto cuando se necesita informacin adicional para actualizar los datos. En este caso, el uso del mtodo Add devuelve un objeto que se puede usar para recopilar la informacin. Por ejemplo, para agregar un elemento a una lista, en primer lugar use el mtodo Add de la clase Microsoft.SharePoint.SPListItemCollection para devolver un objeto SPListItem, asigne valores a las propiedades adecuadas del objeto y, a continuacin, llame al mtodo Update para que los cambios surtan efecto en la base de datos de contenido.

Indizadores
Los indizadores proporcionan un medio til para obtener acceso a elementos individuales de las colecciones. Para devolver un elemento, use corchetes ([]) en Microsoft C# o parntesis (()) en Microsoft Visual Basic que incluyan un ndice o cadena que identifique el elemento de la coleccin. Por ejemplo, si oWebsite representa una instancia de la clase SPWeb, SPList oList = oWebsite.Lists["Announcements"] devuelve la lista Announcements en C#, mientras que Dim oList As SPList = oWebsite.Lists("Announcements") devuelve la misma lista en Visual Basic. Para devolver elementos de la lista, un procedimiento recomendado consiste en llamar a unos de los mtodos GetItem* del objeto de lista y especificar los elementos que se recuperarn. El uso de la propiedad Items para obtener todos los elementos de una lista puede reducir el rendimiento, ya que fuerza la devolucin de todas las columnas de todos los elementos. En su lugar, use el mtodo GetItems, por ejemplo, y pase un objeto SPQuery para especificar el subconjunto: SPListItemCollection collItem = oList.GetItems(oQuery) (en Visual Basic, Dim collItem As SPListItemCollection = oList.GetItems(oQuery)). Una vez devuelta una coleccin de elementos desde una lista mediante un mtodo GetItem*, puede especificar un nombre de campo como un indizador y procesar una iteracin en la coleccin para devolver los valores del campo. En el siguiente ejemplo se muestran los valores Due Date, Status y Title para cada elemento de una coleccin. C# VB foreach(SPListItem oItem in collItem) { Response.Write(SPEncode.HtmlEncode(oItem["Due Date"].ToString()) + "<BR>");

Response.Write(SPEncode.HtmlEncode(oItem["Status"].ToString()) + "<BR>"); Response.Write(SPEncode.HtmlEncode(oItem["Title"].ToString()) + "<BR>"); }

Nota

Adems de requerir una directiva using (Imports en Visual Basic) para el espacio de nombres Microsoft.Shar directiva para el espacio de nombres Microsoft.SharePoint.Utilities.
En el siguiente ejemplo se muestra cmo devolver todos los valores Ttulo y Estado para la lista de tareas en un sitio web de SharePoint. C# VB SPWeb oWebsite = SPContext.Current.Web; SPList oList = oWebsite.Lists["Tasks"]; SPListItemCollection collItem = oList.GetItems("Title", "Status"); foreach(SPListItem oItem in collItem) { Response.Write(SPEncode.HtmlEncode(oItem["Title"].ToString()) + " :: " + SPEncode.HtmlEncode(oItem["Status"].ToString()) + "<BR>"); } Si se ha implementado la limitacin de peticiones, es posible que las consultas ineficientes se bloqueen debido a excesivos problemas de recuento de bsquedas o recuento de elementos. Puede mejorar la eficiencia de una consulta y reducir los problemas de recuento de bsquedas mediante la definicin de un objeto SPQuery que especifique un conjunto restringido de campos de vista (ViewFields) y, a continuacin, pasar dicho objeto de consulta al mtodo GetItems, como se muestra en el ejemplo siguiente. VB Dim oQuery As New SPQuery() oQuery.Query = "<ViewFields><FieldRef Name = ""Title"" />" & "<FieldRef Name = ""Status""/></ViewFields>" Dim collItem As SPListItemCollection = oList.GetItems(oQuery) C# SPQuery oQuery = new SPQuery(); oQuery.Query = "<ViewFields><FieldRef Name = \"Title\" />" + "<FieldRef Name = \"Status\"/></ViewFields>"; SPListItemCollection collItem = oList.GetItems(oQuery); Para solucionar los problemas de limitacin de peticiones de recuento de elementos, es posible que sea necesario paginar los resultados en el ndice de elemento mediante la clase SPListItemCollectionPosition.

Nota

Adems de requerir una directiva using (Imports en Visual Basic) para el Microsoft.SharePoint espacio de no directiva para el espacio de nombres Microsoft.SharePoint.Utilities.
Tambin puede usar los indizadores para modificar los valores de una lista. En el ejemplo siguiente, se agrega un nuevo elemento de lista a una coleccin y los valores de una columna de direccin URL se asignan al elemento. C# VB SPListItem oNewItem = oList.Items.Add(); oNewItem["URL_Field_Name"] = "URL, Field_Description"; oNewItem.Update();

Nota

El tipo de campo URL es nico porque implica dos valores (separados por una coma y un espacio) y en el eje nuevo elemento mediante un indizador nico.
En el siguiente ejemplo se usa el mtodo GetItemById(Int32) para devolver un elemento y, a continuacin, se establecen sus valores de columna Status y Title. C# VB SPListItem oItem = oList.GetItemById(1); oItem["Status"]="Task_Status"; oItem["Title"]="Task_Title"; oItem.Update(); Si puede especificar que la lista de campos recupere para el elemento y si ninguno de los campos es de tipo Lookup o un tipo de campo que herede de SPFieldLookup, puede mejorar el rendimiento mediante una llamada al mtodo GetItemByIdSelectedFields(Int32, String[]), en lugar de llamar a GetItemById(Int32).

Personalizacin de formularios de elemento de lista en Windows SharePoint Services


SharePoint 2003 11 de los 16 ha calificado este til - Valorar este tema Les W. Smith Microsoft Corporation 03 2005 Se aplica a: Microsoft Windows SharePoint Services Resumen: Mejorar y ampliar la interaccin con listas de Microsoft Windows SharePoint Services al personalizar formularios que le permiten trabajar con los elementos de la lista.(34 pginas impresas) Contenido Introduccin a los Formularios de lista Personalizar Definiciones de lista de SharePoint Lista de elementos de formulario Diseo de pgina Formar Ver definicin Creacin de una definicin de sitio personalizada Adicin de navegacin hacia la izquierda a travs de un formulario Controles de servidor Web Incorporacin de un elemento web en una forma y en la pgina de inicio para mostrar datos de lista Crear un formulario para extender el alcance de una encuesta Personalizaciones avanzadas Conclusin Recursos adicionales

Introduccin a los Formularios de lista Personalizar


En Microsoft Windows SharePoint Services, debe utilizar formularios de lista de elementos para crear, modificar o visualizar los elementos individuales de la lista de SharePoint.En este artculo, exploramos las mejores prcticas para la personalizacin de formularios de elementos de lista en Windows SharePoint Services, el diseo de la pgina de SharePoint que contiene un formulario, y el subyacente esquema XML que define el contenido del formulario. Al trabajar a travs de una serie de tareas comunes pocos, se puede entender la manera de extender el alcance y la funcionalidad de las formas de interaccin con listas de SharePoint. Proporcionamos ejemplos de personalizaciones comunes, tales como la adicin de enlaces a la zona de navegacin izquierda del formulario,

mostrar los datos de lista en un formulario, o mostrar un formulario en la pgina de inicio. Tambin proporcionamos ejemplos de personalizaciones avanzadas, como la personalizacin de la barra de herramientas o el cuerpo en forma, o la adicin de secuencia de comandos para interactuar con el usuario hace clic en y para validar los datos. Nos centramos en las personalizaciones que se pueden realizar en las siguientes reas: La pgina ASPX que contiene el formulario de elemento de lista Archivos de esquemas XML que definen los campos de formulario de lista de elementos y puntos de vista de forma Los controles de servidor Web y elementos Web personalizados que consolidan cdigo e implementar tipos y miembros del espacio de nombres en el conjunto de los servicios de Windows SharePoint para ampliar la interaccin del usuario con los datos de lista

Definiciones de lista de SharePoint


Cuando se crea una lista en un sitio de SharePoint, Windows SharePoint Services genera la instancia de la lista a partir de una definicin de lista que figura en la definicin de sitio, desde que se cre el sitio. Cada lista se basa su definicin de archivos que se aplican a nivel mundial para el sitio, tales como las siguientes:

ONET.XML especifica los campos que se incluyen en cada tipo de lista, los tipos de listas
que se pueden crear a travs de las instancias de la pgina Crear sirve para crear listas, o listas de los incluidos en una configuracin particular dentro de una definicin de sitio. FLDTYPES.XML define cmo los diferentes tipos de datos usados en Windows SharePoint Services se transportan o representados a travs de los formularios de elementos de lista.

Cada tipo de lista, sin embargo, tambin se basa gran parte de su definicin de los contenidos de una carpeta dentro de la Local_Drive :\Program Files\Common Files\Microsoft Shared\web server extensions\60\TEMPLATE\ Locale_ID\ Site_Definition\LISTS Local_Drive :\Pr ogram Files\Common Files\Microsoft Shared\web server extensions\60\TEMPLATE\ Locale_ID\ Site_Definition\LISTS directorio, dedicado exclusivamente al tipo de lista en particular. Para la mayora de tipos de lista de la carpeta contiene al menos cinco archivos: AllItems.aspx para ver todos los elementos en una lista NewForm.aspx para la creacin de elementos de la lista DisplayForm.aspx para elementos de lista que muestra EditForm.aspx para la edicin de elementos de lista SCHEMA.XML define campos especiales para la lista, as como las vistas de lista, la barra de tareas relacionadas, y los contenidos principales de vistas utilizadas en los formularios de elementos de lista Nota Para obtener informacin general acerca de las definiciones de sitio y lista, consulte Introduccin a las plantillas y definiciones .

Los tres archivos XML mencionado anteriormente utilizar Collaborative

Application Markup

Language (CAML) para definir cmo se crean instancias de lista. CAML se utiliza para definir y
declarar los campos que componen una lista y se representa en un formulario. Adems, basndose en los metadatos de sitio o lista disponible en el momento, Windows SharePoint Services usa CAML para construir condicionalmente la interfaz de usuario apropiado para el formulario. Advertencia No modifique el contenido de FLDTYPES.XML ya que podra romper todas las definiciones de sitio en un servidor front-end web. Adems, tal como se describe ms adelante en este artculo, crear una definicin de sitio personalizada copiando una definicin de sitio existente, en lugar de modificar los archivos originales instalados con Windows SharePoint Services. Los cambios realizados en los archivos instalados originalmente se pueden sobrescribir al instalar actualizaciones o Service Pack para Windows SharePoint Services, o cuando se actualiza una instalacin a la siguiente versin del producto. Para obtener informacin sobre cmo crear una definicin de sitio personalizada, consulte Creacin de una definicin de sitio a partir de una definicin existente .

Lista de elementos de formulario Diseo de pgina


Las tres pginas ASPX que proporcionan los formularios de elementos de lista son muy similares, que recoge las directrices misma pgina, metadatos, la escritura y Windows SharePoint Services controles de servidor Web. Adems, cada pgina ASPX contiene una tabla que consta de tres filas: una para la bandera o el rea de navegacin superior, otro para el rea de ttulo, y un tercero, tanto para la navegacin de la izquierda y reas de contenido.

Figura 1. Tabla en una pgina ASPX Las cuatro celdas representadas en la tabla de la Figura 1 indican las reas que se pueden personalizar o eliminar por completo de la pgina. Clula de navegacin superior contiene una navegacin de control del espacio de nombres Microsoft.SharePoint.WebControl que inserta el rea de navegacin superior en la

pgina, incluyendo los enlaces a la pgina de inicio, a las pginas de acceso o la creacin de listas, para la gestin del sitio, y para la ayuda. Puede modificar o eliminar el contenido de esta seccin. Para obtener ms informacin, consulte Personalizacin de las reas de navegacin . Ttulo celda contiene los siguientes controles Web de servidor del espacio de nombres Microsoft.SharePoint.WebControl que devuelven informacin sobre el sitio actual, lista y elemento de la lista, en este caso de insertar el ttulo de cada objeto en la pgina: o ProjectProperty o ListProperty o ListItemProperty Izquierda celular navegacin est en blanco en los formularios de elementos de lista, pero puede insertar navegacin personalizada en esta rea, como se demuestra enadicin navegacin hacia la izquierda a travs de un formulario Controles de servidor Web . El contenido clula contiene lo siguiente control WebPartZone desde el espacio de nombres Microsoft.SharePoint.WebPartPages que inserta el contenido del formulario en la pgina: Copiar <WebPartPages:WebPartZone Runat="server" FrameType="None" ID="Main" Titl e="loc:Main" />

Puede agregar otras zonas de elementos Web a la pgina de forma declarativa en la misma forma por la adicin de una zona de elementos Web con un identificador nico. Al incrustar un elemento web personalizado dentro de una definicin de lista en el formulario de elemento de SCHEMA.XML, el valor del atributo WebPartZoneID en el elemento AllUsersWebPart que contiene la parte correspondiente al valor del atributo ID del control WebPartZone . El atributo FrameType de una zona de elementos Web describe la frontera utilizado para el elemento Web. Lo establecido en uno de los siguientes valores: Ninguno: No usar marco o barra de ttulo. Estndar: Marco de Uso y barra de ttulo. TitleBarOnly: Utilice la barra de ttulo, pero no marco.

La zona especifica dnde insertar un elemento Web en la pgina, y el elemento Web a su vez transmite la vista del elemento que se define en la seccin de formularios del archivo Schema.xml para el tipo de lista en particular.

Formar Ver definicin


Dos secciones en el archivo Schema.xml para un tipo de lista son importantes a los efectos de la personalizacin de las formas: la apertura elemento Fields que define campos especiales para la lista, y el elemento forma que contiene la vista de formulario para cada tipo de formulario.

Campos de la seccin
La seccin de campos en el principio del archivo Schema.xml para un tipo particular lista contiene las descripciones de los campos especiales que se deben implementar en una instancia de la lista. Un esquema de lista de tareas, por ejemplo, a diferencia de otros tipos de lista, tiene la siguiente seccin fields, que incluye dos campos de opciones y varios otros tipos de campos, algunos con valores por defecto especificados. Copiar <FIELDS> Campo> Type="Choice" Name="Priority" DisplayName="Priority"> <CHOICES> <Choice> (1) Alta </ choice> <Choice> (2) Normal </ choice> <Choice> (3) Bajo </ choice> </ OPCIONES> <Predeterminado> (2) Normal </ Default> </ Field> Campo> Type="Choice" Name="Status" DisplayName="Status"> <CHOICES> <Choice> No iniciada </ choice> <Choice> En curso </ choice> <Choice> Completado </ choice> <Choice> Diferido </ choice> <Choice> Espera de otra persona </ choice> </ OPCIONES> <Predeterminado> No iniciada </ Default> </ Field> <Tipo de campo = "Nmero" Name = "PercentComplete" Porcentaje = "TRUE" Min = "0" Max = "1" DisplayName = "% completo"> </ Field> <Tipo de campo = "Usuario" list = "UserInfo" Name = "AssignedTo" DisplayName = "Asignado a"> </ Field> <Tipo de campo = "Nota" RichText = "TRUE" Name = "Cuerpo" DisplayName = "Descripcin" puede ordenar = "FALSE"> </ Field> Campo> Type="DateTime" Name="StartDate" DisplayName="Start Date"> <Predeterminado> [Hoy] </ Default> </ Field> Campo> Type="DateTime" Name="DueDate" DisplayName="Due Date"> </ Field> </ Fields>

Adems del campo de ttulo, que se define de forma predeterminada para todos los tipos de lista, cada campo especificado en el anterior elemento Fields aparece en el formulario de elemento de lista en el orden indicado. Los usuarios pueden agregar una columna a una lista existente a travs de la interfaz de usuario, pero al agregar un campo a la enumeracin de apertura de los campos en SCHEMA.XML, se hace el campo generalmente disponibles para el tipo de lista particular, a fin de que las futuras listas creada a travs de la definicin de lista incluye la columna por defecto. Para una tarea de

programacin que gua a travs del proceso de agregar un campo a una definicin de lista, consulte Adicin de un campo a una definicin de lista . El orden de los campos en la seccin de campos determina el orden en que los campos estn representados en la interfaz de usuario de un formulario. Para cambiar el orden de los campos en el formulario, cambiar su orden dentro de la abertura elemento Fields . Nota Si los usuarios finales ya han creado instancias de lista mediante la definicin de lista y modificado sus campos, por ejemplo, al aadir un campo nuevo o cambiar el nombre de visualizacin de un campo existente, cambiando el orden de los campos en SCHEMA.XML no tiene ningn efecto.

Formas Seccin
El elemento forma en SCHEMA.XML contiene la vista y define el contenido de cada tipo de formulario, que incluye la barra de herramientas de elemento de la lista y todo el contenido que aparece debajo de la barra de herramientas en el cuerpo de la pgina. Un elemento Web inserta un HTML <DIV> etiquetas anidadas y dos <Table> etiquetas en la pgina, mientras que SCHEMA.XML define todo el contenido que se transmite a travs del elemento web. El elemento de formulario contiene la vista de formulario para un tipo determinado de la siguiente manera. Copiar <Form Type="EditForm" Url="EditForm.aspx" WebPartZoneID="Main">

Debe establecer el atributo Type para DisplayForm, EditForm o NewForm. El atributo Url identifica la pgina que muestra el formulario de elemento de la lista, y usted puede usar este atributo para especificar una pgina alternativa que se utiliza como forma de un tipo determinado. El atributo WebPartZoneId identifica a la vista de formulario con el identificador de una zona de elementos Web en particular, como se ha descrito anteriormente. Un elemento Form para uno de los tipos pueden contener los subelementos opcionales siguientes: ListFormOpening construye el formulario de entrada oculto publicado a travs de la forma, y tambin bloques de scripts que contienen mtodos para responder a los eventos de interfaz de usuario. ListFormButtons define la barra de herramientas de elemento de la lista y los comandos que contiene. ListFormBody construye la secuencia de comandos que se inserta en la pgina con el fin de construir los controles para mostrar o escribir valores para cada campo.Tambin crea toda la informacin que aparece en la parte inferior de la forma debajo del elemento. ListFormClosing utilizada en el punto de edicin y creacin forma de definir la interfaz de usuario alternativa que aparece cuando el usuario hace clic en Adjuntar archivoen la barra de herramientas.

WebParts contiene declaraciones de los elementos Web incluidos en el formulario de elemento de lista. Este elemento contiene un elemento View o elemento AllUsersWebPart . Utilice el elemento de visualizacin para elementos web que transmiten las vistas de lista, donde se define la visin transmitida a travs de la participacin en un esquema CAML, el uso de la AllUsersWebPart para todos los otros tipos de elementos web.

El propsito principal de estos subelementos es servir como separadores entre las secciones convenientes en la definicin de formulario para ayudar en el diseo de la pgina.Puede modificar sus contenidos de forma individual, eliminarlos por completo, o unirlos en un solo elemento. De hecho, el elemento de formulario puede contener la definicin del formulario completo directamente, sin la mediacin a travs de cualquiera de estos elementos. Nota Para ayudar a asegurar que las formas que personalice va a funcionar bien en versiones futuras de Windows SharePoint Services, debe utilizar Microsoft ASP.NET controles para personalizar los formularios. La modificacin del contenido de los elementos de formulario en SCHEMA.XML no puede llevar ms de si los cambios en la infraestructura de formulario en versiones futuras de Windows SharePoint Services.

Creacin de una definicin de sitio personalizada


Siga esta gua importante a la hora de personalizar las definiciones de sitio o de lista: Trabajo de las copias de los archivos de SharePoint nativos, y de no modificar los archivos originales. Crear una definicin de sitio personalizada de una definicin de sitio instalada originalmente, por ejemplo, la definicin estndar STS o MPS para la definicin Reuniones. Nota Para revisar una tarea de programacin que gua a travs del proceso de creacin de una definicin de sitio personalizada, consulte Creacin de una definicin de sitio a partir de una definicin de sitio existente . Trabajando a partir de una copia de una definicin de sitio ayuda a garantizar la reutilizacin del cdigo y protege sus personalizaciones cuando los parches o actualizaciones se aplican a la implementacin. En las secciones siguientes se describen las tareas que puede realizar para personalizar una definicin de sitio. Antes de comenzar las tareas siguientes, sin embargo, crear una definicin de sitio personalizada y probar los ejemplos en las secciones siguientes slo en los archivos copiados de su definicin.

Adicin de navegacin hacia la izquierda a travs de un formulario Controles de servidor Web


El rea de navegacin izquierda en formularios de elementos de lista est en blanco de forma predeterminada, pero se pueden aadir enlaces a utilizar esta zona. Como se muestra en la Figura 1, el estilo de tabla ms-navframe indica que esta rea, la cual aparece lo siguiente en la pgina ASPX.

Copiar <- Navegacin -> <TR> <TD Valign=top height=100% class=ms-nav> <TABLA height = 100% class = ms-navframe cellpadding = 0 = 0 CELLSPACING border = "0" width = 126px> <tr> <td valign=top width=100%> </ td> <td valign = top class = ms-verticaldots> </ td> </ tr> </ TABLE> </ TD> <- Contenido ->

Vamos a demostrar tres formas de aadir navegacin a la izquierda para el archivo DispForm.aspx de una lista de tareas. Cada mtodo contribuye a una interfaz de usuario consistente y fcil mantenimiento del enlace debido a que su cdigo est centralizada y se puede modificar desde una nica ubicacin. Usted puede agregar funciones de navegacin a la izquierda a travs de: Insercin del control de ViewSelector en la pgina para ofrecer a los usuarios elegir entre las vistas de lista de tareas. Insercin de controles de navegacin para visualizar particulares vnculos de Inicio rpido. Insercin de un control de servidor web personalizado que devuelve y muestra los elementos de una lista centralizada de SharePoint enlaces.

El siguiente ejemplo trata de modificar el archivo DispForm.aspx de una definicin de lista de tareas personalizada y la creacin de un control de servidor Web en Microsoft Visual Studio. NET que utiliza el espacio de nombres Microsoft.SharePoint para devolver los elementos enlaces de la lista, y los System.Web.UI.WebControls espacio de nombres para crear la interfaz de usuario para su visualizacin. La Figura 2 muestra el rea de navegacin izquierda, que ofrece a los usuarios acceso inmediato a los recursos importantes que pueden estar relacionados con la tarea.

Figura 2. rea de navegacin izquierda de una lista de tareas Para insertar una vista de vnculos Selector y Quick Launch 1. Abrir la pgina DispForm.aspx de la definicin de lista de tareas Local_Drive:\ Program Files\Common Files\Microsoft Shared\web server extensions\60\TEMPLATE\ Locale_ID\Custom_Site_Definition \ LISTS\TASK S , y busque la tabla ms-navframe mostrado anteriormente. En este ejemplo se reemplaza el espacio de no separacin primero en esta seccin con tres filas que contienen tres tablas que contribuyen diferentes partes del rea de navegacin izquierda. Vuelva a colocar el espacio de no separacin por primera vez en la anterior msnavframe mesa con una tabla como la siguiente, que se inserta un selector de vista dentro de la clula que contiene el espacio de no separacin. Copiar <TABLE Style="margin-left: 3px" width=115px> <TR> <TD> Seleccione una vista </ TD> </ TR> <TR> <TD Class="ms-navline"> <IMG SRC="/_layouts/images/blank.gif"> </ TD> </ TR> <TR> <TD> <SharePoint:ViewSelector Runat="server"/> </ TD> </ TR> </ TABLE> </ Td> </ tr>

2.

3.

Aadir un cdigo como el siguiente de la fila anterior, que inserta una tabla que contiene los enlaces de Quick Launch que aparecen en los documentos y de las partidas que aparecen en los foros de la pgina principal: Copiar <tr> <td> <TABLE Style="margin-left: 3px" width=115px> <TR> <TD> Recursos </ TD> </ TR> <TR> <TD Class="ms-navline"> <IMG SRC="/_layouts/images/blank.gif"> </ TD> </ TR> <TR> <TD Style="padding-left:10px"> <SharePoint:Navigation LinkBarId="1004" runat="server"/> </ TD> </ TR> <TR> <TD Style="padding-left:10px"> <SharePoint:Navigation LinkBarId="1006" runat="server"/> </ TD> </ TR> </ TABLE>

4.

Restablecer los Servicios de Microsoft Internet Information Server (IIS) para que los cambios realizados surtan efecto.

Para crear e implementar un control de servidor Web 1. 2. Crear una lista de enlaces llamados OrgList que puede utilizar para mantener la lista de enlaces que el control de servidor Web mostrar. Agregar elementos a la nueva lista. En Microsoft Visual Studio. NET, cree un proyecto de biblioteca de controles Web por seleccionando Nuevo en el men Archivo, hacer clic en Proyecto. En este ejemplo, el proyecto se denomina ServerControl1. Para establecer la ruta de salida de la compilacin de la wwwroot/bin directorio, haga clic en el nombre del proyecto en el Explorador de soluciones, haga clic enPropiedades. En el cuadro de dilogo Pginas de propiedades bajo Propiedades de configuracin, haga clic en Generar para establecer el valor de la ruta de salida aLocal_Drive :\Inetpub\wwwroot\bin . La DLL del proyecto que cree debe residir en este directorio para que el control funcione. Agregue una referencia al ensamblado de servicios de Windows SharePoint. Para ello, haga clic en Referencias en el Explorador de soluciones, haga clic en Agregar referencia y, en la ficha. NET, haga clic en Windows SharePoint Services. Haga clic en Aceptar. Para importar los espacios de nombres no se hayan incluido por defecto en el proyecto, agregue las siguientes directivas cerca del principio del archivo. Cs en el proyecto. Copiar utilizando Microsoft.SharePoint; utilizando Microsoft.SharePoint.WebControls; utilizando System.Web.UI.HtmlControls;

3.

4.

5.

6.

Para devolver los datos de lista de SharePoint y crear controles para que aparezca, reemplace el mtodo Control.CreateChildControls.

Copiar protegidas override void CreateChildControls () { strLitCtrl1 cadena = "<style = TABLA \" margin-left: 3px \ "" + "Width = 115px cellpadding = 0 cellspacing = 2 border = 0>" + "<TR> <TD Width=100%> Organizacin </ TD> </ TR>" + "<TR> <TD Class=\"ms-navline\">" + "<Img src = \" / _layouts / images / blank.gif \ "width =" 1 + "Height = 1 alt = \" \ "> </ TD> </ TR> </ TABLE> <TABLE>"; LiteralControl tblStart = new LiteralControl (strLitCtrl1); Controls.Add (tblStart); SPSite siteColl = SPControl.GetContextSite (contexto); SPList list = siteColl.RootWeb.Lists ["OrgLinks"]; Artculos SPListItemCollection = list.Items; foreach (artculo SPListItem en artculos) { strStart cadena = "<TR> <TD width=9px>" + "<Img src = \" / _layouts / images / blank.gif \ "" + "Width = 1 height = 1 alt = \" \ "> </ TD>" + "<TD Style=\"padding-bottom: 6px\">"; LiteralControl rowStart = new LiteralControl (strStart); Controls.Add (rowStart); cadena MyString = item ["URL"] ToString ().; int indexComma myString.IndexOf = (","); cadena strUrl = myString.Substring (0, indexComma); cadena = strTitle myString.Substring (indexComma + 2); HtmlAnchor orgLink = new HtmlAnchor (); orgLink.HRef = strUrl; orgLink.Title = strTitle; orgLink.Target = "_self"; orgLink.InnerText = strTitle; Controls.Add (orgLink); strEnd cadena = "</ TD> </ TR>"; LiteralControl rowEnd = new LiteralControl (strEnd); Controls.Add (rowEnd); } LiteralControl tblEnd = new LiteralControl ("</ TABLE>"); Controls.Add (tblEnd); }

El procedimiento anterior se inicia mediante un control LiteralControl para crear la seccin de apertura irrepetible de la tabla y, a continuacin, recorre todos los elementos de la lista y agrega una fila por cada artculo devuelto. Debido a que el item["URL"] indexador devuelve la URL y el texto interior (el texto del enlace) en la URLde la forma, Inner_Text, el

ejemplo se analizan las dos cadenas utilizando el mtodo String.Substring, a continuacin, asigna a la Href y propiedades Title de un controlHtmlAnchor. 7. Utilice el mtodo Control.RenderChildren dentro del mtodo sustituto Control.Render, como sigue. Copiar RenderChildren (salida);

8.

Para construir el control de servidor Web, en el men Generar, haga clic en Generar solucin o presione CTRL + SHIFT + B. 9. Para utilizar el control, debe registrarse como un control de errores en Windows SharePoint Services mediante sn.exe para crear un par de claves, y registrar el control en el /wwwroot/web.config archivo. Para obtener informacin sobre este proceso, que es el mismo utilizado para registrar los elementos web, consulte "Registrar el elemento web como un SafeControl" en Creacin de un elemento web bsico . 10. Agregue una directiva en la parte superior de DispForm.aspx para registrar el control de servidor personalizado, como sigue, reemplazando el valor PublicKeyTokenutilizado en el ejemplo con el valor real PublicKeyToken de su control. Copiar <% @ Register tagprefix = "OrgLinks" Namespace = "ServerControl1" Asamblea = "ServerControl1, Version = 1.0.0.0, Culture = neutral, PublicKeyToken = 73af0f2b510c7894 "%>

11. Despus de la fila agregada en el paso 3 del procedimiento de Insercin de un selector de vista y enlaces QuickLaunch (vase Adicin de navegacin hacia la izquierda a travs de un formulario Controles de servidor Web ), agregue el control de servidor mediante declaracin de la siguiente manera. Copiar <TR> <TD> <OrgLinks:WebCustomControl1 Runat="server"/>

12. Para que los cambios surtan efecto, reinicie IIS. Puede insertar el control de servidor web personalizado en numerosas pginas en una implementacin, pero la URL que se muestra se pueden administrar desde una sola ubicacin, la lista denominada OrgList que cre anteriormente.

Incorporacin de un elemento web en una forma y en la pgina de inicio para mostrar datos de lista
En SharePoint Team Services de Microsoft, la versin anterior de Microsoft Windows SharePoint Services, puede insertar una vista de lista CAML dentro de una isla de datos XML (indicado por <ows:XML> ) directamente en la pgina HTML. Para ver ejemplos de este procedimiento, consulte Custom Views CAML en SharePoint Team Services . Las vistas personalizadas que se describen en este artculo son estticos, lo que significa que necesita para incrustar su cdigo en el cdigo fuente de la pgina de inicio. En Windows SharePoint Services, las vistas de lista se transmiten a travs de los elementos Web, utilizando los tipos y miembros del espacio de nombres Microsoft.SharePoint acceder a los datos de la lista, y controles ASP.NET para crear la interfaz de usuario. Los elementos Web son inherentemente dinmicos, y a diferencia de los anteriores puntos de vista CAML personalizados, su cdigo no necesita estar contenido dentro de la fuente. En este ejemplo, pasos a travs del proceso de creacin de un elemento web que muestra las tareas que pertenecen al usuario actual, y la incrustacin de la parte en forma de visualizacin de los elementos de tarea y en la pgina de inicio. La Figura 3 muestra el elemento Web en la forma de visualizacin, que muestra las tareas pendientes del usuario actual, si existe.

Figura 3. Atrasado tareas de elementos web Advertencia Adicin de una vista de lista de elementos Web (ListViewWebPart clase) a un formulario de elemento de lista o archivo default.aspx en Windows SharePoint Services puede causar efectos negativos en el comportamiento de la pgina. Adicin de ms de una lista

relacionada con el elemento web a una pgina, como el que se utiliza en este ejemplo, no es compatible. Para crear una vista de lista personalizado y agregarlo a un formulario 1. Crear un elemento web como se describe en Creacin de un elemento web bsico , en sustitucin de SimpleWebPart con OverdueTasksPart en el procedimiento global.Para resumir brevemente, el proceso de creacin de un elemento web implica los siguientes pasos: a. En Visual Studio. NET, cree una aplicacin de elementos Web. b. Establece la ruta de construccin del proyecto a C:\inetpub\wwwroot\bin . c. Usando sn.exe, dar el ensamblado un nombre seguro y, a continuacin, modificar AssemblyInfo.cs en consecuencia. d. En el archivo de WebPart1.cs del elemento web, agregue el cdigo a ejecutar. e. En el archivo \ wwwroot web.config, registrar el elemento web como un control seguro. f. Modificar el proyecto. Dwp. En la parte superior del archivo. Cs, aadir directivas para importar los espacios de nombres necesarios. Copiar using System; utilizando System.Text.RegularExpressions; utilizando System.ComponentModel; utilizando System.Web.UI; utilizando System.Web.UI.WebControls; mediante System.Xml.Serialization; utilizando Microsoft.SharePoint; utilizando Microsoft.SharePoint.Utilities; utilizando Microsoft.SharePoint.WebControls; utilizando Microsoft.SharePoint.WebPartPages;

2.

3.

Reemplace el cdigo de ejemplo SimpleWebPart dentro del mtodo Control.CreateChildControls con el siguiente cdigo, que se inicia la construccin de una mesa para ver los datos de la lista. Copiar Label Label lblTable = new (); lblTable.Font.Name = "Verbena"; lblTable.Text = "Sus Tareas atrasadas"; lblTable.Font.Size = FontUnit.Larger; lblTable.Font.Bold = true; lblTable.ForeColor = System.Drawing.Color.Red; this.Controls.Add (lblTable); Tabla tbl = nueva tabla (); tbl.BorderWidth = 1;

this.Controls.Add (tbl); TableRow rowHeader = new TableRow (); rowHeader.Font.Size = FontUnit.Parse (".68 em"); rowHeader.Font.Bold = true; rowHeader.BackColor = System.Drawing.Color.LightGray; rowHeader.ForeColor = System.Drawing.ColorTranslator.FromHtml ("# 003399"); TableCell cellHeader1 = new TableCell (); cellHeader1.Text = "Ttulo"; rowHeader.Cells.Add (cellHeader1); TableCell cellHeader2 = new TableCell (); cellHeader2.Text = "Prioridad"; rowHeader.Cells.Add (cellHeader2); TableCell cellHeader3 = new TableCell (); cellHeader3.Text = "Fecha de Vencimiento"; rowHeader.Cells.Add (cellHeader3); tbl.Rows.Add (rowHeader);

4.

Inmediatamente despus del cdigo aadido en el paso 2, agregue cdigo que itera a travs de todas las listas de tareas del sitio actual para devolver y mostrar ningn artculo en mora que pertenecen al usuario actual. Copiar SPWeb currentSite = SPControl.GetContextWeb (contexto); wpVisible int = 0; Listas SPListCollection = currentSite.Lists; foreach (SPList list in lists) { if (list.ItemCount > 0 && list.BaseTemplate == SPListTemplateType.Tasks) { SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name = \"AssignedTo\"/>" + "<Value Type=\"Integer\"><UserID/></Value></Eq></Where>"; SPListItemCollection listItems = list.GetItems(query); foreach (SPListItem item in listItems) { if (item["Due Date"] != null && item["Assigned To"] != null && item["Status"].ToString() != "Completed") { if (Convert.ToDateTime(item["Due Date"]) <= System.DateTime.Now) {

TableRow row = new TableRow(); string frmUrl = userSite.Url + "/" + list.Forms[PAGETYPE.PAGE_DISPLAYFORM].Url.ToString(); string strUrl = "<a href=\"" + frmUrl + "?ID=" + item.ID.ToString() + "\">" + item["Title"].ToString() + "</a>"; TableCell cell1 = new TableCell(); cell1.Text = strUrl; cell1.BorderWidth = 1; row.Cells.Add (CLULA1); TableCell cell2 = new TableCell(); cell2.Text = item["Priority"].ToString(); cell2.BorderWidth = 1; row.Cells.Add (Celda2); TableCell cell3 = new TableCell(); if (item["Due Date"]!= null) { cell3.Text = item["Due Date"].ToString(); } ms { cell3.Text = ""; } cell3.BorderWidth = 1; row.Cells.Add (cell3); tbl.Rows.Add(row); wpVisible = 1; } } } } } if (wpVisible == 0) { this.Visible = false; }

The example uses the GetItems(Microsoft.SharePoint.SPQuery) method to return survey responses for the current user, constructing and assigning a CAML string to theQuery property of an SPQuery object, which is then passed as the parameter of the GetItems method. The example uses a wpVisible flag to determine whether the Web Part is visible. If the user has any overdue items, the flag is set to 1 and the Web Part is visible.

5.

Replace the code in the RenderWebPart method with the following code to render the controls added in the example. Copiar EnsureChildControls(); RenderChildren(output);

6. 7. 8.

9.

To build the Web Part, on the Build menu, click Build Solution , or press CTRL+SHIFT+B . Register the Web Part as a safe control in Windows SharePoint Services (for details, see "Register your Web Part as a SafeControl" in Creating a Basic Web Part) . In Notepad or another text editor, open SCHEMA.XML at Local_Drive: \Program Files\Common Files\Microsoft Shared\web server extensions\60\TEMPLATE\Locale_ID\Custom_Site_Definition \ LISTS\TASKS and find the Form element for the display item form, which starts with <Form Type="DisplayForm" Url="DispForm.aspx" WebPartZoneID="Main">. Add the following code immediately before the closing <Form> tag of the display item form, replacing the PublicKeyToken value used in the example with the actualPublicKeyToken value of your Web Part. Copiar <WebParts> <AllUsersWebPart WebPartZoneID="Main" WebPartOrder="2"> <! [CDATA [ <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2"> <Assembly> OverdueTasksPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=33c030758c3fa08e</Assembly> <TypeName>OverdueTasksPart.WebPart1</TypeName> <Title>Your Overdue Tasks</Title> <Description></Description> Ninguno <FrameType> </ FrameType> </WebPart>]]> </ AllUsersWebPart> </WebParts>

The FrameType value is set to None so that the standard Web Part frame and title bar are not displayed. This Web Part is displayed second in order within the Web Part zone with the ID of Main , although you could add another Web Part zone to the ASPX page and the Web Part could then be identified with the new zone. 10. Save your changes to SCHEMA.XML , and then reset IIS. You may also need to create a new list through the list definition for the changes to take effect.

To add the custom view to the home page 1. To embed the overdue tasks view in the home page, open the ONET.XML file at C:\Program Files\Common Files\Microsoft Shared\web server extensions\60\TEMPLATE \ Locale_ID\Custom_Site_Definition \ XML and find the first Module element ( Name="Default" ) in the collection of Module elements located at the end of the file. After the following View element : Copiar <View List="103" BaseViewID="0" WebPartZoneID="Right" WebPartOrder="2"/>

2.

Place an AllUsersWebPart element , such as the one added in the previous step, but replace the PublicKeyToken value used in the example with the actual PublicKeyTokenvalue of your Web Part. Copiar <AllUsersWebPart WebPartZoneID="Left" WebPartOrder="3"> <! [CDATA [ <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2"> <Assembly>WPContainer1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=33c030758c3fa08e</Assembly> <TypeName>OverdueTasksPart.WebPart1</TypeName> Ninguno <FrameType> </ FrameType> <Title>Your Overdue Tasks</Title> </WebPart>]]> </ AllUsersWebPart>

3.

Save your changes to ONET.XML, and then reset IIS.

Creating a Form to Extend the Reach of a Survey


As we saw in the previous example, you can add a list view to a list item form. In addition, you can add a list item form to a Web Part zone in the AllItems.aspx page for viewing a list, or in the home page. Web Parts provide a means for extending the reach of list item forms to various locations in a site. By using Web Parts and the Microsoft .NET Framework to construct a form, you have an alternative to using CAML schema customizations, as discussed in Advanced Customizations . The following example shows how to make a list item form for a survey that appears on the home page if the current user hasn't already taken the survey. The form includes validation for the fields, and when the user clicks Submit , a message appears with a button for closing the form. Figure 4 shows the Web Part as displayed on the home page.

Figura 4. Web Part conveying a survey form To create a Web Part for extending a survey 1. To run the following example, create a simple survey called TestSurvey in the top-level site of the site collection in which you want to deploy the form. Use the following four questions for the survey, using the indicated column types. o Is your group interested in attending the conference? (Yes/No (check box)) o City (single line of text) o Level (choice (menu to choose from)) o Zip Code (single line of text) Create a Web Part as described in Creating a Basic Web Part , replacing SimpleWebPart with TestSurvey in the procedure globally. At the top of the .cs file, add directives to import the required namespaces as follows. Copiar using System; using System.ComponentModel; utilizando System.Web.UI; utilizando System.Web.UI.WebControls; using System.Xml.Serialization; using Microsoft.SharePoint; using Microsoft.SharePoint.Utilities; using Microsoft.SharePoint.WebControls; using Microsoft.SharePoint.WebPartPages; utilizando System.Web.UI.HtmlControls;

2. 3.

4.

Declare variables to use within the class of the .cs file. Copiar

private SPSite siteCollection; private SPList list; private SPListItemCollection items; private private private private private private private private RadioButton radio1; RadioButton radio2; HtmlInputText textbox1; HtmlInputText textbox2; DropDownList dropdown1; HtmlButton button1; Label label5; HtmlAnchor closepart;

5.

Define a button1_click event for the Submit button, which gathers the data the user entered and adds a new item to the list. The procedure also changes the visibility of a label for displaying a message and of a button to close the Web Part to true . Copiar SPListItem item = items.Add(); if (radio1.Checked == true) { item["Is your group interested in attending the conference?"] = "1"; } ms { item["Is your group interested in attending the conference?"] = "0"; } item["City"] = textbox1.Value; item["Level"] = dropdown1.SelectedItem.Value; item["Zip_x0020_ Code"] = textbox2.Value; item.Update (); label5.Text = "Thanks for taking the survey!"; label5.Visible = true; closepart.Visible = true; siteCollection.Close();

6.

Define a closepart_click event for the button to close the form. Copiar public void closepart_click (object sender, EventArgs e) { this.Visible = false;

7.

Use the Control.CreateChildControls method override to build the user interface programmatically, first checking if the current user has already taken the survey and, if so, hiding the form and exiting the procedure. Copiar siteCollection = SPControl.GetContextSite(Context); list = siteCollection.RootWeb.Lists["TestSurvey"]; SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name = \"Author\"/>" + "<Value Type=\"Integer\"><UserID/></Value></Eq></Where>"; items = list.GetItems(query); if (items.Count > 0) { this.Visible = false; volver; }

The example uses the GetItems(Microsoft.SharePoint.SPQuery) method to return survey responses for the current user, constructing a CAML string and assigning it to theQuery property of an SPQuery object, which is then passed as the parameter of the GetItems method. 8. If the user has not already taken the survey, the example proceeds to construct the user interface using .NET Framework controls. You can group option buttons by using the RadioButton.GroupName property, as follows. Copiar Controls.Add(new LiteralControl("<BR>")); Etiqueta de label1 = new Label (); label1.Text = "Is your group interested in attending the conference? "; Controls.Add(label1); Controls.Add(new LiteralControl("<BR><BR>")); radio1 = new RadioButton(); radio1.Text = "Yes"; radio1.Checked = true; radio1.GroupName = "interest"; Controls.Add(radio1); radio2 = new RadioButton(); radio2.Text = "No"; radio2.GroupName = "interest";

Controls.Add(radio2);

Use a RequiredFieldValidator control to verify that values are specified for required fields. Copiar Controls.Add(new LiteralControl("<BR><BR>")); Label label2 = new Label(); label2.Text = "City "; Controls.Add(label2); textbox1 = new HtmlInputText(); textbox1.Value=""; textbox1.ID = "ctlWhere"; Controls.Add(textbox1); RequiredFieldValidator rfValid1 = new RequiredFieldValidator(); rfValid1.ControlToValidate = "ctlWhere"; rfValid1.ErrorMessage = "Please specify the name of a city."; rfValid1.Display = System.Web.UI.WebControls.ValidatorDisplay.Static; Controls.Add(rfValid1);

To apply the RequiredFieldValidator control to a drop-down list box, use the InitialValue property to determine whether the user made a selection, as follows. Copiar Controls.Add(new LiteralControl("<BR><BR>")); Label label3 = new Label(); label3.Text = "Level "; Controls.Add(label3); dropdown1 = new DropDownList(); dropdown1.ID = "ctlLevel"; dropdown1.Items.Add(new ListItem("Select Level","Select Level")); dropdown1.Items.Add(new ListItem("One","One")); dropdown1.Items.Add(new ListItem("Two","Two")); dropdown1.Items.Add(new ListItem("Three","Three")); Controls.Add(dropdown1); RequiredFieldValidator rfValid2 = new RequiredFieldValidator(); rfValid2.ControlToValidate = "ctlLevel"; rfValid2.ErrorMessage = "Please specify a level."; rfValid2.InitialValue = "Select Level"; rfValid2.Display = System.Web.UI.WebControls.ValidatorDisplay.Static; Controls.Add(rfValid2);

Use the RegularExpressionValidator control to make sure the user types values in special fields in the expected format, such as the following example, which verifies values entered for the zip code box that is created. Copiar Controls.Add(new LiteralControl("<BR><BR>")); Label label4 = new Label(); label4.Text = "Zip Code "; Controls.Add(label4); textbox2 = new HtmlInputText(); textbox2.Value=""; textbox2.ID = "ctlZip"; Controls.Add(textbox2); RequiredFieldValidator rfValid3 = new RequiredFieldValidator(); rfValid3.ControlToValidate = "ctlZip"; rfValid3.ErrorMessage = "Please specify a zip code."; rfValid3.Display = System.Web.UI.WebControls.ValidatorDisplay.Static; Controls.Add(rfValid3); RegularExpressionValidator regex = new RegularExpressionValidator(); regex.ControlToValidate = "ctlZip"; regex.ValidationExpression = "[0-9]{5}(-[0-9]{4})?"; regex.Text = "Please enter a valid zip code."; regex.Display = System.Web.UI.WebControls.ValidatorDisplay.Static; Controls.Add(regex);

Use the HtmlAnchor.ServerClick event to associate a button click with a specific event handler: Copiar Controls.Add(new LiteralControl("<BR><BR>")); button1 = new HtmlButton(); button1.InnerText = "Submit"; button1.ServerClick += new EventHandler (button1_click); Controls.Add (button1);

To prevent a control from being visible initially, set its Visible property to false when creating the control. Copiar Controls.Add(new LiteralControl("<BR><BR>")); label5 = new Label(); label5.Visible = false; Controls.Add(label5);

Controls.Add(new LiteralControl("<BR><BR>")); closepart = new HtmlAnchor(); closepart.InnerText = "Close"; closepart.ServerClick += new EventHandler (closepart_click); closepart.Visible = false; Controls.Add (closepart); siteCollection.Close();

9.

The RenderWebPart method renders the controls on the page. Copiar RenderChildren(output);

10. To build the Web Part, on the Build menu, click Build Solution , or press CTRL+SHIFT+B . 11. Register the Web Part as a safe control in Windows SharePoint Services (for details, see "Register your Web Part as a SafeControl" in Creating a Basic Web Part) . 12. To import the Web Part into a home page, click Modify Shared Page on the home page, point to Add Web Part , click Import , browse to the .dwp file of the Web Part, and click Upload . Drag the part into a zone. Note This example assumes the existence of a survey list like the one represented in Figure 4 that is located in the top-level site of the site collection.

Advanced Customizations
The following sections describe advanced customizations that might not carry over into future versions of Windows SharePoint Services if the form infrastructure changes. The tasks involve customizing Form elements in SCHEMA.XML , rather than using ASP.NET controls, to customize forms.

Modifying the Toolbar and Body in a Form


This task involves adding code to the SCHEMA.XML file of the Tasks list definition that adds a different link to the toolbar and different additional text in the body depending on certain conditions. If the item has an attachment, a different link is added to the toolbar depending on the priority of the task. A link does not appear if the priority is low or if there is no attachment. Figure 5 shows the text that is displayed to draw the user's attention to the additional link on the toolbar.

Figura 5. Custom text and link displayed in a form To modify the toolbar and body in a form 1. In Notepad or another text editor, open the SCHEMA.XML file of the Tasks list in your custom site definition at Local_Drive:\ Program Files\Common Files\Microsoft Shared\web server extensions\60\TEMPLATE \ Locale_ID\Custom_Site_Definition\ LISTS\TASK S. To add a link at the end of the toolbar, find the ListFormButtons element in the form definition for the DisplayForm type and locate the following table cell near the end of this section, which defines the Go Back to List link. Copiar <TD class="2ms-toolbar"> <table cellpadding=1 cellspacing=0 border=0> <tr><td colspan=2 nowrap> <a tabindex=2 class="ms-toolbar" ACCESSKEY=G ID=diidIOGoBack href="]]></HTML> <ListProperty Select='DefaultViewUrl'/> <HTML><![CDATA[" onclick="javascript:GoBack(']]></HTML> <ScriptQuote NotAddingQuote="TRUE"> <ListProperty Select="DefaultViewUrl"/></ScriptQuote> <HTML><![CDATA[');return false;" target="_self"> <LocID ID="L_GOBackItem">]]></HTML> <HTML>Go Back to List</HTML> <HTML><![CDATA[</LocID> </a></td></tr></table> </ TD>

2.

The example shows how CAML is frequently used to prepare HTML for the browser, where certain elements are used to intersperse item, list, and project property values within the markup language sections contained in HTML elements. In this example, we use the ListProperty element to return the URL of the default view for the list.

Good resources for discovering possible values that you can assign to the Select attribute of ListProperty include the natively installed CAML files, as well as attributes listed for the List element , and numerous properties of the SPList class . You can use the ProjectProperty element , Property element , and ServerProperty element to return sitescoped or server-scoped Windows SharePoint Services property values. 3. Add the following code example immediately after the last closing table cell tag ( </TD> ) shown in the code example of step 2 for the Go Back to List button, which adds an additional cell if the item has an attachment and the Priority field contains High or Medium . Copiar <!--Add the following code--> ]]></HTML> <Switch> <Expr><Field Name="Attachments"/></Expr> <Case Value=""/> <Default> <Switch> <Expr><Field Name="Priority"/></Expr> <Case Value="(1) High"> <HTML><![CDATA[ <TD class=ms-separator>|</td> <TD class="2ms-toolbar"> <table cellpadding=1 cellspacing=0 border=0> <tr><td colspan=2 nowrap> <a tabindex=2 class="ms-toolbar" href="FirstUrl">High Priority Resolution Guidelines </a><br></td></tr></table></TD>]]> </ HTML> </Case> <Case Value="(2) Normal"> <HTML><![CDATA[ <TD class=ms-separator>|</td> <TD class="2ms-toolbar"> <table cellpadding=1 cellspacing=0 border=0> <tr><td colspan=2 nowrap> <a tabindex=2 class="ms-toolbar" href="SecondUrl"> Guidelines</a> </td></tr></table></TD>]]> </ HTML> </Case> <Default></Default> </Switch> </Default> </Switch> <HTML><![CDATA[

The example interposes nested Switch element statements within the page definition, evaluating first the Attachments field and then the Priority field to create the appropriate

HTML. If the Attachments field evaluates to an empty string, then no action is taken. If there is an attachment, a different URL is provided in the toolbar depending on the priority. The default is to add no URL to the toolbar when the priority is low. For a list of the fields available by default for a given list type that can be evaluated for an item, as shown in the example, see Field Tables for Default Lists . Note Replace the placeholders used as URLs in the example with actual links. 4. Find the following block of code near the end of the ListFormBody element , which creates the section line that appears at the bottom of the item form. Copiar <HTML><![CDATA[ <table border=0 cellpadding=0 cellspacing=0 width=100%> <tr><td>&nbsp;</td></tr> <tr><td class="ms-formlabel"> <table border=0 cellpadding=0 cellspacing=4 width=100%> <tr><td class="ms-sectionline" height=1>

5.

Replace the nonbreaking space (&nbsp;) in the previous cell with the following example, which uses the same nested Switch statements, as in step 3, to conditionally add text to the form body. Copiar ]]></HTML> <Switch> <Expr><Field Name="Attachments"/></Expr> <Case Value=""/> <Default> <Switch> <Expr><Field Name="Priority"/></Expr> <Case Value="(1) High"> <HTML><![CDATA[ <table border=0 cellpadding=0 cellspacing=0> <tr><td class="ms-formbody"> Click the High Priority Resolution Guidelines link on the toolbar for directions about completing this task.</td></tr><tr><td> <img border=0 width=1 height=3 src="/_layouts/images/blank.gif" alt=""> </td></tr></table>]]></HTML> </Case> <Case Value="(2) Normal"> <HTML><![CDATA[ <table border=0 cellpadding=0 cellspacing=0> <tr><td class="ms-formbody"> Click the Guidelines link on the toolbar for

directions about completing this task. </td></tr><tr><td> <img border=0 width=1 height=3 src="/_layouts/images/blank.gif" alt=""> </td></tr></table>]]></HTML> </Case> <Default> <HTML><![CDATA[ <table border=0 cellpadding=0 cellspacing=0> <tr><td class="ms-formbody"> You might find the attached file useful in preparing for this task, but its use is optional. </td></tr><tr><td> <img border=0 width=1 height=3 src="/_layouts/images/blank.gif" alt=""> </td></tr></table>]]></HTML> </Default> </Switch> </Default> </Switch> <HTML><![CDATA[

If the priority is high or normal, the example adds different text that draws attention to and explains the URL on the toolbar. If the priority is low, which is the default case, no additional link appears in the toolbar and so the message does not concern a URL. 6. For your changes to take effect, reset IIS. Note Your changes might not have an effect on existing lists; to see their effects, you might need to create a new list.

Adding Custom Script that Accesses Page Elements in an Edit Form


To respond to events that occur by using controls in the form, you can add script to the page created in the browser by tapping into existing script blocks of SCHEMA.XML. For the NewForm type, the ClickOnce method in the ListFormOpening element is called when the user clicks Save and Close , but for the EditForm type, SubmitForm is called. You can add a custom method to a script block contained in the ListFormOpening element and add a call to your custom method from the beginning of the existing Windows SharePoint Services method. Both the ClickOnce and SubmitForm methods call the ValidateAndSubmit method defined in OWS.JS, a major JavaScript file used in Windows SharePoint Services. When the user clicks buttons within the form, methods in OWS.JS are called to complete the post. In addition, OWS.JS methods build the user interface for each field displayed in the form. This example shows how to add script to validate a field that contains social security numbers, and script to display a message box acknowledging that an item has been added to a tasks list. As Figure 6 shows, if an incorrectly formed social security number is submitted in the form, a message box indicates that an invalid number is specified and the procedure to submit the form is exited. If

the number is valid, as Figure 7 shows, the form is submitted and a message box acknowledges that the item is added to the list.

Figura 6. Error message that results from an invalid social security number

Figura 7. Message box that acknowledges that an item is added to the list To add custom script that accesses page elements 1. In Notepad or another text editor, open SCHEMA.XML in the appropriate Local_Drive:\ Program Files\Common Files\Microsoft Shared\web server extensions\60\TEMPLATE \Locale_ID\Custom_Site_Definition\LISTS\TASK S directory. In the opening Fields element , make a small change to the order of the fields in the item form by moving the UserInfo and PercentComplete fields to the beginning of the form, interposing a new Field element between them for social security numbers, as follows. Copiar <FIELDS> <Field Type="User" List="UserInfo" Name="AssignedTo" DisplayName="Assigned To"></Field>

2.

<Field Type="Text" Name="SSN" DisplayName="Social Security Number"> </ Field> <Field Type="Number" Name="PercentComplete" Percentage="TRUE" Min="0" Max="1" DisplayName="% Complete"></Field>

3.

You can access current values contained by controls using the elements collection on the FORM element of the document object model, which returns an array containing references to all form elements. Use either the collection index or the name of an element as an indexer to specify a particular control (for example,document.forms[0].elements[elementName or index] ). To ascertain the name or index of controls, you can iterate through the collection of page elements using the name and value properties of each element to display all names and values of elements in the form. Find the ListFormOpening element for either the EditForm or NewForm type, and temporarily add code like the following to the beginning of the ClickOnce() or SubmitForm() method, reset IIS, and then create a new item in the list to display all the names and current values of elements in the form. Copiar var j; var showControls=""; for (j=0; j<document.forms[0].elements.length; j++) { showControls += document.forms[0].elements[j].name + " == " + document.forms[0].elements[j].value + "\n"; } alert(showControls); }

Running this script reveals that you can use the following element names to refer to current values for fields displayed in the custom list item form for tasks lists: o o o o o o o o o o o o o urn:schemas-microsoft-com:office:office#Title OWS:Priority:Dropdown OWS:Status:Dropdown OWS:PercentComplete:Local urn:schemas-microsoft-com:office:office#AssignedTo urn:schemas-microsoft-com:office:office#Body OWS:StartDate:Date OWS:StartDate:Hours OWS:StartDate:Minutes OWS:DueDate:Date OWS:DueDate:Hours OWS:DueDate:Minutes urn:schemas-microsoft-com:office:office#SSN

After you know which fields to reference, you're ready to delete this temporary example and add script to validate the new social security number field and display acknowledgment that the item was added. The script in this example uses the urn:schemas-microsoftcom:office:office#Title and custom urn:schemas-microsoft-com:office:office#SSN fields to return current values. 4. Add code like the following to the beginning of the ClickOnce() or SubmitForm() method in the edit or new item form, which calls a custom ValidateField method and prevents form submission if the method returns false . Copiar var myCheck = ValidateField(); if (myCheck == false) { volver; }

5.

Add a method call to the end of the ClickOnce() and SubmitForm() methods immediately before the closing curly brace. Copiar AcknowledgeSubmission();

6.

Add the following method to the end of the script block immediately before the closing Script tag in both the edit and new item forms, which uses the test method of aRegExp object to perform validation on the social security number field. Copiar function ValidateField() { var ssnField = "urn:schemas-microsoft-com:office:office#SSN"; var ssnBox = document.forms[0].elements[ssnField].value; var regEx = /^(\d{3})\-(\d{2})\-(\d{4})$/; var regx = new RegExp(regEx); var r = regx.test(ssnBox); if (r == false) { alert("Please specify a valid social security number."); return (false); } }

7.

To display a message box acknowledging that the item was submitted, add a function like the following after the custom method added in step 6. Copiar function AcknowledgeSubmission() { var listUrl = ]]></HTML> <ScriptQuote> <ListUrlDir WebRel="FALSE"/> </ScriptQuote> <HTML><![CDATA[; var columnName = "urn:schemas-microsoft-com:office:office#Title"; var confirmPosted = "Thank you for adding \"" + document.forms[0].elements[columnName].value + "\" to " + listUrl + "\.\n\n"; alert(confirmPosted); }

The example uses HTML CDATA partitioning and the ListUrlDir element with its WebRel attribute set to FALSE to return the full URL of the list, which in the resulting line of code in the browser is assigned to the listUrl variable. In other words, a complete line similar to the following is produced in the resulting page. Copiar var listUrl = "http://Server/sites/SiteCollection/Site/Lists/Tasks";

In the form for editing items, you can change the previous confirmPosted string to a message that is appropriate for the context of making changes to items. 8. After saving your changes to SCHEMA.XML, reset IIS so that they can take effect.

S-ar putea să vă placă și