Procedimiento para trabajar con sitios web

Última modificación: viernes, 29 de abril de 2011

Hace referencia a: SharePoint Foundation 2010

En este artículo
Recuperación de las propiedades de un sitio web
Recuperación sólo de las propiedades especificadas de un sitio web
Actualización del título y la descripción de un sitio web
Creación de un sitio web

Disponible en SharePoint Online

Para trabajar con sitios web, comience usando el constructor ClientContext() (JavaScript: ClientContext(serverRelativeUrl)) y pase una dirección URL o un URI para devolver un contexto de solicitud específico.

Recuperación de las propiedades de un sitio web

Use la propiedad Web (JavaScript: web) de la clase ClientContext (JavaScript: ClientContext) para especificar las propiedades del objeto de sitio web que se encuentra en la dirección URL del contexto especificado. Después de cargar el objeto de sitio web mediante el método Load<T>(T, []) (JavaScript: load(clientObject)) y, posteriormente, llamar a ExecuteQuery() o ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) (JavaScript: executeQueryAsync(succeededCallback, failedCallback)), obtendrá acceso a todas las propiedades de ese sitio web. En el siguiente ejemplo se muestra el título y la descripción del sitio web raíz de una colección de sitios especificada, aunque todas las otras propiedades devueltas de forma predeterminada se ponen a disposición después de cargar el objeto de sitio web y ejecutar la consulta. Para obtener una lista de las propiedades que no están disponibles de forma predeterminada al recuperar objetos de cliente específicos, vea Introducción a la recuperación de datos.

using System;
using Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveWebsite
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);

            Web oWebsite = clientContext.Web;

            clientContext.Load(oWebsite);

            clientContext.ExecuteQuery();

            Console.WriteLine("Title: {0} Description: {1}", oWebsite.Title, oWebsite.Description);
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveWebsite

        Shared Sub Main()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"

            Dim clientContext As New ClientContext(siteUrl)
            Dim oWebsite As Web = clientContext.Web

            clientContext.Load(oWebsite)

            clientContext.ExecuteQuery()

            Console.WriteLine("Title: {0} Description: {1}", oWebsite.Title, oWebsite.Description)
        End Sub
    End Class
End Namespace
var siteUrl = '/sites/MySiteCollection ';
    
function retrieveWebSite() {
    var clientContext = new SP.ClientContext(siteUrl);
    this.oWebsite = clientContext.get_web();

    clientContext.load(this.oWebsite);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
    alert('Title: ' + this.oWebsite.get_title() + ' Decription: ' + this.oWebsite.get_description());
}
    
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Recuperación sólo de las propiedades especificadas de un sitio web

Para reducir la transferencia de datos innecesaria entre cliente y servidor, puede resultar útil devolver sólo propiedades especificadas del objeto de sitio web, en lugar de todas sus propiedades. En este caso, use la sintaxis de la expresión lambda o consulta LINQ con el método Load<T>(T, []) (JavaScript: load(clientObject)) para especificar las propiedades que se van a devolver desde el servidor. En el siguiente ejemplo, solo se ponen a disposición el título y la fecha de creación del objeto de sitio web después de llamar a ExecuteQuery() (JavaScript: executeQueryAsync(succeededCallback, failedCallback)). Por ejemplo, si intenta escribir oWebsite.Description en la consola, recibirá PropertyOrFieldNotInitializedException.

using System;
using Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class RetrieveWebsiteProperties
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            Web oWebsite = clientContext.Web;

            clientContext.Load(
                oWebsite,
                website => website.Title,
                website => website.Created);

            clientContext.ExecuteQuery();

            Console.WriteLine("Title: {0} Created: {1}", oWebsite.Title, oWebsite.Created);
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class RetrieveWebsiteProperties

        Shared Sub Main()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"

            Dim clientContext As New ClientContext(siteUrl)
            Dim oWebsite As Web = clientContext.Web

            clientContext.Load(oWebsite, _ 
                           Function(website) website.Title, _ 
                           Function(website) website.Created)

            clientContext.ExecuteQuery()

            Console.WriteLine("Title: {0} Created: {1}", oWebsite.Title, oWebsite.Created)
        End Sub
    End Class
End Namespace
var siteUrl = '/sites/MySiteCollection ';
    
function retrieveWebSiteProperties() {
    var clientContext = new SP.ClientContext(siteUrl);
    this.oWebsite = clientContext.get_web();

    clientContext.load(this.oWebsite, 'Title', 'Created');

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
    alert('Title: ' + this.oWebsite.get_title() + ' Created: ' + this.oWebsite.get_created());
}
    
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Tenga en cuenta que en JavaScript, el constructor ClientContext(serverRelativeUrl) toma una dirección URL relativa al servidor y el método load(clientObject) acepta cadenas en lugar de objetos LINQ reales.

Actualización del título y la descripción de un sitio web

Para modificar un sitio web, se deben establecer las propiedades y llamar al método Update() (JavaScript: update()), de manera similar al modo en que funciona el modelo de objetos servidor. Sin embargo, en el modelo de objetos cliente, debe llamar a ExecuteQuery() o ExecuteQueryAsync(ClientRequestSucceededEventHandler, ClientRequestFailedEventHandler) (JavaScript: executeQuery(succeededCallback, failedCallback)) para solicitar el procesamiento por lotes para todos lo comandos que se especifiquen. En el siguiente ejemplo se cambia el título y la descripción de un sitio web especificado.

using System;
using Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class UpdateWebSite
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";

            ClientContext clientContext = new ClientContext(siteUrl);
            Web oWebsite = context.Web;

            oWebsite.Title = "Updated Web Site";
            oWebsite.Description = "This is an updated Web site.";

            oWebsite.Update();

            clientContext.ExecuteQuery();
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class UpdateWebSite

        Shared Sub Main()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"

            Dim clientContext As New ClientContext(siteUrl)
            Dim oWebsite As Web = clientContext.Web

            oWebsite.Title = "Updated Web Site"
            oWebsite.Description = "This is an updated Web site."

            oWebsite.Update()

            clientContext.ExecuteQuery()
        End Sub
     End Class
End Namespace
var siteUrl = '/sites/MySiteCollection ';
    
function updateWebSite() {
    var clientContext = new SP.ClientContext(siteUrl);
    this.oWebsite = clientContext.get_web();

    this.oWebsite.set_title('Updated Web Site');
    this.oWebsite.set_description('This is an updated Web site.');
    this.oWebsite.update();

    clientContext.load(this.oWebsite, 'Title', 'Description');

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
    alert('Title: ' + this.oWebsite.get_title() + ' Decription: ' + this.oWebsite.get_description());
}
    
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Creación de un sitio web

Para crear un objeto de sitio web, use la clase WebCreationInformation (JavaScript: WebCreationInformation) para definir sus propiedades y, a continuación, pase este objeto al método Add(WebCreationInformation) (JavaScript: add(parameters)) de la clase WebCollection (JavaScript: WebCollection).

En el siguiente ejemplo se crea un sitio web de blog nuevo dentro de una colección de sitios.

using System;
using Microsoft.SharePoint.Client;

namespace Microsoft.SDK.SharePointServices.Samples
{
    class CreateWebSite
    {
        static void Main()
        {
            string siteUrl = "http://MyServer/sites/MySiteCollection";
            string blogDescription = "A new blog Web site.";
            int blogLanguage = 1033;
            string blogTitle = "Blog Web Site";
            string blogUrl = "blogwebsite";
            bool blogPermissions = false;
            string webTemplate = "BLOG#0";

            ClientContext clientContext = new ClientContext(siteUrl);
            Web oWebsite = clientContext.Web;

            WebCreationInformation webCreateInfo = new WebCreationInformation();
            webCreateInfo.Description = blogDescription;
            webCreateInfo.Language = blogLanguage;
            webCreateInfo.Title = blogTitle;
            webCreateInfo.Url = blogUrl;
            webCreateInfo.UseSamePermissionsAsParentSite = blogPermissions;
            webCreateInfo.WebTemplate = webTemplate;

            Web oNewWebsite = oWebsite.Webs.Add(webCreateInfo);

            clientContext.Load(
                oNewWebsite,
                website => website.ServerRelativeUrl,
                website => website.Created);

            clientContext.ExecuteQuery();

            Console.WriteLine("Server-relative Url: {0} Created: {1}", oNewWebsite.ServerRelativeUrl, oNewWebsite.Created);
        }
    }
}
Imports System
Imports Microsoft.SharePoint.Client

Namespace Microsoft.SDK.SharePointServices.Samples
    Class CreateWebSite

        Shared Sub Main()

            Dim siteUrl As String = "http://MyServer/sites/MySiteCollection"
            Dim blogDescription As String = "A new Blog Web site."
            Dim blogLanguage As Integer = 1033
            Dim blogTitle As String = "Blog Web Site"
            Dim blogUrl As String = "blogwebsite"
            Dim blogPermissions As Boolean = False
            Dim webTemplate As String = "BLOG#0"

            Dim clientContext As New ClientContext(siteUrl)
            Dim oWebsite As Web = clientContext.Web

            Dim webCreateInfo As New WebCreationInformation()
            webCreateInfo.Description = blogDescription
            webCreateInfo.Language = blogLanguage
            webCreateInfo.Title = blogTitle
            webCreateInfo.Url = blogUrl
            webCreateInfo.UseSamePermissionsAsParentSite = blogPermissions
            webCreateInfo.WebTemplate = webTemplate

            Dim oNewWebsite As Web = oWebsite.Webs.Add(webCreateInfo)

            clientContext.Load(oWebsite, _ 
                               Function(website) website.ServerRelativeUrl, _ 
                               Function(website) website.Created)

            clientContext.ExecuteQuery()

            Console.WriteLine("Server-relative Url: {0} Created: {1}", oWebsite.ServerRelativeUrl, oWebsite.Created)
        End Sub
    End Class
End Namespace
var siteUrl = '/sites/MySiteCollection ';
    
function createWebSite() {
    var blogDescription = 'A new Blog Web site.';
    var blogLanguage = 1033;
    var blogTitle = 'Blog Web Site';
    var blogUrl = 'blogwebsite';
    var blogPermissions = false;
    var webTemplate = 'BLOG#0';

    var clientContext = new SP.ClientContext(siteUrl);
    this.oWebsite = clientContext.get_web();

    var webCreateInfo = new SP.WebCreationInformation();
    webCreateInfo.set_description(blogDescription);
    webCreateInfo.set_language(blogLanguage);
    webCreateInfo.set_title(blogTitle);
    webCreateInfo.set_url(blogUrl);
    webCreateInfo.set_useSamePermissionsAsParentSite(blogPermissions);
    webCreateInfo.set_webTemplate(webTemplate);

    this.oNewWebsite = this.oWebsite.get_webs().add(webCreateInfo);

    clientContext.load(this.oNewWebsite, 'ServerRelativeUrl', 'Created');

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
    alert('Title: ' + this.oWebsite.get_title() + ' Decription: ' + this.oWebsite.get_description());
}
    
function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

En el ejemplo anterior se usa una expresión de consulta LINQ para devolver las propiedades ServerRelativeUrl (JavaScript: serverRelativeUrl) y Created (JavaScript: created), cuyos valores no se muestran a menos que los pida explícitamente.

Nota

Al usar LINQ para crear consultas en el modelo de objetos cliente, se usa LINQ to Objects en lugar del proveedor LINQ to SharePoint, que sólo puede usarse al escribir código en el modelo de objetos servidor.

Para obtener información y un ejemplo acerca de cómo trabajar con sitios web dentro del contexto del modelo de objetos de SharePoint Foundation Silverlight, vea Uso del modelo de objetos Silverlight.

Vea también

Conceptos

Introducción a la recuperación de datos

Creación de objetos cliente

Instrucciones del modelo de objetos cliente

Tareas comunes de programación

Otros recursos

Biblioteca de clases de cliente

Biblioteca de clases de ECMAScript