簡體   English   中英

使用Microsoft.Graph通過C#控制台應用程序列出日歷

[英]Using Microsoft.Graph to list calendars with C# Console Application

我在這讓自己陷入了真正的泡菜。 :(我只是不明白如何轉移我在這里看到的內容:

https://developer.microsoft.com/zh-CN/graph/docs/api-reference/beta/api/user_list_calendars

進入我的C#控制台應用程序的上下文。

我做了很多:

//Set the scope for API call to user.read
string[] _scopes = new string[] { "user.read",  "calendars.read" };

並確認我登錄時確實要求訪問用戶日歷。

但是我不知道從這里去哪里。 我在示例代碼中有這個:

   private void DisplayBasicTokenInfo(AuthenticationResult authResult)
    {
        string strTokenInfoText = "";
        if (authResult != null)
        {
            strTokenInfoText += $"Name: {authResult.User.Name}" + Environment.NewLine;
            strTokenInfoText += $"Username: {authResult.User.DisplayableId}" + Environment.NewLine;
            strTokenInfoText += $"Token Expires: {authResult.ExpiresOn.ToLocalTime()}" + Environment.NewLine;
            strTokenInfoText += $"Access Token: {authResult.AccessToken}" + Environment.NewLine;
            Console.WriteLine(strTokenInfoText);
        }
    }

但是顯然沒有什么可以用來獲得日歷列表的。

我在這里問了一個類似的問題,沒有任何答案,但是從那時起,我取得了更多進步:

結合使用Microsoft Outlook API和C#列出日歷並添加事件

更新資料

我這樣調整我的方法:

public async Task AquireToken()
{
    AuthenticationResult authResult = null;

    try
    {
        if (authResult == null)
        {
            authResult = await Program.PublicClientApp.AcquireTokenSilentAsync(_scopes, Program.PublicClientApp.Users.FirstOrDefault());
        }
    }
    catch (MsalUiRequiredException ex)
    {
        // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
        System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

        try
        {
            authResult = await Program.PublicClientApp.AcquireTokenAsync(_scopes);
        }
        catch (MsalException msalex)
        {
            strResultsText = $"Error Acquiring Token:{System.Environment.NewLine}{msalex}";
        }
    }
    catch (Exception ex)
    {
        strResultsText = $"Error Acquiring Token Silently:{System.Environment.NewLine}{ex}";
    }

    if (authResult != null)
    {
        strResultsText = await GetHttpContentWithToken(_graphAPIEndpoint, authResult.AccessToken);

        DisplayBasicTokenInfo(authResult);

        GraphServiceClient graphClient = new GraphServiceClient(
             new DelegateAuthenticationProvider(
                 (requestMessage) =>
                 {
                     // Append the access token to the request.
                     requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
                     return Task.FromResult(0);
                 }));

        SignOut();
        if (strResultsText != "")
            Console.WriteLine(strResultsText);
    }
}

如您所見,我添加了以下代碼:

GraphServiceClient graphClient = new GraphServiceClient(
     new DelegateAuthenticationProvider(
         (requestMessage) =>
         {
             // Append the access token to the request.
             requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
             return Task.FromResult(0);
         }));

我在SignOut上設置了一個斷點,但無法使其正常工作。

我希望能夠使用graphClient.me.Calendars

困惑。

更新資料

我試着看讀過的書。 也許我只是在錯誤的地方做事? 但是當我設置一個斷點時:

斷點

這不是我所期望的。

更新2

我這樣調整代碼:

   if (authResult != null)
    {
        strResultsText = await GetHttpContentWithToken(_graphAPIEndpoint, authResult.AccessToken);

        DisplayBasicTokenInfo(authResult);

        GraphServiceClient graphClient = new GraphServiceClient(
                 new DelegateAuthenticationProvider(
                     (requestMessage) =>
                     {
                         // Append the access token to the request.
                         requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
                         return Task.FromResult(0);
                     }));

        var calendars = await graphClient
                             .Me
                             .Calendars
                             .Request()
                             .GetAsync();
        Console.WriteLine(calendars.Count.ToString());
        List<Calendar> listCalendars = calendars.ToList();
        foreach(Calendar oCalendar in listCalendars)
        {
            Console.WriteLine(oCalendar.Name);
        }
        SignOut();
        if (strResultsText != "")
            Console.WriteLine(strResultsText);
    }

在監視列表上沒有斷點的情況下,在SignOut上具有斷點,在我的控制台窗口中,我有:

控制台輸出

因此,似乎正常。 我想我可能只需要調整代碼的邏輯,並獲取AquireToken方法即可返回Token並從那里獲取它。 我明天再玩。

更新3

感謝您的評論,我開始努力:

public async Task BuildCalendarsList()
{
    if (_AuthResult == null)
        return;

    try
    {
        GraphServiceClient graphClient = new GraphServiceClient(
                 new DelegateAuthenticationProvider(
                     (requestMessage) =>
                     {
                         // Append the access token to the request.
                         requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", _AuthResult.AccessToken);
                         return Task.FromResult(0);
                     }));

        var calendars = await graphClient
                             .Me
                             .Calendars
                             .Request()
                             .GetAsync();

        Console.WriteLine($"Number of calendars: {calendars.Count}");

        _ListCalendars = calendars.ToList();
    }
    catch(Exception ex)
    {
        _ListCalendars = null;
        Console.WriteLine($"Error BuildCalendarsList: {ex.Message}");
    }
}

public void DisplayCalendarsList()
{
    try
    {
        foreach (Calendar oCalendar in _ListCalendars)
        {
            string strCalendarInfo = $"Calendar Name: {oCalendar.Name}";
            strCalendarInfo += $" Calendar Id: {oCalendar.Id}";
            Console.WriteLine(strCalendarInfo);
        }
    }
    catch(Exception ex)
    {
        Console.WriteLine($"Error DisplayCalendarsList: {ex.Message}");
    }
 }

為了他人的利益,這就是我的工作方式:

public bool InitAuthenticatedClientAsync()
{
    bool bSuccess = true;

    _graphClient = new GraphServiceClient(
        new DelegateAuthenticationProvider(
            async (requestMessage) =>
            {
                try
                {
                    var accounts = await PublicClientApp.GetAccountsAsync();
                    // See: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released#acquiring-a-token-also-got-simpler
                    _AuthResult = await PublicClientApp.AcquireTokenSilent(_Scopes, accounts.FirstOrDefault()).ExecuteAsync();
                }
                catch (MsalUiRequiredException ex)
                {
                    // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
                    System.Diagnostics.Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");

                    try
                    {
                        // See: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/MSAL.NET-3-released#acquiring-a-token-also-got-simpler
                        _AuthResult = await PublicClientApp.AcquireTokenInteractive(_Scopes).ExecuteAsync();
                    }
                    catch (MsalException msalex)
                    {
                        SimpleLog.Log(msalex);
                        Console.WriteLine("GetAuthenticatedClientAsync: Acquire token error. See log.");
                        bSuccess = false;
                    }
                }
                catch (Exception ex)
                {
                    SimpleLog.Log(ex);
                    Console.WriteLine("GetAuthenticatedClientAsync: Acquire token silently error. See log.");
                    bSuccess = false;
                }

                if(bSuccess)
                {
                    // Append the access token to the request.
                    requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", _AuthResult.AccessToken);

                    // Get event times in the current time zone.
                    requestMessage.Headers.Add("Prefer", "outlook.timezone=\"" + TimeZoneInfo.Local.Id + "\"");
                }
            }));

    return bSuccess;
}

public async Task<bool> BuildCalendarsList()
{
    bool bSuccess = true;

    if (_graphClient == null)
        return false;

    try
    {
        var calendars = await _graphClient
                             .Me
                             .Calendars
                             .Request()
                             .GetAsync();


        foreach (Calendar oCalendar in calendars)
        {
            _CalendarInfo.AddCalendarEntry(oCalendar.Name, oCalendar.Id);
        }

        bSuccess = SaveCalendarInfo();
    }
    catch (Exception ex)
    {
        SimpleLog.Log(ex);
        Console.WriteLine("BuildCalendarsList: See error log.");
        bSuccess = false;
    }

    return bSuccess;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM