如何使用C#MSGraph将日历事件添加到Outlook 365 [英] How To Add Calendar Events to Outlook 365 Using C# MSGraph

查看:144
本文介绍了如何使用C#MSGraph将日历事件添加到Outlook 365的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用的当前应用程序实质上是为Microsoft Outlook 365创建包装器应用程序.我与MSGraph的合作不多,并且一直很难将事件设置为从窗体登录到用户的日历中窗口,或者在获取令牌后实际上做任何事情.这是我目前正在尝试使用的代码.

A current application I'm working on is to create essentially a wrapper application for Microsoft Outlook 365. I haven't worked much with MSGraph, and have been having a hard time setting events to the logged in user's calendar from the Form Window, or really doing anything after acquiring a token. and this is the code I'm currently trying to use.

    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);
        }
    }

更新

好的,感谢下面的Seiya Su,我设法使这段代码大部分都起作用了,但是,每当我向日历中添加一个事件时,都需要登录.

Okay thanks to Seiya Su below I managed to make this code work for the most part, However, every single time I add an event to the calendar it requires logging in.

    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);          

我建立了一个测试方法来解决这个问题,并尝试过以下方法:

I built a test method to mess around and tried things like this:

    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);

    }

但是它仍然无法正常工作,并要求我为添加的每个事件登录.我同意用户必须登录,只要他们只登录一次,是否有人知道解决此问题的方法?我目前的想法是将令牌传递给请求,但这似乎无济于事.

But it still didn't work and asked me to log in for every event added. I am OKAY with the user having to log in, as long as they only log in once, does anyone know a way around this issue? My current thought was to pass the token along to the request but that seemed to do nothing.

推荐答案

1您在代码中使用了错误的EndPoint.

1 You use wrong EndPoint in your code.

2由于可以使用MS图形库,因此这里有一个更有效的工作代码.您可以重新封装它.

2 Since you can use the MS Graph Library, here's a more efficient worked code.You can just re-encapsulate it.

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

Update 2018-10-5

对于您的更新代码,我们不需要每次都传递令牌.我不确定您的Windows操作系统是WPF还是Winform等.对于MVC项目,代码和身份验证流是否应该更好地工作.只需尝试将脱机或此类合并范围传递到您的 GraphScope 设置文件.

For your updated code, we don't need to pass the token everytime. I am not sure your From Windows is WPF or Winform or such.The code and auth flow should work better for MVC project. Just try to pass offline or such Scope to your GraphScope setting file.

最后.不要总是将遇到的新问题更新为现有问题.尽管它们是相关的,但不再是一个问题.虽然旧问题已经解决,但最好还是再提出一个新问题.否则它们仍然是一个问题.

Last. Don't always update the new issue you encounter to the exist question. Although they are related, but not one question any more. While the old question have close, the better open a new one. Otherwise they are still one issue.

这篇关于如何使用C#MSGraph将日历事件添加到Outlook 365的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆