Export (0) Print
Expand All

Greeting the user

This topic describes and demonstrates how to use the Live Connect APIs to greet a user by name and how to display the user's profile picture.

Greeting a user by name when he or she visits your app is a simple but effective way of building a stronger connection between the user and your app. This connection can help you influence users to return to your app.

This topic describes how to display the user's name and display their profile picture in these languages. The code examples assume that your app initialized the APIs, that the user signed in, and that he or she consented to the wl.basic scope (which enables your app to get the user's name). For more info about these initial steps, see Signing users in and Obtaining user consent.

To make full use of the code examples in this topic, you can use them in the context of larger code reference samples that we provide in Working with the code examples.

Getting the user's name and profile picture in JavaScript and HTML for Windows Store apps

Here's how to display the user's name.


function greetUser_onClick() {
    WL.login({
        scope: "wl.basic"
    }).then(
        function (response)
        {
            WL.api({
                path: "me",
                method: "GET"
            }).then(
                function (response){
                    document.getElementById("infoArea").innerText =
                        "Hello, " + response.first_name + " " +
                        response.last_name + "!";
                },
                function (responseFailed){
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed){
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
    );
}


The code calls the WL.api function. If the call is successful, and a textarea control exists with the name infoArea, the code changes the control's text to display a message with the signed-in user's first and last name. The code gets this info from response.first_name and response.last_name.

Here's how to display the user's profile picture.


function getImage_onClick() {
    WL.login({
        scope: "wl.basic"
    }).then(
        function (response)
        {
            WL.api({
                path: "me/picture",
                method: "GET"
            }).then(
                function (response) {
                    if (response.location) {
                        imgTagString = "<img src='" + response.location + "' />";
                        document.getElementById("userImage").innerHTML = imgTagString;
                    }
                },
                function (responseFailed) {
                    document.getElementById("infoArea").innerText =
                        "Error calling API: " + responseFailed.error.message;
                }
            );
        },
        function (responseFailed) {
            document.getElementById("infoArea").innerText =
                "Error signing in: " + responseFailed.error_description;
        }
     );         
}


The code uses the WL.login function to sign the user in with the wl.basic scope. If the sign-in is successful, and an img control with the name userImage exists, the code sets the src attribute of the userImage control to a GET call to the signed-in user's profile picture.

Top

Getting the user's name and profile picture in C# for Windows Store apps and Windows Phone apps

Here's how to display the user's name.


private async void btnGreetUser_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveAuthClient auth = new LiveAuthClient();
        LiveLoginResult initializeResult = await auth.InitializeAsync();
        try
        {
            LiveLoginResult loginResult = await auth.LoginAsync(new string[] { "wl.basic" });
            if (loginResult.Status == LiveConnectSessionStatus.Connected)
            {
                LiveConnectClient connect = new LiveConnectClient(auth.Session);
                LiveOperationResult operationResult = await connect.GetAsync("me");
                dynamic result = operationResult.Result;
                if (result != null)
                {
                    this.infoTextBlock.Text = string.Join(" ", "Hello", result.name, "!");
                }
                else
                {
                    this.infoTextBlock.Text = "Error getting name.";
                }
            }
        }
        catch (LiveAuthException exception)
        {
            this.infoTextBlock.Text = "Error signing in: " + exception.Message;
        }
        catch (LiveConnectException exception)
        {
            this.infoTextBlock.Text = "Error calling API: " + exception.Message;
        }
    }
    catch (LiveAuthException exception)
    {
        this.infoTextBlock.Text = "Error initializing: " + exception.Message;
    }
}


In the custom btnGreetUser_Click event handler method, the code calls the GetAsync method from the instance of LiveConnectClient. If the call is successful, the code displays a message that contains the signed-in user's name. The code gets the signed-in user's name from the Result property of the LiveOperationResult instance. The Result property contains a representation of the JavaScript Object Notation (JSON)-formatted info.

Here's how to display the user's profile picture.


private async void btnDisplayProfile_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LiveConnectClient liveClient = new LiveConnectClient(this.session);
        LiveOperationResult operationResult = await liveClient.GetAsync("me/picture");
        dynamic result = operationResult.Result;
        BitmapImage image = new BitmapImage(new Uri(result.location, UriKind.Absolute));
        this.imgResult.Source = image;
    }
    catch (LiveConnectException exception)
    {
        this.infoTextBlock.Text = "Error getting user picture: " + exception.Message;
    }
}


The code does this:

  1. The GetAsync method of the LiveConnectClient instance calls me/picture to get info about the user's profile picture.
  2. If the call succeeds, the Result property of the LiveOperationResult instance contains info about the user's profile picture as a JSON-formatted object.
  3. In this JSON-formatted object, the location structure contains a link to the user's profile picture.

Top

Getting the user's name and profile picture in Objective-C for iOS

Here's how to display the user's name and profile picture.


- (void) getMe
{
    if (self.liveClient) {
        [self.liveClient getWithPath:@"me" 
                            delegate:self 
                           userState:@"me"];
        [self.liveClient getWithPath:@"me/picture" 
                            delegate:self 
                           userState:@"me-picture"];
    }
}

- (void) liveOperationSucceeded:(LiveOperation *)operation
{
    if ([operation.userState isEqual:@"me"]) {
        self.nameLabel.text = [operation.result objectForKey:@"name"];
        self.genderLabel.text = [operation.result objectForKey:@"gender"];
        self.profileLinkLabel.text = [operation.result objectForKey:@"link"];
    }
    if ([operation.userState isEqual:@"me-picture"]) {
        NSString *location = [operation.result objectForKey:@"location"];
        if (location) {
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:location]];
            self.profilePictureView.image = [UIImage imageWithData:data];        
        }
    }
}


In this example, the getWithPath:delegate:userState method of the LiveConnectClient variable calls the Live Connect APIs to get info about the signed-in user. If the call is successful, this example code is part of a larger interface that implements the LiveOperationDelegate interface and so its liveOperationSucceeded method is called. Otherwise, if the call by userState is unsuccessful, the example's liveOperationFailed:operation method is called. Note that the userState parameter, when set to @"me" or @"me-picture", is used to find the correct logic for you to call to get the user's name, gender, and profile link, to get the user's profile picture, and to display them in the correct controls.

Top

Getting the user's name and profile picture in Java for Android

Here's how to display the user's name.


public void greetUser() {
    client.getAsync("me", new LiveOperationListener() {
        public void onComplete(LiveOperation operation) {
            JSONObject result = operation.getResult();
            resultTextView.setText("Hello, " + result.optString("name") + "!");
        }
        public void onError(LiveOperationException exception, LiveOperation operation) {
            resultTextView.setText("Error getting name: " + exception.getMessage());
        }
    });
}


In the onClick event-handler method, the code calls the getAsync method from the instance of LiveConnectClient. If the call is successful, the code displays a message that contains the signed-in user's first and last name. The code gets the user's first and last name from the getResult method of the LiveOperation argument instance. The getResult method call gets a representation of the JSON-formatted info.

Here's how to display the user's profile picture.


public void getUserImage() {
    client.getAsync("me/picture", new LiveOperationListener() {
        public void onComplete(LiveOperation operation) 
        {
            JSONObject result = operation.getResult();
            String link = result.optString("location");
            showImage(link);                        
        }
        public void onError(LiveOperationException exception, LiveOperation operation) 
        {
            resultTextView.setText("Error getting user's profile picture: " + exception.getMessage());
        }
    });
}

private void showImage(String url)
{
    client.downloadAsync(url, new LiveDownloadOperationListener() {
        public void onDownloadCompleted(LiveDownloadOperation operation)
        {
            InputStream input =  operation.getStream();
            try {
                Bitmap bMap = BitmapFactory.decodeStream(input);
                picture.setImageBitmap(bMap);
            } 
            finally {
                try {
                    input.close(); 
                }
                catch (IOException e) {
                }
            }
        }
        public void onDownloadFailed(LiveOperationException exception, LiveDownloadOperation operation)
        {
            resultTextView.setText("Error getting user's profile picture: " + exception.getMessage());
        }
        public void onDownloadProgress(int totalBytes, int bytesRemaining, LiveDownloadOperation operation)
        {
            resultTextView.setText("Downloading user's profile picture... " + bytesRemaining + " bytes downloaded " +
                    "(" + (bytesRemaining / totalBytes) * 100 + "%)");
        }
    });
}


The code does this:

  1. The getAsync method of the LiveConnectClient instance calls me/picture to get the user's profile picture.
  2. If the call to get the user's profile picture succeeds, the getResult method of the onComplete method's operation parameter gets info about the user's picture as a JSON-formatted object.
  3. The custom showImage method uses the location structure in the JSON-formatted object to get the user's profile picture and then show it in a picture-viewer control.

Top

Getting the user's name and profile picture using REST

To get the user's name, after you make the appropriate GET call in Representational State Transfer (REST), the user's first and last names are in the response. Here's how to make a GET call. (In this example, me represents the signed-in user.)

GET https://apis.live.net/v5.0/me?access_token=ACCESS_TOKEN

And here's how to get the user's profile picture. (In this example, me again represents the signed-in user.)

GET https://apis.live.net/v5.0/me/picture?access_token=ACCESS_TOKEN

Top

Next steps

You now have an app that can greet a user by name and display his or her profile picture. Learn more about:

Top

 

 

Show:
© 2014 Microsoft