重新想象 Windows 8 Store Apps (58) - 微軟賬號


[源碼下載]


重新想象 Windows 8 Store Apps (58) - 微軟賬號



作者:webabcd


介紹
重新想象 Windows 8 Store Apps 之 微軟賬號

  • 獲取微軟賬號的用戶相關的信息
  • 獲取或設置微軟賬號的圖片和視頻
  • 微軟賬號的驗證,和相關信息的獲取



示例
1、演示如何獲取微軟賬號的用戶相關的信息
Account/AccountInfo.xaml

<Page
    x:Class="XamlDemo.Account.AccountInfo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Account"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">

            <TextBlock Name="lblMsg" FontSize="14.667" />

        </StackPanel>
    </Grid>
</Page>

Account/AccountInfo.xaml.cs

/*
 * 演示如何獲取微軟賬號的用戶相關的信息
 */

using System;
using Windows.System.UserProfile;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;

namespace XamlDemo.Account
{
    public sealed partial class AccountInfo : Page
    {
        public AccountInfo()
        {
            this.InitializeComponent();
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (UserInformation.NameAccessAllowed) // 是否允許訪問用戶名
            {
                // 獲取用於顯示的名稱
                lblMsg.Text = "display name: " + await UserInformation.GetDisplayNameAsync();
                lblMsg.Text += Environment.NewLine;

                // 獲取 first name
                lblMsg.Text += "first name: " + await UserInformation.GetFirstNameAsync();
                lblMsg.Text += Environment.NewLine;

                // 獲取 last name
                lblMsg.Text += "last name: " + await UserInformation.GetLastNameAsync();
                lblMsg.Text += Environment.NewLine;
            }

            // 如果需要獲取 GetDomainNameAsync(), GetPrincipalNameAsync(), GetSessionInitiationProtocolUriAsync() 等信息
            // 則需要在 Package.appxmanifest 中增加配置 <Capability Name="enterpriseAuthentication" />,且必須使用公司賬號上傳 app
        }
    }
}


2、演示如何獲取或設置微軟賬號的圖片和視頻
Account/AccountPicture.xaml

<Page
    x:Class="XamlDemo.Account.AccountPicture"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Account"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">

            <StackPanel Orientation="Horizontal">
                <Button x:Name="btnSetImage" Content="設置當前微軟賬號的圖片(可以分別指定小圖,大圖,視頻)" Click="btnSetImage_Click_1" />
            </StackPanel>

            <StackPanel Orientation="Horizontal" Margin="0 10 0 0">
                <Image x:Name="imgSmall" Width="96" Height="96" HorizontalAlignment="Left" />
                <Image x:Name="imgLarge" Width="448" Height="448" Margin="10 0 0 0" HorizontalAlignment="Left" />
                <MediaElement x:Name="mediaElement" Width="200" Height="200" Margin="10 0 0 0" HorizontalAlignment="Left" />
            </StackPanel>

        </StackPanel>
    </Grid>
</Page>

Account/AccountPicture.xaml.cs

/*
 * 演示如何獲取或設置微軟賬號的圖片和視頻
 */

using System;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.System.UserProfile;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using XamlDemo.Common;

namespace XamlDemo.Account
{
    public sealed partial class AccountPicture : Page
    {
        public AccountPicture()
        {
            this.InitializeComponent();
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            GetSmallImage();
            GetLargeImage();
            GetVideo();

            // 當微軟賬號的圖片或視頻發生變化時觸發的事件
            UserInformation.AccountPictureChanged += PictureChanged;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            UserInformation.AccountPictureChanged -= PictureChanged;
        }

        private void PictureChanged(object sender, object e)
        {
            GetSmallImage();
            GetLargeImage();
            GetVideo();
        }

        // 獲取小圖片
        private async void GetSmallImage()
        {
            // UserInformation.GetAccountPicture(AccountPictureKind.SmallImage) - 獲取當前微軟賬號的小圖片
            StorageFile image = UserInformation.GetAccountPicture(AccountPictureKind.SmallImage) as StorageFile;
            if (image != null)
            {
                try
                {
                    IRandomAccessStream imageStream = await image.OpenReadAsync();
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(imageStream);
                    imgSmall.Source = bitmapImage;
                }
                finally { }
            }
        }

        // 獲取大圖片
        private async void GetLargeImage()
        {
            // UserInformation.GetAccountPicture(AccountPictureKind.LargeImage) - 獲取當前微軟賬號的大圖片
            StorageFile image = UserInformation.GetAccountPicture(AccountPictureKind.LargeImage) as StorageFile;
            if (image != null)
            {
                try
                {
                    IRandomAccessStream imageStream = await image.OpenReadAsync();
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.SetSource(imageStream);
                    imgLarge.Source = bitmapImage;
                }
                finally { }
            }
        }

        // 獲取視頻
        private async void GetVideo()
        {
            // UserInformation.GetAccountPicture(AccountPictureKind.Video) - 獲取當前微軟賬號的視頻
            StorageFile video = UserInformation.GetAccountPicture(AccountPictureKind.Video) as StorageFile;
            if (video != null)
            {
                try
                {
                    IRandomAccessStream videoStream = await video.OpenAsync(FileAccessMode.Read);
                    mediaElement.SetSource(videoStream, "video/mp4");
                }
                finally { }
            }
        }


        // 設置圖片
        private async void btnSetImage_Click_1(object sender, RoutedEventArgs e)
        {
            if (Helper.EnsureUnsnapped())
            {
                FileOpenPicker imagePicker = new FileOpenPicker
                {
                    ViewMode = PickerViewMode.Thumbnail,
                    SuggestedStartLocation = PickerLocationId.PicturesLibrary,
                    FileTypeFilter = { ".jpg", ".jpeg", ".png", ".bmp" }
                };

                StorageFile imageFile = await imagePicker.PickSingleFileAsync();
                if (imageFile != null)
                {
                    // UserInformation.SetAccountPicturesAsync() - 設置微軟賬號的圖片和視頻(可以分別指定:小圖片,大圖片,視頻)
                    SetAccountPictureResult result = await UserInformation.SetAccountPicturesAsync(null, imageFile, null);
                    if (result == SetAccountPictureResult.Success)
                    {
                       
                    }
                }
            }
        }
    }
}


3、演示微軟賬號的驗證,和相關信息的獲取
Account/AccountAuthorization.xaml

<Page
    x:Class="XamlDemo.Account.AccountAuthorization"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:XamlDemo.Account"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="Transparent">
        <StackPanel Margin="120 0 0 0">

            <TextBlock Name="lblMsg" FontSize="14.667" />
            <Button Name="btnSignIn" Content="登錄"  Margin="0 10 0 0" Click="btnSignIn_Click_1" />
            <Button Name="btnSignOut" Content="注銷" Margin="0 10 0 0" Click="btnSignOut_Click_1" />
            
        </StackPanel>
    </Grid>
</Page>

Account/AccountAuthorization.xaml.cs

/*
 * 演示微軟賬號的驗證,和相關信息的獲取
 * 
 * 注:
 * 1、如果要使用此功能,需要先去 https://manage.dev.live.com/Applications/Index 注冊,否則會出現“應用程序請求身份驗證令牌被禁用或者配置錯誤”錯誤
 * 2、關於 Live Connect 的更多東西,請參見“Live Connect 開發人員中心”:http://msdn.microsoft.com/zh-cn/live
 */

using System;
using System.Collections.Generic;
using Windows.Security.Authentication.OnlineId;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace XamlDemo.Account
{
    public sealed partial class AccountAuthorization : Page
    {
        // OnlineIdAuthenticator - 用於身份驗證,以及信息獲取
        private OnlineIdAuthenticator _authenticator;

        public AccountAuthorization()
        {
            this.InitializeComponent();

            _authenticator = new OnlineIdAuthenticator();
        }

        private async void btnSignIn_Click_1(object sender, RoutedEventArgs e)
        {
            lblMsg.Text += "登錄中";
            lblMsg.Text += Environment.NewLine;

            try
            {
                // 用於身份驗證,以及獲取 token(通過此 token 可以用 rest 方式獲取指定范圍內的信息)
                var targetArray = new List<OnlineIdServiceTicketRequest>();
                targetArray.Add(new OnlineIdServiceTicketRequest("wl.basic wl.contacts_photos wl.calendars", "DELEGATION"));

                /*
                 * OnlineIdAuthenticator.AuthenticateUserAsync() - 登錄
                 *     CredentialPromptType.DoNotPrompt - 不顯示登錄 UI(可能會導致無法登錄)
                 *     CredentialPromptType.PromptIfNeeded - 如果需要的話才顯示登錄 UI(一般來說一個 app 在登錄成功一次之后,就不必再通過 UI 登錄了)
                 *     CredentialPromptType.RetypeCredentials - 始終顯示登錄 UI
                 */
                var result = await _authenticator.AuthenticateUserAsync(targetArray, CredentialPromptType.PromptIfNeeded);
                if (result.Tickets[0].Value != string.Empty)
                {
                    lblMsg.Text += "已登錄";
                    lblMsg.Text += Environment.NewLine;

                    // 獲取 token (此 token 可以通過 rest 方式訪問 wl.basic wl.contacts_photos wl.calendars 信息)
                    // 相關信息的訪問地址 https://apis.live.net/v5.0/me?access_token=
                    lblMsg.Text += "token: " + result.Tickets[0].Value;
                    lblMsg.Text += Environment.NewLine;
                }
                else
                {
                    lblMsg.Text += "未得到 token ,errorCode: " + result.Tickets[0].ErrorCode.ToString();
                    lblMsg.Text += Environment.NewLine;
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text += ex.ToString();
                lblMsg.Text += Environment.NewLine;
            }
        }

        private async void btnSignOut_Click_1(object sender, RoutedEventArgs e)
        {
            lblMsg.Text += "注銷中";
            lblMsg.Text += Environment.NewLine;

            // OnlineIdAuthenticator.SignOutUserAsync() - 注銷
            await _authenticator.SignOutUserAsync();

            lblMsg.Text += "已注銷";
            lblMsg.Text += Environment.NewLine;
        }
    }
}



OK
[源碼下載]


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM