是否可以创建带有附件的日历事件?

Is it possible to create calendar events with attachments?

我想使用 Microsoft Graph 创建一个日历活动,这很有效,但不幸的是,我无法向该活动添加附件。事件已创建但没有附件。没有报错。

这是我的代码:

DateTimeTimeZone start = new DateTimeTimeZone
{
    TimeZone = TimeZoneInfo.Local.Id,
    DateTime = dateTimePicker1.Value.ToString("o"),
};

DateTimeTimeZone end = new DateTimeTimeZone
{
    TimeZone = TimeZoneInfo.Local.Id,
    DateTime = dateTimePicker2.Value.ToString("o"),
};

Location location = new Location
{
    DisplayName = "Thuis",
};

byte[] contentBytes = System.IO.File
    .ReadAllBytes(@"C:\test\sample.pdf");

var ev = new Event();

FileAttachment fa = new FileAttachment
{
    ODataType = "#microsoft.graph.fileAttachment",
    ContentBytes = contentBytes,
    ContentType = "application/pdf",
    Name = "sample.pdf",
    IsInline = false,
    Size = contentBytes.Length
};

ev.Attachments = new EventAttachmentsCollectionPage();
ev.Attachments.Add(fa);

ev.Start = start;
ev.End = end;
ev.IsAllDay = false;
ev.Location = location;
ev.Subject = textBox2.Text;

var response = await graphServiceClient
    .Users["user@docned.nl"]
    .Calendar
    .Events
    .Request()
    .AddAsync(ev);

似乎仍然不支持在 单个 请求 ()

中创建带有附件的事件

作为解决方法,可以先创建一个没有附件的事件,然后将附件添加到其中(需要向服务器发出两次请求),例如:

var ev = new Event
{
    Start = start,
    End = end,
    IsAllDay = false,
    Location = location,
    Subject = subject
};

//1.create an event first 
var evResp = await graphServiceClient.Users[userId].Calendar.Events.Request().AddAsync(ev);

byte[] contentBytes = System.IO.File.ReadAllBytes(localPath);
var attachmentName = System.IO.Path.GetFileName(localPath);
var fa = new FileAttachment
{
    ODataType = "#microsoft.graph.fileAttachment",
    ContentBytes = contentBytes,
    ContentType = MimeMapping.GetMimeMapping(attachmentName),
    Name = attachmentName,
    IsInline = false
};

//2. add attachments to event
var faResp = await graphServiceClient.Users[userId].Calendar.Events[evResp.Id].Attachments.Request().AddAsync(fa);

我发现如果您创建没有与会者的活动,而不是创建附件并更新与会者的活动,他们将收到包含所有附件的活动电子邮件。

我正在使用 HTTP put 将其更改为 GRAPH SDK 应该没有问题。

这是我的代码:

var eventContainer = new EventContainer();
eventContainer.Init(); //populate the event with everything except the attendees and attachments        

//Send POST request and get the updated event obj back
eventContainer = GraphUtil.CreateEvent(eventContainer);

//Create a basic attachment
var attachment = new Attachment
{
      ODataType = "#microsoft.graph.fileAttachment",
      contentBytes = Convert.ToBase64String(File.ReadAllBytes(path)),
      name = $"attachment.pdf"
};

//Post request to create the attachment and get updated obj back
attachment = GraphUtil.CreateAttachment(attachment);

//Prepare new content to update the event
var newContent = new
{
       attachments = new List<Attachment> { attachment },
       attendees = New List<Attendee> { attends } //populate attendees here
};

//Patch request containing only the new content get the updated event obj back.
eventContainer = GraphUtil.UpdateEvent(newContent);

如果您在发送活动后发送附件,与会者只能在他们的日历活动中看到附件,而不能在要求他们确认的活动电子邮件中看到附件。

您可以在活动中通过创建共享来共享 OneDrive 中的文件 link。

如果文件不在OneDrive中,您必须先将文件上传到OneDrive。之后,您可以创建一个分享 link 并在活动正文中将附件展示给与会者(已授予访问权限)。

public async Task<DriveItem> uploadFileToOneDrive(string eventOwnerEmail, string filePath, string fileName)
{
    // get a stream of the local file
    FileStream fileStream = new FileStream(filePath, FileMode.Open);

    string token = GetGraphToken();

    var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
    {
        requestMessage
            .Headers
            .Authorization = new AuthenticationHeaderValue("bearer", token);

        return Task.FromResult(0);
    }));


    // upload the file to OneDrive
    var uploadedFile = graphServiceClient.Users[eventOwnerEmail].Drive.Root
                                  .ItemWithPath(fileName)
                                  .Content
                                  .Request()
                                  .PutAsync<DriveItem>(fileStream)
                                  .Result;

    return uploadedFile;
}


public async Task<Permission> getShareLinkOfDriveItem(string eventOwnerEmail, DriveItem _item)
{
    string token = GetGraphToken();

    var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
    {
        requestMessage
            .Headers
            .Authorization = new AuthenticationHeaderValue("bearer", token);

        return Task.FromResult(0);
    }));    
    
    var type = "view";
    var scope = "anonymous"; 

    var ret = await graphServiceClient.Users[eventOwnerEmail].Drive.Items[_item.Id]
                                .CreateLink(type, scope, null, null, null)
                                .Request()
                                .PostAsync();


    return ret;
}

您可以从您的程序中调用方法,如下所示:

var driveItem = uploadFileToOneDrive(eventOwnerEmail, filePath, fileName);
Task<Permission> shareLinkInfo = getShareLinkOfDriveItem(eventOwnerEmail, driveItem);

string shareLink = shareLinkInfo.Result.Link.WebUrl;

您可以将共享文件附加到活动正文中,如下所示:

 body = "<p>You can access the file from the link: <a href = '" + shareLink  + "' >" + driveItem.Name + " </a></p> ";