Utilisation d'informations de profil avec ASP.NET AJAX

Mise à jour : novembre 2007

Le service Web de profil ASP.NET vous permet d'utiliser le service de profil de l'application ASP.NET dans les applications . Cette rubrique montre comment appeler le service de profil de l'application depuis le navigateur en utilisant du code ECMAScript (JavaScript).

L'utilisation des informations de profil requiert que vous activiez tout d'abord le service de profil sur le site Web. Cela le rend disponible en tant que service Web. Lorsque le service Web de profil est activé, vous pouvez l'appeler par les méthodes de la classe du script client Sys.Services.ProfileService.

Activation du service de profil

Pour utiliser le service de profil depuis script, vous devez activer le service de profil à l'aide de l'élément suivant, dans le fichier Web.config de l'application.

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

Par défaut, aucune propriété de profil n'est disponible. Pour chaque propriété de profil que vous souhaitez rendre disponible dans une application cliente, ajoutez le nom de la propriété à l'attribut readAccessProperties de l'élément profileService. De la même façon, pour chaque propriété de profil de serveur qui peut être définie en fonction des données envoyées depuis application cliente, ajoutez le nom de la propriété à l'attribut writeAccessProperties. L'exemple suivant indique la façon d'exposer des propriétés individuelles et de définir la possibilité pour une application cliente de les lire et écrire.

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

Vous définissez les propriétés de profil dans la section profile en utilisant la syntaxe de l'exemple suivant. Pour les propriétés groupées, utilisez l'élément 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>

Pour plus d'informations, consultez Comment : configurer les services ASP.NET dans ASP.NET AJAX.

Exemple

L'exemple suivant indique comment utiliser le service de profil depuis un script client. L'exemple se compose d'une page Web ASP.NET qui contient un contrôle ScriptManager. Lorsque ce contrôle est inclus dans la page, l'objet Sys.Services.AuthenticationService est automatiquement disponible à tout script client dans la page.

La page contient un bouton d'ouverture de session associé à un gestionnaire d'événements nommé OnClickLogin. Le code de la méthode appelle la méthode login de l'objet AuthenticationService.

Après vous être connecté, la fonction de rappel loginComplete est appelée, elle appelle la méthode load de l'objet Sys.Services.ProfileService pour charger le profil pour l'utilisateur courant.

Les informations de profil se composent des couleurs d'arrière-plan et de premier plan que vous pouvez définir après vous être connecté. Les couleurs d'arrière-plan et de premier plan sont des propriétés de profil que vous devez définir dans le fichier Web.config. Pour définir ces propriétés, ajoutez les éléments suivants dans le fichier Web.config de l'application :

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

L'exemple de code fournit des fonctions de rappel réussi asynchrones pour les méthodes de load et save. Vous pouvez également ajouter des fonctions de rappel non réussi pour les méthodes load et save.

Remarque :

Avant d'exécuter l'exemple, assurez-vous qu'au moins un utilisateur est défini dans la base de données d'appartenance de l'application. Pour plus d'informations sur la création d'un utilisateur dans la base de données par défaut SQL Server Express Edition, consultez Utilisation de l'authentification par formulaire avec ASP.NET AJAX.

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>

Voir aussi

Tâches

Comment : configurer les services ASP.NET dans ASP.NET AJAX

Concepts

Utilisation de services Web dans ASP.NET AJAX

Appel de services Web à partir du script client

Utilisation de l'authentification par formulaire avec ASP.NET AJAX

Sys.Services.AuthenticationService, classe

Sys.Services.ProfileService, classe