簡體   English   中英

如何使用C#MSGraph將日歷事件添加到Outlook 365

[英]How To Add Calendar Events to Outlook 365 Using C# MSGraph

我正在使用的當前應用程序實質上是為Microsoft Outlook 365創建包裝器應用程序。我與MSGraph的合作不多,並且一直很難從“表單窗口”中將事件設置為登錄用戶的日歷,或者在獲取令牌后真正做任何事情。 這是我當前正在嘗試使用的代碼。

    PublicClientApplication clientApp;
    GraphServiceClient graphClient;
    string token;
    string userEmail;


    public async void Start()
    {
        await GetDataAsync();
        return;
    }

    async Task GetDataAsync()
    {
        clientApp = new PublicClientApplication(ConfigurationManager.AppSettings["ClientId"].ToString());

        graphClient = new GraphServiceClient(
                    "https://graph.microsoft.com/v1.0",
                    new DelegateAuthenticationProvider(
                        async (requestMessage) =>
                        {
                            requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", await GetTokenAsync(clientApp));
                        }));

        var currentUser = await graphClient.Me.Request().GetAsync().ConfigureAwait(false);
        userEmail = currentUser.Mail;
        return;
    }


    async Task<string> GetTokenAsync(PublicClientApplication clientApp)
    {
        //need to pass scope of activity to get token
        string[] Scopes = { "User.Read", "Calendars.ReadWrite", "Calendars.ReadWrite.Shared"};
        token = null;

        AuthenticationResult authResult = await clientApp.AcquireTokenAsync(Scopes).ConfigureAwait(false);
        token = authResult.AccessToken;

        return token;
    }


    public async void SetAppointment(string subject, DateTime start, DateTime end, List<Attendee> attendies)
    {
        try
        {
            using (HttpClient c = new HttpClient())
            {
                String requestURI = "https://graph.microsoft.com/v1.0/users/" + userEmail + "/calendar/events.";


                ToOutlookCalendar toOutlookCalendar = new ToOutlookCalendar();


                TimeZone Timezone = TimeZone.CurrentTimeZone;
                toOutlookCalendar.Subject = subject;
                toOutlookCalendar.Start = start;
                toOutlookCalendar.End = end;
                toOutlookCalendar.Attendees = attendies;


                HttpContent httpContent = new StringContent(JsonConvert.SerializeObject(toOutlookCalendar), Encoding.UTF8, "application/json");

                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestURI);
                request.Content = httpContent;
                //Authentication token
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

                var response = await c.SendAsync(request);
                var responseString = await response.Content.ReadAsStringAsync();
            }
        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
    }

UPDATE

好的,感謝下面的Seiya Su,我設法使這段代碼大部分都起作用了,但是,每當我向日歷中添加一個事件時,都需要登錄。

    public async void SetAppointment(string Subject, string Body, string Start, string End, string Location, List<string> attendees) 
    {
        var myEvent = new Microsoft.Graph.Event();
        myEvent.Subject = Subject;
        myEvent.Body = new ItemBody() { ContentType = BodyType.Text, Content = Body };
        myEvent.Start = new DateTimeTimeZone() { DateTime = Start, TimeZone = "" };
        myEvent.End = new DateTimeTimeZone() { DateTime = End, TimeZone = "" };
        myEvent.Location = new Location() { DisplayName = Location };

        var appointment = await graphClient.Me.Calendar.Events.Request().AddAsync(myEvent);          

我構建了一個測試方法來解決這個問題,並嘗試了以下操作:

    public async void graphTesting()
    { 
        var myEvent = new Microsoft.Graph.Event();
        myEvent.Subject = "Test";
        myEvent.Body = new ItemBody() { ContentType = BodyType.Text, Content = "This is test." };
        myEvent.Start = new DateTimeTimeZone() { DateTime = "2018-10-3T12:00:00", TimeZone = "Pacific Standard Time" };
        myEvent.End = new DateTimeTimeZone() { DateTime = "2018-10-3T13:00:00", TimeZone = "Pacific Standard Time" };
        myEvent.Location = new Location() { DisplayName = "conf room 1" };
        //myEvent.Attendees = attendies;                   


        var myEvent2 = new Microsoft.Graph.Event();
        myEvent2.Subject = "Test";
        myEvent2.Body = new ItemBody() { ContentType = BodyType.Text, Content = "This is test." };
        myEvent2.Start = new DateTimeTimeZone() { DateTime = "2018-10-4T12:00:00", TimeZone = "Pacific Standard Time" };
        myEvent2.End = new DateTimeTimeZone() { DateTime = "2018-10-4T13:00:00", TimeZone = "Pacific Standard Time" };
        myEvent2.Location = new Location() { DisplayName = "conf room 1" };
        //myEvent.Attendees = attendies;                   



        // Create the event.
        var user = graphClient.Me.Calendar.Events.Request();
        await user.Header("bearer", token).AddAsync(myEvent);
        await user.Header("bearer", token).AddAsync(myEvent2);

    }

但是它仍然無法正常工作,要求我為添加的每個事件登錄。 我同意用戶必須登錄,只要他們只登錄一次,是否有人知道解決此問題的方法? 我目前的想法是將令牌傳遞給請求,但這似乎無濟於事。

1您在代碼中使用了錯誤的EndPoint。

2由於您可以使用MS圖形庫,因此這里有一個更有效的工作代碼。您可以重新封裝它。

var myEvent = new Microsoft.Graph.Event();
myEvent.Subject = "Test";
myEvent.Body = new ItemBody() { ContentType = BodyType.Text, Content = "This is test." };
myEvent.Start = new DateTimeTimeZone() { DateTime = "2018-9-29T12:00:00", TimeZone = "Pacific Standard Time" };
myEvent.End = new DateTimeTimeZone() { DateTime = "2018-9-29T13:00:00", TimeZone = "Pacific Standard Time" };
myEvent.Location = new Location() { DisplayName = "conf room 1" }; 
 //myEvent.Attendees = attendies;                   

 // Create the event. 
 //graphClient.Me.Calendar.Events.Request().AddAsync(myEvent)
 var mySyncdEvent = await graphClient.Users["you mail"].Calendar.Events.Request()
.AddAsync(myEvent);

更新2018-10-5

對於您的更新代碼,我們不需要每次都傳遞令牌。 我不確定您的From Windows是WPF還是Winform之類的。代碼和身份驗證流對於MVC項目是否應該工作得更好。 只需嘗試將脫機或此類范圍傳遞到您的GraphScope設置文件。

持續。 不要總是將遇到的新問題更新為現有問題。 盡管它們是相關的,但不再是一個問題。 雖然舊問題已經解決,但最好還是再提出一個新問題。 否則它們仍然是一個問題。

暫無
暫無

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

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