Обновление повторяющегося ряда с помощью EWS в Exchange
Узнайте, как обновить всю повторяющуюся серию одновременно с помощью управляемого API EWS или EWS в Exchange.
Управляемый API EWS или EWS можно использовать для обновления повторяющегося ряда, обновив весь ряд или обновив одно вхождение. В этой статье мы обсудим, как обновить всю серию одновременно.
Как правило, обновление повторяющегося ряда очень похоже на изменение одной встречи. Вы используете те же методы и операции, но используете идентификатор элемента повторяющегося образца серии. В некоторых случаях вы не можете начать с повторяющегося образца, и вам может потребоваться найти идентификатор элемента для повторяющегося образца.
Однако при обновлении повторяющегося ряда следует учитывать одно ключевое различие: обновление шаблона повторения. Обновление шаблона повторения возможно только с помощью повторяющегося образца, а изменения в шаблоне могут добавлять или удалять вхождения. Например, если изменить свойство Recurrence.EndDate до даты, превышающей его текущее значение, шаблон повторения будет повторно оценен, и могут быть добавлены дополнительные вхождения.
Изменение всех вхождений в ряде с помощью управляемого API EWS
Чтобы изменить все вхождения в ряде, выполните следующие действия:
- Привязать к повторяющимся главному элементу для ряда с помощью метода Appointment.BindToRecurringMaster или Appointment.Bind для повторяющегося образца.
- Обновите свойства повторяющегося объекта Master Appointment .
- Сохраните изменения в повторяющейся главной коллекции с помощью метода Appointment.Save .
В следующем примере обновляется повторяющийся ряд для изменения расположения, добавления участника и изменения шаблона повторения. В этом примере предполагается, что объект ExchangeService, переданный в параметре службы, инициализирован с допустимыми значениями в свойствах Credentials и Url. Параметр recurringAppointment — это объект Appointment , привязанный к вхождаемости или повторяющегося главного элемента для обновляемого ряда.
using Microsoft.Exchange.WebServices.Data;
public static bool UpdateRecurringSeries(ExchangeService service, Appointment recurringAppointment)
{
Appointment recurringMaster = null;
// If the item is a single appointment, fail.
if (recurringAppointment.AppointmentType == AppointmentType.Single)
{
Console.WriteLine("ERROR: The item to delete is not part of a recurring series.");
return false;
}
// Check the Appointment that was passed. Is it
// an occurrence or the recurring master?
if (recurringAppointment.AppointmentType != AppointmentType.RecurringMaster)
{
// If an occurrence was passed in, bind to the master.
try
{
// This method results in a call to EWS.
recurringMaster = Appointment.BindToRecurringMaster(service, recurringAppointment.Id);
}
catch (Exception ex)
{
Console.WriteLine("Couldn't bind to master: {0}", ex.Message);
return false;
}
}
else
{
// Bind to the appointment to load all properties.
// This method results in a call to EWS.
recurringMaster = Appointment.Bind(service, recurringAppointment.Id);
}
// Basic updates. These kinds of updates are the same
// as if you were updating a single appointment.
// Update the location. All occurrences will update to this new location.
recurringMaster.Location = "Conference Room 2";
// Add an attendee.
Attendee newAttendee = new Attendee("sadie@contoso.com");
recurringMaster.RequiredAttendees.Add(newAttendee);
// Changes to the recurrence. This is only applicable to a recurring
// master.
// If the series has an end date, extend the series to add two more occurrences.
if (recurringMaster.Recurrence.HasEnd)
{
// NumberOfOccurrences is only set if the user created the
// appointment with a set number of occurrences.
// Otherwise, there's a start and end date.
if (recurringMaster.Recurrence.NumberOfOccurrences != null)
{
recurringMaster.Recurrence.NumberOfOccurrences += 2;
}
else
{
// This is a bit more complicated if you want to add two more
// occurrences. You need to calculate a new end date.
Type recurrenceType = recurringMaster.Recurrence.GetType();
switch (recurrenceType.Name)
{
case "DailyPattern":
recurringMaster.Recurrence.EndDate =
recurringMaster.Recurrence.EndDate.Value.AddDays(2);
break;
case "WeeklyPattern":
recurringMaster.Recurrence.EndDate =
recurringMaster.Recurrence.EndDate.Value.AddDays(14);
break;
case "YearlyPattern":
recurringMaster.Recurrence.EndDate =
recurringMaster.Recurrence.EndDate.Value.AddYears(2);
break;
default:
// Do nothing here. There are other recurrence
// types but for simplicity, these aren't covered.
break;
}
}
}
else
{
// If it has no end, set an end date to 2 weeks from today.
recurringMaster.Recurrence.EndDate = DateTime.Now.AddDays(14);
}
// Update the series.
try
{
// This method results in a call to EWS.
recurringMaster.Update(ConflictResolutionMode.AutoResolve);
}
catch (Exception ex)
{
Console.WriteLine("Error updating series: {0}", ex.Message);
return false;
}
return true;
}
Изменение всех вхождений в ряде с помощью EWS
Чтобы изменить все вхождения в ряде, необходимо использовать операцию UpdateItem с идентификатором элемента повторяющегося образца в элементе ItemId в запросе. Структура запроса аналогична запросу на обновление одной встречи.
В следующем примере обновляется повторяющийся ряд следующими способами:
- Обновления расположение ряда, задав элемент Location.
- Обновления участников, задав элемент RequiredAttendees.
- Обновления повторение, задав элемент Recurrence (RecurrenceType).
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types"
xmlns:soap="https://schemas.xmlsoap.org/soap/envelope/">
<soap:Header>
<t:RequestServerVersion Version="Exchange2007_SP1" />
<t:TimeZoneContext>
<t:TimeZoneDefinition Id="Eastern Standard Time" />
</t:TimeZoneContext>
</soap:Header>
<soap:Body>
<m:UpdateItem MessageDisposition="SaveOnly" ConflictResolution="AutoResolve" SendMeetingInvitationsOrCancellations="SendToAllAndSaveCopy">
<m:ItemChanges>
<t:ItemChange>
<t:ItemId Id="AAMkADA5..." ChangeKey="DwAAABYA..." />
<t:Updates>
<t:SetItemField>
<t:FieldURI FieldURI="calendar:Location" />
<t:CalendarItem>
<t:Location>Conference Room 2</t:Location>
</t:CalendarItem>
</t:SetItemField>
<t:SetItemField>
<t:FieldURI FieldURI="calendar:RequiredAttendees" />
<t:CalendarItem>
<t:RequiredAttendees>
<t:Attendee>
<t:Mailbox>
<t:Name>Mack Chaves</t:Name>
<t:EmailAddress>mack@contoso.com</t:EmailAddress>
<t:RoutingType>SMTP</t:RoutingType>
</t:Mailbox>
</t:Attendee>
<t:Attendee>
<t:Mailbox>
<t:Name>Sadie Daniels</t:Name>
<t:EmailAddress>sadie@contoso.com</t:EmailAddress>
<t:RoutingType>SMTP</t:RoutingType>
</t:Mailbox>
</t:Attendee>
</t:RequiredAttendees>
</t:CalendarItem>
</t:SetItemField>
<t:SetItemField>
<t:FieldURI FieldURI="calendar:Recurrence" />
<t:CalendarItem>
<t:Recurrence>
<t:WeeklyRecurrence>
<t:Interval>1</t:Interval>
<t:DaysOfWeek>Tuesday</t:DaysOfWeek>
</t:WeeklyRecurrence>
<t:EndDateRecurrence>
<t:StartDate>2014-05-06</t:StartDate>
<t:EndDate>2014-06-22-04:00</t:EndDate>
</t:EndDateRecurrence>
</t:Recurrence>
</t:CalendarItem>
</t:SetItemField>
<t:SetItemField>
<t:FieldURI FieldURI="calendar:MeetingTimeZone" />
<t:CalendarItem>
<t:MeetingTimeZone TimeZoneName="Pacific Standard Time" />
</t:CalendarItem>
</t:SetItemField>
</t:Updates>
</t:ItemChange>
</m:ItemChanges>
</m:UpdateItem>
</soap:Body>
</soap:Envelope>
Сервер отвечает элементом UpdateItemResponse , который включает элемент ResponseCode со значением NoError, указывающим, что обновление прошло успешно.