1

这是我删除一组日历条目的代码:

public async Task<bool> DeleteCalendarEvents(SettingsBase oSettings)
{
    try
    {
        var oEvents = await _graphClient
                                .Me
                                .Calendars[oSettings.CalendarID]
                                .Events
                                .Request()
                                .Select("Start,Subject,Id")
                                .Top(50)
                                .Filter(oSettings.GetFilterString())
                                .OrderBy("start/DateTime")
                                .GetAsync();

        List<Event> listEvents = new List<Event>();

        listEvents.AddRange(oEvents);
        while (oEvents.NextPageRequest != null)
        {
            oEvents = await oEvents.NextPageRequest.GetAsync();
            listEvents.AddRange(oEvents);
        }

        foreach (Event oEvent in listEvents)
        { 
            await _graphClient.Me.Events[oEvent.Id].Request().DeleteAsync();
        }
    }
    catch (Exception ex)
    {
        SimpleLog.Log(ex);
        Console.WriteLine("DeleteCalendarEvents: See error log.");
        return false;
    }

    return true;
}

然后我有一个方法可以将新事件添加到日历中:

public async Task<bool> AddEventsToCalendar(MWBData.MWBCalendarData oData)
{
    if (oData.SettingsMWB.CalendarEntryType != "CLM_MidweekMeeting")
    {
        SimpleLog.Log("AddEventsToCalendar: CalendarEntryType is not set to CLM_MidweekMeeting.", SimpleLog.Severity.Error);
        Console.WriteLine("AddEventsToCalendar: See error log.");
        return false;
    }

    try
    {
        // Now create the new events
        foreach (EventWeek oWeek in oData.Weeks)
        {
            bool bSuccess = await AddEventToCalendar(oWeek, oData.SettingsMWB);
            if(bSuccess)
            {
                // Now create any Weekend Meeting events
                if(oWeek.WeekendMeeting.Included)
                {
                    bSuccess = await AddEventToCalendar(oWeek.WeekendMeeting, oData.SettingsMWB);
                    if(!bSuccess)
                    {
                        Console.WriteLine("AddEventsToCalendar: See error log.");
                        return false;
                    }
                }
            }
            else
            {
                Console.WriteLine("AddEventToCalendar: See error log.");
                return false;
            }
        }
    }
    catch (Exception ex)
    {
        SimpleLog.Log(ex);
        Console.WriteLine("AddEventsToCalendar: See error log.");
        return false;
    }

    return true;
}

如您所见,对于它调用的每个事件AddEventToCalendar。该方法部分地创建了这样的事件:

// Add the event
Event createdEvent = await _graphClient.Me.Calendars[oSettings.CalendarID].Events.Request().AddAsync(new Event
{
    Subject = oEvent.GetSubject(),
    Body = body,
    Start = startTime,
    End = endTime,
    IsAllDay = oEvent.IsAllDayEvent(),
    IsReminderOn = bSetReminder,
    ReminderMinutesBeforeStart = bSetReminder ? iReminderMinutes : (int?)null,
    Location = location,
    SingleValueExtendedProperties = extendedProperties,
    Sensitivity = oSettings.SetCalendarPrivate ? Sensitivity.Private : Sensitivity.Normal
});

现在,我知道 Microsoft Graph 支持使用 JSON 的批处理模式。但是我不知道如何用我写的东西来实现它。尝试将我的代码转换为批处理操作列表以减少调用是有意义的。

我该怎么做呢?

更新

我找到了这篇文章,但我不确定它是否相关以及我应该做什么。因此,我仍然希望获得有关如何执行此操作的任何具体指导。我确信其他潜在用户将从中受益匪浅——或者被引导到我错过的现有资源。谢谢你。

4

2 回答 2

1

即使尚不支持批量请求,您也可以考虑以下概念验证,该概念演示如何实现对检索实体的基本支持:msgraph-sdk-dotnet

//1.Construct a Batch request 
var batchRequest = new BatchRequest(); 
//2. Add sub queries. Two parameters needs to be specified: a request and a result object                 
batchRequest.AddQuery(graphClient.Users[loginName].Request(), typeof(Microsoft.Graph.User));
batchRequest.AddQuery(graphClient.Sites["root"].Request(),typeof(Microsoft.Graph.Site));
//3. Execute Batch request
var result = await graphClient.GetBatchAsync(batchRequest);  

其中BatchRequest类引入了对批处理请求的支持

public class BatchRequest
{

    private Dictionary<string, IBaseRequest> _queriesTable = new Dictionary<string, IBaseRequest>();
    private Dictionary<string,Type> _resultsTable = new Dictionary<string, Type>();

    public KeyValuePair<IBaseRequest, Type> this[string queryId]
    {
        get
        {
            return new KeyValuePair<IBaseRequest,Type>(_queriesTable[queryId], _resultsTable[queryId]);
        }
    }


    public void AddQuery(IBaseRequest query, Type entityType)
    {
        var queryId = Guid.NewGuid().ToString();
        _resultsTable[queryId] = entityType;
        _queriesTable[queryId] = query;
    } 


    /// <summary>
    /// Construct JSON batch request https://developer.microsoft.com/en-us/graph/docs/concepts/json_batching
    /// </summary>
    /// <param name="client"></param>
    /// <returns></returns>
    public HttpRequestMessage ToMessage(GraphServiceClient client)
    {
        var batchMessage = new HttpRequestMessage();
        batchMessage.RequestUri = new Uri("https://graph.microsoft.com/v1.0/$batch");
        batchMessage.Method = HttpMethod.Post;
        batchMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        dynamic payload = new ExpandoObject();
        payload.requests = _queriesTable.Select(kv =>
        {
            var message = kv.Value.GetHttpRequestMessage();
            dynamic request = new ExpandoObject();
            request.id = kv.Key; 
            request.method = message.Method.ToString();
            request.url = message.RequestUri.AbsoluteUri.Replace(client.BaseUrl,string.Empty);
            if(message.Content != null)
                request.body = message.Content;

            request.headers = message.Headers.ToDictionary(x => x.Key, x => x.Value.FirstOrDefault());
            return request;
        });
        var jsonPayload = client.HttpProvider.Serializer.SerializeObject(payload);
        batchMessage.Content = new StringContent(jsonPayload,Encoding.UTF8,"application/json");
        return batchMessage;
    }

}

并且GetBatchAsync是执行批处理请求的扩展方法:

public static class GraphServiceClientExtensions
{
    public static async Task<List<object>> GetBatchAsync(this GraphServiceClient client, BatchRequest request)
    {
        var batchMessage = request.ToMessage(client);
        await client.AuthenticationProvider.AuthenticateRequestAsync(batchMessage);
        var response = await client.HttpProvider.SendAsync(batchMessage);

        var content = await response.Content.ReadAsStringAsync();
        var json = JObject.Parse(content);
        var entities = json["responses"].Select(item =>
        {
            var queryId = (string)item["id"];
            var entityPayload = JsonConvert.SerializeObject(item["body"]);
            var subRequest = request[queryId];
            var entity = JsonConvert.DeserializeObject(entityPayload, subRequest.Value);
            return entity;
        }); 
        return entities.ToList();
    }
}

要旨:Microsoft.Graph.BatchSupport.cs

就像我说的那样,这只是一个概念验证,并且在这个实现中只支持检索实体,所以如果你想实现像删除这样的其他操作,你可以利用它作为起点

结果

在此处输入图像描述

于 2018-11-06T18:18:58.477 回答
0

图形库现在不支持此功能。

https://github.com/microsoftgraph/msgraph-sdk-dotnet/issues/136

一种解决方法,使用HttpClient请求批处理端点,

Mock jsonObject(需要使用StringBuilder等创建字符串,使用for/foreach遍历事件列表,然后将item info追加到json对象中,记得增加id值):

注意:嵌套 json 似乎不适用于 Graph,所以这个工作区仍然需​​要测试。

    {
      "requests": [
        {
          "id": "1",
         "url": "/me",
          "method": "POST",
          "body": {
  "subject": "Let's go for lunch",
  "body": {
    "contentType": "HTML",
    "content": "Does late morning work for you?"
  },
  "start": {
      "dateTime": "2017-04-15T12:00:00",
      "timeZone": "Pacific Standard Time"
  },
  "end": {
      "dateTime": "2017-04-15T14:00:00",
      "timeZone": "Pacific Standard Time"
  },
  "location":{
      "displayName":"Harry's Bar"
  },
  "attendees": [
    {
      "emailAddress": {
        "address":"samanthab@contoso.onmicrosoft.com",
        "name": "Samantha Booth"
      },
      "type": "required"
    }
  ]
},
          "headers": {
            "Content-Type": "application/json"
          }
        },
        {
          "id": "2",
         "url": "/me",
          "method": "POST",
          "body": {
  "subject": "Let's go for lunch",
  "body": {
    "contentType": "HTML",
    "content": "Does late morning work for you?"
  },
  "start": {
      "dateTime": "2017-04-15T12:00:00",
      "timeZone": "Pacific Standard Time"
  },
  "end": {
      "dateTime": "2017-04-15T14:00:00",
      "timeZone": "Pacific Standard Time"
  },
  "location":{
      "displayName":"Harry's Bar"
  },
  "attendees": [
    {
      "emailAddress": {
        "address":"samanthab@contoso.onmicrosoft.com",
        "name": "Samantha Booth"
      },
      "type": "required"
    }
  ]
},
          "headers": {
            "Content-Type": "application/json"
          }
        },
        {
          "id": "3", 
          "url": "/me",
          "method": "POST",
          "body": {
  "subject": "Let's go for lunch",
  "body": {
    "contentType": "HTML",
    "content": "Does late morning work for you?"
  },
  "start": {
      "dateTime": "2017-04-15T12:00:00",
      "timeZone": "Pacific Standard Time"
  },
  "end": {
      "dateTime": "2017-04-15T14:00:00",
      "timeZone": "Pacific Standard Time"
  },
  "location":{
      "displayName":"Harry's Bar"
  },
  "attendees": [
    {
      "emailAddress": {
        "address":"samanthab@contoso.onmicrosoft.com",
        "name": "Samantha Booth"
      },
      "type": "required"
    }
  ]
},
          "headers": {
            "Content-Type": "application/json"
          }
        }
      ]
    }

执行代码:

var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); 
var result = await client.PostAsync(url, content);
于 2018-11-06T02:35:21.233 回答