Compartir a través de


Usar información de perfiles con AJAX en ASP.NET

Actualización: noviembre 2007

El servicio web de perfil de ASP.NET le permite utilizar el servicio de aplicación de perfiles de ASP.NET en aplicaciones de . En este tema se muestra cómo llamar al servicio de perfil de aplicación desde el explorador mediante el código ECMAScript (JavaScript).

Para utilizar la información del perfil se debe habilitar primero el servicio del perfil en el sitio web. Esto lo deja disponible como un servicio web. Cuando el servicio web del perfil está habilitado, puede invocarlo llamando a los métodos de la clase de script de cliente Sys.Services.ProfileService.

Habilitar el servicio de perfil

Para usar el servicio de perfil desde el script, debe habilitar el servicio de perfil mediante el elemento siguiente en el archivo Web.config de la aplicación.

<system.web.extensions>
  <scripting>
    <webServices
      < profileService enabled="true" />
    </webServices
  </scripting>
</system.web.extensions>

De forma predeterminada, no está disponible ninguna propiedad de perfil. Para cada propiedad de perfil que desea dejar disponible en una aplicación cliente, agregue el nombre de la propiedad al atributo readAccessProperties del elemento profileService. De igual forma, para cada propiedad de perfil de servidor que se puede establecer según los datos enviados desde una aplicación cliente, agregue el nombre de propiedad al atributo writeAccessProperties. El ejemplo siguiente muestra cómo exponer propiedades individuales y establecer si una aplicación cliente puede leerlas y escribirlas.

<profileService enabled="true" 
  readAccessProperties="Backgroundcolor,Foregroundcolor" 
  writeAccessProperties=" Backgroundcolor,Foregroundcolor"/>

Defina las propiedades de perfil en la sección profile con una sintaxis similar a la del ejemplo siguiente. Para las propiedades agrupadas, utilice el elemento group.

<system.web>
  <profile enabled="true">
    <add name=" Backgroundcolor" type="System.String"
       defaultValue="white" />
    <add name=" Foregroundcolor" type="System.String"
     defaultValue="black" />
    <properties>
      <group name="Address">
       <add name="Street" type="System.String" />
       <add name="City" type="System.String"/>
       <add name="PostalCode" type="System.String" />
      </group>
    </properties>
  </profile>
</system.web>

Para obtener más información, vea Cómo: Configurar servicios de ASP.NET en ASP.NET AJAX.

Ejemplo

El ejemplo siguiente muestra cómo utilizar el servicio de perfil de script de cliente. El ejemplo se compone de una página web ASP.NET que contiene un control ScriptManager. Cuando este control está incluido en la página, el objeto Sys.Services.AuthenticationService queda disponible automáticamente para cualquier script de cliente de la página.

La página contiene un botón de inicio de sesión con un controlador de eventos asociado denominado OnClickLogin. El código del método llama al método login del objeto AuthenticationService.

Una vez iniciada la sesión, se llama a la función de devolución de llamada loginComplete que llama el método load del objeto Sys.Services.ProfileService para cargar el perfil del usuario actual.

La información del perfil se compone del color de primer y segundo plano, que puede establecer una vez iniciada la sesión. El color de primer y segundo plano son propiedades de perfil que debe establecer en el archivo Web.config. Para definir estas propiedades, agregue los siguientes elementos al archivo Web.config de la aplicación:

<profile enabled="true">
  <properties>
    <add name="Backgroundcolor" type="System.String"
       defaultValue="white"/>
    <add name="Foregroundcolor" type="System.String"
       defaultValue="black"/>
  </properties>
</profile>

El código de ejemplo proporciona funciones de devolución de llamada completadas asincrónicas para los métodos de carga y almacenamiento. También puede agregar funciones de devolución de llamada fallidas para los métodos de carga y almacenamiento.

Nota:

Antes de ejecutar el ejemplo, compruebe que hay por lo menos un usuario definido en la base de datos de pertenencia de la aplicación. Para obtener información sobre cómo crear un usuario en la base de datos de SQL Server Express Edition predeterminada, vea Utilizar la autenticación de formularios con AJAX en ASP.NET.

var setProfileProps;

function pageLoad()
{
    var userLoggedIn = 
        Sys.Services.AuthenticationService.get_isLoggedIn();
        // alert(userLoggedIn);
        
    profProperties = $get("setProfileProps");
    passwordEntry = $get("PwdId");
    
    if (userLoggedIn == true)
    {
        LoadProfile();
        GetElementById("setProfProps").style.visibility = "visible";
        GetElementById("logoutId").style.visibility = "visible";
    }
    else
    {
        DisplayInformation("User is not authenticated.");
    }
     
}


// The OnClickLogout function is called when 
// the user clicks the Logout button. 
// It logs out the current authenticated user.
function OnClickLogout()
{
    Sys.Services.AuthenticationService.logout(
        null, OnLogoutComplete, AuthenticationFailedCallback,null);
}


function OnLogoutComplete(result, 
    userContext, methodName)
{
    // Code that performs logout 
    // housekeeping goes here.          
}       



// This is the callback function called 
// if the authentication failed.
function AuthenticationFailedCallback(error_object, 
    userContext, methodName)
{   
    DisplayInformation("Authentication failed with this error: " +
        error_object.get_message());
}



// Loads the profile of the current
// authenticated user.
function LoadProfile()
{
    Sys.Services.ProfileService.load(null, 
        LoadCompletedCallback, ProfileFailedCallback, null);

}

// Saves the new profile
// information entered by the user.
function SaveProfile()
{
    
    // Set background color.
    Sys.Services.ProfileService.properties.Backgroundcolor = 
        GetElementById("bgcolor").value;
    
    // Set foreground color.
    Sys.Services.ProfileService.properties.Foregroundcolor =
        GetElementById("fgcolor").value; 
    
    // Save profile information.
    Sys.Services.ProfileService.save(null, 
        SaveCompletedCallback, ProfileFailedCallback, null);
    
}

// Reads the profile information and displays it.
function LoadCompletedCallback(numProperties, userContext, methodName)
{
    document.bgColor = 
        Sys.Services.ProfileService.properties.Backgroundcolor;

    document.fgColor =   
        Sys.Services.ProfileService.properties.Foregroundcolor;         
}

// This is the callback function called 
// if the profile was saved successfully.
function SaveCompletedCallback(numProperties, userContext, methodName)
{
    LoadProfile();
    // Hide the area that contains 
    // the controls to set the profile properties.
    SetProfileControlsVisibility("hidden");
}

// This is the callback function called 
// if the profile load or save operations failed.
function ProfileFailedCallback(error_object, userContext, methodName)
{
    alert("Profile service failed with message: " + 
            error_object.get_message());
}


// Utility functions.

// This function sets the visibilty for the
// area containing the page elements for settings
// profiles.
function SetProfileControlsVisibility(currentVisibility)
{
   profProperties.style.visibility = currentVisibility; 
}

// Utility function to display user's information.
function DisplayInformation(text)
{
    document.getElementById('placeHolder').innerHTML += 
    "<br/>"+ text;
}


function GetElementById(elementId)
{
    var element = document.getElementById(elementId);
    return element;
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

<%@ Page Language="VB" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" >

    <title>Using Profile Service</title>
   <style type="text/css">
        body {  font: 11pt Trebuchet MS;
                padding-top: 72px;
                text-align: center }

        .text { font: 8pt Trebuchet MS }
    </style>

</head>
<body>

    <form id="form1" >
    
        <asp:ScriptManager  ID="ScriptManagerId">
            <Scripts>
                <asp:ScriptReference Path="Profile.js" />
            </Scripts>
        </asp:ScriptManager>


        <h2>Profile Service</h2>
    
        <p>
            You must log in first to set or get profile data. 
            Create a new user, if needed. <br /> Refer to the Authentication example.
        </p>
         
        <div id="loginId" style="visibility:visible">
            <table id="loginForm">
                <tr>
                    <td>User Name: </td>
                    <td><input type="text" 
                        id="userId" name="userId" value=""/></td>
                </tr>
                
                <tr>
                    <td>Password: </td>
                    <td><input type="password" 
                        id="userPwd" name="userPwd" value="" /></td>
                </tr>
                
                <tr>
                    <td><input type="button" 
                        id="login" name="login" value="Login" 
                            onclick="OnClickLogin()" /></td>
                </tr>
            </table>              
    
        </div>
        
        <div id="setProfProps" style="visibility:hidden">
            <input type="button" 
            value="Set Profile Properties" 
            onclick="SetProfileControlsVisibility('visible')"/> 
        </div>
        
        <div id="placeHolder" style="visibility:visible" />
        
        <br />
        
        
        <input id="logoutId" type="button" 
            value="Logout"  style="visibility:hidden"
        onclick="OnClickLogout()" />
        
    
        <div id="setProfileProps" style="visibility:hidden">
            <table>
                <tr>
                    <td>Foreground Color</td>
                    <td><input type="text" id="fgcolor" 
                    name="fgcolor" value=""/></td>
                </tr>
                
                <tr>
                    <td>Background Color</td>
                    <td><input type="text" id="bgcolor" 
                        name="bgcolor" value="" /></td>
                </tr>
                
                <tr>
                    <td><input type="button" 
                    id="saveProf" name="saveProf" 
                    value="Save Profile Properties" 
                    onclick="SaveProfile();" /></td>
                </tr>
            </table>      
        </div>        
    
    </form>

</body>

</html>
<%@ Page Language="C#" %>

<html xmlns="http://www.w3.org/1999/xhtml" >
<head >

    <title>Using Profile Service</title>
   <style type="text/css">
        body {  font: 11pt Trebuchet MS;
                padding-top: 72px;
                text-align: center }

        .text { font: 8pt Trebuchet MS }
    </style>

</head>
<body>

    <form id="form1" >
    
        <asp:ScriptManager  ID="ScriptManagerId">
            <Scripts>
                <asp:ScriptReference Path="Profile.js" />
            </Scripts>
        </asp:ScriptManager>


        <h2>Profile Service</h2>
    
        <p>
            You must log in first to set or get profile data. 
            Create a new user, if needed. <br /> 
        </p>
         
        <div id="setProfProps" style="visibility:visible">
            <input type="button" 
            value="Set Profile Properties" 
            onclick="SetProfileControlsVisibility('visible')"/> 
        </div>
        
        <div id="placeHolder" style="visibility:visible" />
        
        <br />
        
        
        <input id="logoutId" type="button" 
            value="Logout"  style="visibility:hidden"
        onclick="OnClickLogout()" />
        
    
        <div id="setProfileProps" style="visibility:hidden">
            <table>
                <tr>
                    <td>Foreground Color</td>
                    <td><input type="text" id="fgcolor" 
                    name="fgcolor" value=""/></td>
                </tr>
                
                <tr>
                    <td>Background Color</td>
                    <td><input type="text" id="bgcolor" 
                        name="bgcolor" value="" /></td>
                </tr>
                
                <tr>
                    <td><input type="button" 
                    id="saveProf" name="saveProf" 
                    value="Save Profile Properties" 
                    onclick="SaveProfile();" /></td>
                </tr>
            </table>      
        </div>        
    
    </form>

</body>

</html>

Vea también

Tareas

Cómo: Configurar servicios de ASP.NET en ASP.NET AJAX

Conceptos

Usar servicios web en ASP.NET para AJAX

Llamar a servicios web desde script de cliente

Utilizar la autenticación de formularios con AJAX en ASP.NET

Sys.Services.AuthenticationService (Clase)

Sys.Services.ProfileService (Clase)