zoukankan      html  css  js  c++  java
  • Windows 商店应用中使用 Office 365 API Tools

    本篇我们介绍一个API 工具,用于在 Windows Store App 中使用 Office 365 API。

    首先来说一下本文的背景:

    使用 SharePoint 做过开发的同学们应该都知道,SharePoint 有一套客户端对象模型(Client Object Model)用于读取和操作列表和文档库的数据。这个模型支持的应用程序类型包括ASP.NET、WPF、Silverlight和WP等,但是 Windows Store App 不在支持行列中(这一点我一直不太理解)。。。这样的话,我们就没办法在 Store App 中直接使用这个模型了,那如果我们的 Store App 想利用 SharePoint 作为服务端,应该怎么办呢?

    这也是最初接触 Store App 和 SharePoint 的时候困扰我的东西。当时是在给微软中国做一个应用,需求是将 Office 365 与 Store App 相结合,在 Store App 中实现对 Office 365 数据的读取和操作,将多种数据和文件集成到一起,形成一个一站式个人工作平台,进而展示 Office 365 在工作中的作用,作为微软 Office 365 宣传的 Demo 使用。需求其实挺简单,但是最常用的对象模型不被支持,这就没这么简单了。值得庆幸的是我们还有另外一套神器:SharePoint REST API (REST API reference and samples)。

    SharePoint为我们提供了一套标准的 REST API,利用它我们可以通过网络请求的方式来读取和更新数据。读取数据还算简单,只需要拼接 API 地址和解析 json / XML 数据就可以了。但是操作数据就比较麻烦了,拼接需要 POST 的内容是一件说起来很容易,但很繁琐的工作。而且更让人头疼的是 SharePoint Online 的认证方式。(关于 REST API 的使用,我会在随后的文章中介绍,这里只是让大家感受一下使用的感受。)所以相对以对象模型,我们需要做的工作也多了不少。这就是本文的前提背景,找一个工具来把我们从繁琐的工作中解脱出来。它就是 Microsoft Office 365 API Tools for Visual Studio 2013

    下载地址:https://visualstudiogallery.msdn.microsoft.com/a15b85e6-69a7-4fdf-adda-a38066bb5155 。只支持 Visual Studio 2013。来看看安装程序的信息:

    安装过程很简单,这里就不介绍了。利用这个工具,就可以实现数据的操作,包括了邮件、联系人、日历、文件等。

    下面我们来看看详细的使用过程:

    1. 在工程中添加工具中的服务 

    解决方案名上点右键,选择 “添加” -> "连接的服务",出现下面界面

    点击“注册应用”,登录自己的 Office 365 账号,就会出现与 Office 365 站点关联的信息

    选择一项服务,点击右侧的“权限...”对该服务的权限进行配置,配置后点击“确定”,就可以完成对这一项服务的引用了。这个过程中工具对将你添加的服务注册到 Microsoft Azure Active Directory 中。这里的配置会在应用进行登录认证的时候提示给用户,类似于微博 API 认证过程。

    2. 在代码中整合 Office 365 API

    代码中 Office 365 API 的整个分为三个步骤:

    (1). Creating the Office 365 discovery client

    我们的程序会调用不同的Endpoints来展现不同内容,例如用户邮件、日历、OneDrive 或联系人等。程序需要调用 Office 365 Discovery Service 来获得这些 EndPoints 的地址。

    详细描述可以参照:http://msdn.microsoft.com/en-us/office/office365/howto/discover-service-endpoints 和 http://msdn.microsoft.com/en-us/office/office365/api/discovery-service-rest-operations 。

    (2). Getting an access token for Office 365

    在授权使用 Discovery Service 时,我们的代码可以使用从Azure AD 中返回的 token,这个 token 用于下一步访问数据之用。

    (3). Creating the client object to access the Office 365 services

    在获得了 Office 365 数据取得的权限后,我们就可以创建客户端对象来取得我们需要的数据了。

    不同类型的数据需要创建不用的客户端对象,例如日历、联系人、邮件,需要创建 Outlook Services client object。文件 和 网站,需要创建 SharePoint client object。用户信息 需要创建 Azure AD client object。

    我们看一段简单的代码来验证一下这个过程:

    public async Task<List<IContact>> GetContactsAsync()
    {
    
        // Make sure we have a reference to the Exchange client
        var exchangeClient = await AuthenticationHelper.EnsureOutlookClientCreatedAsync();
    
        // Query contacts
        var contactsResults = await exchangeClient.Me.Contacts.OrderBy(c => c.DisplayName).ExecuteAsync();
    
        // Return the first page of contacts. 
        return contactsResults.CurrentPage.ToList();
    
    }
    public static async Task<OutlookServicesClient> EnsureOutlookClientCreatedAsync()
    {
        try
        {
            AuthenticationContext = new AuthenticationContext(CommonAuthority);
    
            if (AuthenticationContext.TokenCache.ReadItems().Count() > 0)
            {
                // Bind the AuthenticationContext to the authority that sourced the token in the cache 
                // this is needed for the cache to work when asking for a token from that authority 
                // (the common endpoint never triggers cache hits) 
                string cachedAuthority = AuthenticationContext.TokenCache.ReadItems().First().Authority;
                AuthenticationContext = new AuthenticationContext(cachedAuthority);
    
            }
    
            // Create a DiscoveryClient using the discovery endpoint Uri.  
            DiscoveryClient discovery = new DiscoveryClient(DiscoveryServiceEndpointUri,
                async () => await AcquireTokenAsync(AuthenticationContext, DiscoveryResourceId));
    
            // Now get the capability that you are interested in.
            CapabilityDiscoveryResult result = await discovery.DiscoverCapabilityAsync("Mail");
    
            var client = new OutlookServicesClient(
                result.ServiceEndpointUri,
                async () => await AcquireTokenAsync(AuthenticationContext, result.ServiceResourceId));
    
            return client;
        }
        // The following is a list of all exceptions you should consider handling in your app.
        // In the case of this sample, the exceptions are handled by returning null upstream. 
        catch (DiscoveryFailedException dfe)
        {
            MessageDialogHelper.DisplayException(dfe as Exception);
    
            // Discovery failed.
            AuthenticationContext.TokenCache.Clear();
            return null;
        }
        catch (MissingConfigurationValueException mcve)
        {
            MessageDialogHelper.DisplayException(mcve);
    
            // Connected services not added correctly, or permissions not set correctly.
            AuthenticationContext.TokenCache.Clear();
            return null;
        }
        catch (AuthenticationFailedException afe)
        {
            MessageDialogHelper.DisplayException(afe);
    
            // Failed to authenticate the user
            AuthenticationContext.TokenCache.Clear();
            return null;
    
        }
        catch (ArgumentException ae)
        {
            MessageDialogHelper.DisplayException(ae as Exception);
            // Argument exception
            AuthenticationContext.TokenCache.Clear();
            return null;
        }
    }

    这里我们获得了 Outlook Service 的 Client,并且获得了 token,然后利用这个 Client 来取得 Outlook 的联系人信息。

    这里是一个完整的使用了 Office 365 API Tools 的 Windows Store App Demo:https://github.com/OfficeDev/Office-365-APIs-Starter-Project-for-Windows,供大家参考。

    好了,到这里我们就把 Office 365 API Tools 介绍完了,希望对大家开发 Store App 有所帮助。下一篇我们将对前面提到的 SharePoint 2013 REST API 做出详细介绍,谢谢! 

  • 相关阅读:
    自我介绍
    工作流
    spring框架
    关于建立内部会议讨论规范的想法
    论文第3章:移动绘图平台的架构设计
    迭代器、推导式、函数式编程学习笔记
    Python装饰器学习(九步入门)
    Inkpad绘图原理浅析
    从零开始创建一个插件
    Entity Framework的启动速度优化
  • 原文地址:https://www.cnblogs.com/shaomeng/p/4097311.html
Copyright © 2011-2022 走看看