Share via


Crear un complemento hospedado por el proveedor que incluya un tipo de contenido y una lista de SharePoint personalizados

Create a SharePoint Add-in that combines a cloud-hosted web application with custom SharePoint-hosted list templates, list instances, and custom content types by using the Office Developer Tools for Visual Studio. Learn how to interact with SharePoint add-in webs by using the REST/OData web service, and how to implement OAuth in a SharePoint Add-in.

La mayoría de los componentes clásicos de SharePoint (como tipos de contenido personalizados, definiciones de listas personalizadas y flujos de trabajo) se pueden incluir en un complemento de SharePoint hospedado en la nube. El ejemplo sencillo de este artículo contiene lo siguiente:

  • Una web de complemento con:

    • Algunas columnas de sitio personalizadas

    • Un tipo de contenido personalizado que usa las columnas personalizadas

    • Una plantilla de lista personalizada que usa el tipo de contenido personalizado

    • Una instancia de lista basada en la definición de lista personalizada

  • Una aplicación web ASP.NET que lee datos de la instancia de lista

Requisitos previos para crear este complemento de SharePoint

  • Visual Studio

  • Visual Studio includes the Microsoft Office Developer Tools for Visual Studio, but sometimes a version of the tools is released between updates of Visual Studio. To be sure that you have the latest version of the tools, run the installer for Office Developer Tools for Visual Studio 2013 or the installer for Office Developer Tools for Visual Studio 2015.

  • Una instalación de SharePoint para pruebas y depuración

    • Puede estar en el mismo equipo que el equipo de desarrollo, o bien puede desarrollar con una instalación de SharePoint remota. Si trabaja con una instalación remota, necesitará instalar el archivo redistribuible del modelo de objetos de cliente en la instalación del estilo. Está disponible como un paquete redistribuible en el Centro de descarga de Microsoft. Busque “SDK de componentes de cliente de SharePoint Server 2013” o “SDK de componentes de cliente de SharePoint Online”.

    • El sitio web de prueba de SharePoint debe crearse desde la definición de sitio del Sitio para desarrolladores (que puede crear en la Administración central).

    • Your remote web application communicates with the add-in web by using either JavaScript and the cross-domain library or OAuth. If OAuth is used, as it is in the continuing example of this article, the SharePoint installation must be configured to use OAuth.

    Nota

    Si necesita ayuda para configurar un entorno de desarrollo que se adapte a sus necesidades, vea Dos tipos de complementos de SharePoint: hospedado por SharePoint y hospedado por el proveedor.

Conceptos básicos que es importante conocer antes de crear un complemento

Antes de empezar a crear complementos, debe contar con nociones básicas de los complementos de SharePoint y las diferencias entre complementos de SharePoint hospedados en SharePoint y hospedados por el proveedor. Los artículos de la tabla siguiente deberían darle esas nociones.

Título del artículo Descripción
Complementos de SharePoint Obtenga información sobre el nuevo modelo de complementos de SharePoint, que permite crear complementos (pequeñas soluciones fáciles de usar para usuarios finales).
Aspectos importantes del entorno de desarrollo y la arquitectura de los complementos de SharePoint Obtenga información sobre aspectos de la arquitectura de los Complementos de SharePoint y el modelo para aplicaciones para SharePoint, como las opciones de hospedaje de complementos, las opciones de la interfaz de usuario (IU), el sistema de implementación, el sistema de seguridad y el ciclo de vida.
Seleccionar modelos para desarrollar y hospedar un complemento de SharePoint Obtenga información sobre las diferentes formas en que puede hospedar complementos de SharePoint.

Desarrollar un complemento de SharePoint

En los procedimientos presentados en esta sección, se crea un Complemento de SharePoint que incluye una web de complemento con componentes de SharePoint y una aplicación web remota en el equipo de desarrollo.

Para configurar la solución de Visual Studio y sus elementos

  1. In Visual Studio, create an Add-in for SharePoint project from the Office SharePoint | Add-ins node (under either C# or Visual Basic) in the templates tree of the New Project Wizard. Select the Provider-hosted hosting option. In the continuing example of this article, C# is used as the language, and LocalTheater is the project name.

  2. En el asistente, seleccione Finalizar.

  3. Abra el archivo AppManifest.xml en el diseñador de manifiesto. El elemento Title tiene el nombre del proyecto como valor predeterminado. Sustitúyalo por otro que sea más atractivo, ya que se trata del nombre del complemento que los usuarios verán en la IU.

  4. Specify a Name for the add-in. This is an internal name that must contain only ASCII characters and must contain no spaces; for example, LocalTheater.

  5. Abra el archivo Web.config en el proyecto de aplicación web y agregue el elemento <customErrors mode="Off"/> al elemento system.web.

  6. Check to see that references to the following assemblies are in the web application project. If your edition of Visual Studio did not add the references automatically, add them now.

    • Microsoft.IdentityModel.dll. This assembly is installed into the global assembly cache with Windows Identity Foundation (WIF). Because this is a .NET Framework 3.5 assembly, it is filtered out of the Framework node of the Add Reference dialog box by default. You can add a reference to it by browsing directly to the C:\Program Files\Reference Assemblies\Microsoft\Windows Identity Foundation\v3.5 directory of your development computer.

    • Microsoft.IdentityModel.Extensions.dll. You can add a reference to it by browsing directly to the C:\Program Files\Reference Assemblies\Microsoft\Microsoft Identity Extensions\1.0 folder of your development computer.

    • System.IdentityModel.dll. This assembly is part of the .NET Framework 4, and it appears on the Assemblies | Framework node of the Add Reference dialog box.

  7. If your remote web application accesses information in the host web as well as in the add-in web, you must add an AppPermissionRequests element, with one or more child AppPermissionRequest elements, to the AppManifest.xml file. (The web application in the continuing example of this article accesses only the add-in web. Add-in principals automatically have all permissions needed to the add-in web, so the AppManifest.xml in the example does not have an AppPermissionRequests element.) For more information about add-in permission requests and how to add them, see Add-in permissions in SharePoint.

Para agregar los componentes de SharePoint

You add SharePoint components to an add-in exactly as you would add them to a classic farm solution. However, not every kind of SharePoint component can be included in a SharePoint Add-in. The purposes these components serve are accomplished in other ways in SharePoint Add-ins.

Para obtener más información sobre los tipos de componente de SharePoint que pueden incluirse en un complemento de SharePoint y cómo incluirlos en un proyecto, vea Tipos de componentes de SharePoint que se pueden encontrar en un complemento para SharePoint.

A efectos del ejemplo en curso, use los procedimientos siguientes, que ofrecen ejemplos de uso de Visual Studio para agregar columnas personalizadas, tipos de contenido, plantillas de lista e instancias de lista a un complemento de SharePoint.

Para crear los tipos de columna personalizados

  1. En el Explorador de soluciones, agregue un elemento Columna de sitio de SharePoint al proyecto de complemento de SharePoint con el nombre Actor.

  2. In the elements.xml file for the new site column, edit the Field element so that it has the attributes and values shown in the following example, except that you should not change the GUID for the ID attribute from the value that Visual Studio generated for it. Don't forget the framing braces "{}".

    <Field ID="{generated GUID}" 
        Name="Actor" 
        Title="Actor" 
        DisplayName="Actor/Actress" 
        Group="Theater and Movies" 
        Description="The person cast, perhaps tentatively, in the role" 
        Type="Text" 
    />
  1. Agregue otra Columna de sitio al proyecto llamado EstadoCasting.

  2. En el archivo elements.xml de la nueva columna de sitio, edite el elemento Field para que tenga los atributos y valores que se muestran en el ejemplo siguiente, excepto que no tiene que cambiar el GUID del atributo ID del valor que generó Visual Studio para él.

  <Field ID="{generated GUID}" 
      Name="CastingStatus" 
      Title="CastingStatus"
      DisplayName="Casting Status" 
      Group="Theater and Movies" 
      Description="The current casting status of the role" 
      Type="Choice">
  </Field>
  1. Como este es un campo de elección, debe especificar las posibles opciones, el orden en que deben aparecer en la lista desplegable cuando un usuario efectúe la elección, y la opción predeterminada. Agregue el marcado secundario siguiente al elemento Field.
  <CHOICES>
      <CHOICE>Not Started</CHOICE>
      <CHOICE>Audition Scheduled</CHOICE>
      <CHOICE>Auditioned</CHOICE>
      <CHOICE>Role Offered</CHOICE>
      <CHOICE>Committed to Role</CHOICE>
  </CHOICES>
  <MAPPINGS>
      <MAPPING Value="1">Not Started</MAPPING>
      <MAPPING Value="2">Audition Scheduled</MAPPING>
      <MAPPING Value="3">Auditioned</MAPPING>
      <MAPPING Value="4">Role Offered</MAPPING>
      <MAPPING Value="5">Committed to Role</MAPPING>
  </MAPPINGS>
<Default>Not Started</Default>

Para crear el tipo de contenido personalizado

  1. In Solution Explorer, add a SharePoint Content Type item to the SharePoint Add-in project with the name ActingRole. When prompted by the wizard to select the base content type, select Item, and then select Finish.

  2. Si el Diseñador de tipo de contenido no se abre automáticamente, seleccione el tipo de contenido ActingRole en el Explorador de soluciones para abrirlo.

  3. Abra la pestaña Tipo de contenido del Diseñador y rellene los cuadros de texto tal y como se indica a continuación:

    • Nombre del tipo de contenido: ActingRole

    • Descripción: Representa un papel en una película o en una obra de teatro.

    • Nombre de grupo: Teatro y cine

  4. Verifique que ninguna de las casillas de la pestaña esté seleccionada. Es posible que, de forma predeterminada, la casilla Hereda las columnas del tipo de contenido primario esté seleccionada. Desactívela.

  5. Abra la pestaña Columnas del Diseñador.

  6. Use the grid to add the two site columns to the content type. They are listed in the drop-down list by their display names: Actor/Actress and Casting Status. (If they are not listed, you may not have saved the project since adding the custom site columns. Select Save all).

  7. Guarde el archivo y cierre el Diseñador.

  8. Para completar el paso siguiente es necesario trabajar directamente en el XML sin formato para el tipo de contenido; así que, en el Explorador de soluciones, seleccione el archivo elements.xml secundario del tipo de contenido ActingRole.

  9. There are already FieldRef elements in the file for the two columns that you added. Add FieldRef elements for two built-in SharePoint columns as peers of the two that are already there. The following is the markup for the elements. You must use these same GUIDs for the ID attribute because these are built-in field types with fixed IDs. Add these above the two FieldRef elements for the custom site columns.

  <FieldRef Name="LinkTitle" ID="{82642ec8-ef9b-478f-acf9-31f7d45fbc31}" DisplayName="Character" />
  <FieldRef Name="Title" ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" DisplayName="Character" />

Tenga en cuenta que hemos dado a estos campos el nombre para mostrar personalizado: Personaje, en el sentido de un personaje de una obra de teatro o una película.

Para crear la plantilla de lista personalizada y una instancia de lista

  1. Add a SharePoint List item to the SharePoint Add-in project with the name CharactersInShow. On the Choose List Settings page of the SharePoint Customization Wizard, leave the list display name at the default CharactersInShow, select the Create a customizable list based on option, and select Default (Blank) on the drop-down list. Select Finish.

  2. Cuando complete el asistente, se creará una plantilla de lista PersonajesDelEspectáculo con una instancia de lista secundaria llamada PersonajesEnInstanciaEspectáculo. Puede que, de forma predeterminada, se haya abierto un diseñador de listas. Se usará en un paso posterior.

  3. Abra el elemento secundario de elements.xml de la plantilla de lista CharactersInShow (no abra el elemento secundario de elements.xml de CharactersInShowInstance).

  4. Agregue espacios al atributo DisplayName para que sea más fácil leerlo: Personajes del espectáculo.

  5. Establezca el atributo Description en Los personajes de una película o una obra de teatro.

  6. Deje los demás atributos con su valor predeterminado, guarde el archivo y ciérrelo.

  7. Si el Diseñador de listas no se abre, seleccione el nodo CharactersInShow en el Explorador de soluciones.

  8. Abra la pestaña Columnas en el Diseñador y seleccione el botón Tipos de contenido.

  9. En el cuadro de diálogo Configuración de tipo de contenido, agregue el tipo de contenido ActingRole.

  10. Seleccione el tipo de contenido NewEmployee en la lista de tipos y elija el botón Establecer como predeterminado.

  11. Seleccione el tipo de contenido Item, haga clic con el botón derecho en la pequeña punta de flecha que aparece a la izquierda del nombre del tipo de contenido y luego haga clic en Eliminar.

  12. Repeat the preceding step for the Folder content type, so that ActingRole is the only content type listed. Select OK to close the dialog.

  13. Three columns are now in the list of columns. Select Title, right-click the small arrowhead that appears to the left of the content type name, and then select Delete. Only two columns should now be listed, Actor/Actress and Casting Status.

  14. Abra la pestaña Lista del diseñador. Esta pestaña se usa para configurar determinados valores de la lista instancia, no la lista plantilla.

  15. Cambie los valores de esta pestaña por los siguientes:

  • Título: Characters in Hamlet

  • URL de lista: Lists/CharactersInHamlet

  • Descripción: Los personajes de Hamlet e información sobre el casting.

Deje las casillas en su estado predeterminado, guarde el archivo y cierre el Diseñador.

  1. The list instance may have its old name in Solution Explorer. If so, open the shortcut menu for CharactersInShowInstance, select Rename, and change the name to CharactersInHamlet.

  2. Abra el archivo schema.xml.

  3. There may be two ContentType elements in the file, one with the Name attribute value of ActingRole and another called ListFieldsContentType. Only the one called ActingRole belongs, so delete any other ContentType elements.

    Nota

    No puede haber saltos de línea entre los elementos ContentType, en cuyo caso al principio puede parecer que solo hay uno. Desplácese a la derecha y compruebe atentamente la existencia de otros.

  4. The Fields element should have two Field elements (which are on a single line if there is no line break between them). One should exactly duplicate the Field element in the Actor site column elements.xml, and the other should exactly duplicate the Field element from the CastingStatus site column elements.xml. If there is not an exact match, including all child elements (such as the CHOICES and MAPPINGS elements), copy the Field element from the site column elements.xml file and paste it in place of the mismatched Field element in the schema.xml file.

  5. En el archivo schema.xml, en el elemento View cuyo valor BaseViewID es "0", sustituya el elemento ViewFields existente con el marcador siguiente. (Use exactamente este GUID para el FieldRef llamado LinkTitle).

  <ViewFields>
    <FieldRef Name="Title" ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" DisplayName="Character" />
    <FieldRef Name="Actor" ID="{GUID from the site column elements.xml}" />
    <FieldRef Name="CastingStatus" ID="{GUID from the site column elements.xml}" />
  </ViewFields>
  1. Replace the two missing ID attribute values with the GUIDs in the respective site column elements.xml files. Don't forget the framing braces "{}".

  2. En el archivo schema.xml, en el elemento View cuyo valor BaseViewID es "1", sustituya el elemento ViewFields existente por el marcador siguiente. (Use exactamente este GUID para el FieldRef llamado LinkTitle).

  <ViewFields>
    <FieldRef Name="LinkTitle" ID="{82642ec8-ef9b-478f-acf9-31f7d45fbc31}" DisplayName="Character" />
  </ViewFields>
  1. Copie los dos elementos FieldRef para Actor y CastingStatus que agregó en la vista anterior en este elemento ViewFields como elementos del mismo nivel del LinkTitle FieldRef.

  2. Guarde y cierre el archivo schema.xml.

  3. Abra el archivo elements.xml que es un elemento secundario de la instancia de lista PersonajesDeHamlet.

  4. Rellene la lista con algunos datos iniciales agregando el marcado siguiente como elemento secundario del elemento ListInstance.

    <Data>
      <Rows>
        <Row>
          <Field Name="Title">Hamlet</Field>
          <Field Name="Actor">Tom Higginbotham</Field>
          <Field Name="CastingStatus">Committed to Role</Field>
        </Row>
        <Row>
          <Field Name="Title">Claudius</Field>
          <Field Name="Actor"></Field>
          <Field Name="CastingStatus">Not Started</Field>
        </Row>
        <Row>
          <Field Name="Title">Gertrude</Field>
          <Field Name="Actor">Satomi Hayakawa</Field>
          <Field Name="CastingStatus">Auditioned</Field>
        </Row>
        <Row>
          <Field Name="Title">Ophelia</Field>
          <Field Name="Actor">Cassi Hicks</Field>
          <Field Name="CastingStatus">Committed to Role</Field>
        </Row>
        <Row>
          <Field Name="Title">The ghost</Field>
          <Field Name="Actor">Lertchai Treetawatchaiwong</Field>
          <Field Name="CastingStatus">Role Offered</Field>
        </Row>
      </Rows>
    </Data>
  1. In Solution Explorer, select Feature1 to open the Feature designer. In the designer, set the Title to Theater and Movie Data Components, and set the Description to Site columns, content types, and list instances for data about theater and movies.. Save the file, and close the designer.

  2. Si no se cambiado el nombre de Feature1 en el Explorador de soluciones, abra el menú contextual, seleccione Cambiar nombre y cambie el nombre a TheaterAndMovieDataComponents.

Para programar el proyecto de aplicación web remota

Desarrolle la aplicación web como lo haría con cualquier otra aplicación web de su plataforma preferida. Para una pila de Microsoft, puede usar el servicio web de REST/OData o uno de los modelos de objeto de cliente de SharePoint. Para una pila distinta de Microsoft, puede usar puntos de conexión de REST/OData en SharePoint para realizar operaciones de creación/lectura/actualización/eliminación (CRUD) en datos de la web del complemento.

Nota

When you add a reference to an assembly to your web application project in Visual Studio, set the Copy Local property of the assembly to True, unless you know that the assembly is already installed on the web server, or you can ensure that it is installed before you deploy your add-in. The .NET Framework is installed on Microsoft Azure Web Roles and Azure websites. But the SharePoint client assemblies and the various Microsoft managed code extensions and foundations are not installed. Office Developer Tools for Visual Studio automatically adds references to some assemblies commonly used in SharePoint Add-ins and sets the Copy Local property.

En el ejemplo en curso, desarrollará una aplicación web ASP.NET. Siga estos pasos.

  1. Abra el archivo Default.aspx y sustituya el elemento del cuerpo del archivo por el marcador siguiente. El marcador agrega un botón Obtener reparto que, cuando se elige, lee la lista Personajes de Hamlet que está en la web de complemento y presenta sus datos en un control GridView que solo aparece después de presionar el botón.
  <body >
    <form id="form1" runat="server">
      <div>
        <h2>Local Theater</h2>
      </div>
      <asp:Literal ID="Literal1" runat="server"><br /><br /></asp:Literal>
      <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Get the Cast"/>
      <asp:Literal ID="Literal2" runat="server"><br /><br /></asp:Literal>
      <asp:GridView ID="GridView1" runat="server" Caption="The Cast" ></asp:GridView>
    </form>
  </body>

  1. Abra el archivo Default.aspx.cs y agréguele las instrucciones using siguientes.
  using Microsoft.SharePoint.Client;
  using Microsoft.IdentityModel.S2S.Tokens;
  using System.Net;
  using System.IO;
  using System.Xml;
  using System.Data;
  using System.Xml.Linq;
  using System.Xml.XPath;
  using Microsoft.SharePoint.Samples;

La última de estas instrucciones se refiere al espacio de nombres que se declara en el archivo TokenHelper.cs.


3. Agregue los campos siguientes a la clase **Default**. ```csharp SharePointContextToken contextToken; string accessToken; Uri sharepointUrl; ```
  1. Sustituya el método Page_Load por el código siguiente que usa la clase TokenHelper para obtener tokens del servidor de tokens seguro que cumple OAuth. A continuación, el token de acceso se almacena en la propiedad CommandArgument del botón para que el controlador de eventos de clic de botón lo recupere posteriormente.
    protected void Page_Load(object sender, EventArgs e)
  {
      TokenHelper.TrustAllCertificates();
      string contextTokenString = TokenHelper.GetContextTokenFromRequest(Request);

      if (contextTokenString != null)
      {
          // Get context token
          contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, Request.Url.Authority);

          // Get access token
          sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
          accessToken = TokenHelper.GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
          
          // Pass the access token to the button event handler.
          Button1.CommandArgument = accessToken;
      }
  }

  1. Agregue el controlador de eventos siguiente a la clase Default. El controlador empezará recuperando el token de acceso almacenado en la propiedad CommandArgument del botón.
    protected void Button1_Click(object sender, EventArgs e)
  {
      // Retrieve the access token that the Page_Load method stored
      // in the button's command argument.
      string accessToken = ((Button)sender).CommandArgument;
  }

  1. El controlador tiene que volver a adquirir la dirección URL de la web de complemento modificada en postbacks, así que agregue el código siguiente.
      if (IsPostBack)
    {
        sharepointUrl = new Uri(Request.QueryString["SPAppWebUrl"]);
    }

  1. Add the following line that uses one of the SharePoint REST/OData endpoints to obtain list data. In this example, the code reads the Characters in Hamlet list that is deployed to the add-in web. The APIs for this service make it easy, in a single line of code, to select a list and specify three fields from the list to return.

Note that in the OData URL, you must use the internal names of the fields (columns) rather than the display names, so the code uses Title, Actor, and CastingStatus rather than Character, Actor/Actress, and Casting Status. For more information about the REST/OData web service, see Use OData query operations in SharePoint REST requests.

    // REST/OData URL section
    string oDataUrl = "/_api/Web/lists/getbytitle('Characters In Hamlet')/items?$select=Title,Actor,CastingStatus";

  1. Agregue el código siguiente que usa las clases HttpWebRequest y HttpWebResponse del espacio de nombres System.Net para crear la solicitud HTTP y los objetos de respuesta.
  // HTTP Request and Response construction section
  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(sharepointUrl.ToString() + oDataUrl);
  request.Method = "GET";
  request.Accept = "application/atom+xml";
  request.ContentType = "application/atom+xml;type=entry";
  request.Headers.Add("Authorization", "Bearer " + accessToken);
  HttpWebResponse response = (HttpWebResponse)request.GetResponse();

  1. Add the following code to parse the ATOM-formatted response XML. It uses the classes of the System.Xml.Linq namespace to parse the data that is returned and construct a List<T> of the items from the SharePoint list. (You could also use the classes of the System.Xml namespace.)

Note that, in the XML that SharePoint returns, the child elements of the entry element hold metadata about the list item. The actual row data of a SharePoint list item is nested two layers down in the properties element. For that reason the Elements<T> extension method is used twice to filter out the higher levels.

  // Response markup parsing section
  XDocument oDataXML = XDocument.Load(response.GetResponseStream(), LoadOptions.None);
  XNamespace atom = "http://www.w3.org/2005/Atom";
  XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";
  XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"; 

  List<XElement> entries = oDataXML.Descendants(atom + "entry")
                          .Elements(atom + "content")
                          .Elements(m + "properties")
                          .ToList();

  1. Add the following LINQ query to construct an IEnumerable<T> collection of an anonymous type that has just the properties you need and no others. Note that although the code must refer to the item title field by its internal name Title, the property name in the anonymous type, to which the value is assigned, can be named Character. One effect of this is that when the collection is bound to a grid control, the more appropriate name Character appears on the page.
  var entryFieldValues = from entry in entries
  select new { Character=entry.Element(d + "Title").Value, 
               Actor=entry.Element(d + "Actor").Value, 
               CastingStatus=entry.Element(d + "CastingStatus").Value };

  1. Finish the handler with the following code to bind the data to a GridView control on the page. The column headers in the grid default to the property names of the anonymous type: Character, Actor, and CastingStatus. The GridView control has properties that enable you to control the name and formatting column headers, so you could have Actor/Actress and Casting Status to match the column headers in SharePoint. For simplicity, these techniques are not described here. (You could also use a DataGrid control.)
    GridView1.DataSource = entryFieldValues;
    GridView1.DataBind();

  1. Guarde todos los archivos.

Para probar y depurar el complemento de SharePoint

  1. To test the SharePoint Add-in and its remote web application, select the F5 key in Visual Studio. The web application is deployed to IIS Express at localhost. The SharePoint Add-in is installed to the target SharePoint website. (In the continuing example, the remote add-in does not try to interact with the host web, and the add-in principal automatically has permissions to the add-in web, so you are not prompted to grant permissions.) The Site Contents page of your target SharePoint website opens, and you see the new add-in listed there.

  2. Select the SharePoint Add-in, and the remote web application opens to the page you specified in the StartPage element in the AppManifest.xml file. Use the web application as needed to verify that it is working. In the continuing example of this topic, just select the button. Doing so creates a grid and populates it with the Characters in Hamlet list of the add-in web.

Publicar el complemento de SharePoint

To publish your SharePoint Add-in, upload the add-in package to a corporate add-in catalog or to the Office add-in store. For more information, see Publishing to the Office Store or an organization's add-in catalog and Publish SharePoint Add-ins.

Solución de problemas

Si el complemento no funciona, es posible que se haya producido un error en el marcado CAML que bloquee la implementación de los componentes de SharePoint. Siga un procedimiento similar al que indicamos a continuación, que está basado en el ejemplo que estamos usando, para comprobar la implementación.

Para probar el aprovisionamiento de la web de complemento

  1. Open the Site Settings page of the host web. In the Site Collection Administration section, select the Site hierarchy link.

  2. En la página Jerarquía de sitios, verá que el complemento se indica mediante la dirección URL. No lo inicie; copie la dirección URL y úsela en los pasos siguientes.

  3. Navegue hasta URL_de_web_de_aplicación/_layouts/15/ManageFeatures.aspx y, en la página Características del sitio que se abra, compruebe que Componentes de datos de teatros y películas esté presente en la lista alfabética de características del complemento de SharePoint y que su estado sea Activo.

  4. Navegue hasta URL_de_web_de_aplicación/_layouts/15/mngfield.aspx y, en la página Columnas de sitio que se abra, compruebe que el grupo Teatro y cine esté presente en la lista de columnas de sitio y que contenga las nuevas columnas de sitio personalizadas (Actor/Actriz y Estado del casting).

  5. Navegue hasta URL_de_web_de_aplicación/_layouts/15/mngctype.aspx y, en la página Tipos de contenido de sitio que se abra, compruebe que el grupo Teatro y cine esté presente en la lista de tipos de contenido y que contenga el nuevo tipo de contenido ActingRole.

  6. Select the link to the ActingRole content type. On the Site Content Type page that opens, verify that the content type has the two new site column types, Actor/Actress and Casting Status, and that the item title field has been given your custom display name: Character.

  7. Navegue hasta URL_de_web_de_aplicación/_layouts/15/mcontent.aspx y, en la página Bibliotecas y listas del sitio que se abra, compruebe que esté presente el vínculo Personalizar "Personajes de Hamlet".

  8. Select the Customize "Characters in Hamlet" link, and verify on the list settings page that the only content type for the list is your custom ActingRole content type, and that your two new site columns, Actor/Actress and Casting Status are listed in the Columns section. (The Title column may appear with its internal name Title instead of the display name Character that you gave it.)

Nota

If there is no Content Types section on the page, you must enable management of content types. Click the Advanced Settings link, and on the Advanced Settings page, enable management of content types, and then select OK. You are returned to the previous page, where there is now a list of Content Types section.

  1. Near the top of the page is the Web Address of the list. Copy this and paste it into the address bar of your browser, and then navigate to the list. Verify that the list has the sample items that you created. (The Title column may appear with its internal name Title instead of the display name Character that you gave it.)

Vea también