Текущее приложение, над которым я работаю, - это создание приложения-оболочки для 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);
}
}
ОБНОВЛЕНИЕ
Хорошо, благодаря 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);
}
Но это все равно не сработало и попросило меня войти в систему для каждого добавленного события.Я согласен с тем, что пользователю приходится входить в систему, если он входит в систему только один раз. Кто-нибудь знает способ обойти эту проблему?Моя текущая мысль состояла в том, чтобы передать токен запросу, но это, похоже, ничего не дало.