Работа с элементами календаря на Exchange Server

Отправка запросов на встречу

В этой статье показано, как отправить запрос на встречу нескольким получателям с помощью Exchange Web Services и Aspose.Email.

  1. Создайте запрос на встречу, используя класс Appointment, и укажите местоположение, время и участников.
  2. Создайте экземпляр класса MailMessage и установите встречу с помощью метода MailMessage.AddAlternateView().
  3. Подключитесь к Exchange Server и отправьте запрос на встречу, используя метод Send(MailMessage).

Класс EWSClient можно использовать для подключения к Exchange Server с поддержкой Exchange Web Services (EWS). Для этого сервер должен быть Exchange Server 2007 или более поздней версии. Следующий фрагмент кода показывает, как использовать EWS для отправки запросов на встречу.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
try
{
// Create instance of IEWSClient class by giving credentials
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain");
// Create the meeting request
Appointment app = new Appointment("meeting request", DateTime.Now.AddHours(1), DateTime.Now.AddHours(1.5), "administrator@test.com", "bob@test.com");
app.Summary = "meeting request summary";
app.Description = "description";
RecurrencePattern pattern = new Aspose.Email.Calendar.Recurrences.DailyRecurrencePattern(DateTime.Now.AddDays(5));
app.Recurrence = pattern;
// Create the message and set the meeting request
MailMessage msg = new MailMessage();
msg.From = "administrator@test.com";
msg.To = "bob@test.com";
msg.IsBodyHtml = true;
msg.HtmlBody = "<h3>HTML Heading</h3><p>Email Message detail</p>";
msg.Subject = "meeting request";
msg.AddAlternateView(app.RequestApointment(0));
// send the appointment
client.Send(msg);
Console.WriteLine("Appointment request sent");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

Работа с элементами календаря с использованием EWS

Aspose.Email предоставляет возможность добавлять, обновлять и отменять встречи с помощью клиента Exchange Web Service (EWS). Методы IEWSClient CreateAppointment, UpdateAppointment и CancelAppointment позволяют управлять элементами календаря с использованием EWS. В этой статье приведен подробный пример кода для работы с элементами календаря. Следующий пример кода показывает, как:

  1. Создать встречу.
  2. Обновить встречу.
  3. Удалить/Отменить встречу.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "your.username", "your.Password");
DateTime date = DateTime.Now;
DateTime startTime = new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0);
DateTime endTime = startTime.AddHours(1);
string timeZone = "America/New_York";
Appointment app = new Appointment("Room 112", startTime, endTime, "organizeraspose-email.test3@domain.com","attendee@gmail.com");
app.SetTimeZone(timeZone);
app.Summary = "NETWORKNET-34136" + Guid.NewGuid().ToString();
app.Description = "NETWORKNET-34136 Exchange 2007/EWS: Provide support for Add/Update/Delete calendar items";
string uid = client.CreateAppointment(app);
Appointment fetchedAppointment1 = client.FetchAppointment(uid);
app.Location = "Room 115";
app.Summary = "New summary for " + app.Summary;
app.Description = "New Description";
client.UpdateAppointment(app);
Appointment[] appointments1 = client.ListAppointments();
Console.WriteLine("Total Appointments: " + appointments1.Length);
Appointment fetchedAppointment2 = client.FetchAppointment(uid);
Console.WriteLine("Summary: " + fetchedAppointment2.Summary);
Console.WriteLine("Location: " + fetchedAppointment2.Location);
Console.WriteLine("Description: " + fetchedAppointment2.Description);
client.CancelAppointment(app);
Appointment[] appointments2 = client.ListAppointments();
Console.WriteLine("Total Appointments: " + appointments2.Length);

Список встреч с поддержкой пагинации

Метод ListAppointments, предоставляемый API IEWSClient, извлекает полный список встреч с Exchange сервера. Это может занять время, если на Exchange Server имеется большое количество встреч. API предоставляет перегруженные методы метода ListAppointments, которые обеспечивают поддержку пагинации для данной операции. Это можно использовать в различных комбинациях с функцией запросов. Следующие перегруженные методы доступны для перечисления встреч с Exchange Server с поддержкой пагинации.

  • AppointmentCollection IEWSClient.ListAppointments(int itemsPerPage).
  • AppointmentCollection IEWSClient.ListAppointments(string folderUri, int itemsPerPage).
  • AppointmentCollection IEWSClient.ListAppointments(MailQuery query, int itemsPerPage).
  • AppointmentCollection IEWSClient.ListAppointments(string folderUri, MailQuery query, int itemsPerPage).
  • AppointmentCollection IEWSClient.ListAppointments(int itemsPerPage, int itemOffset).
  • AppointmentCollection IEWSClient.ListAppointments(string folderUri, int itemsPerPage, int itemOffset).
  • AppointmentCollection IEWSClient.ListAppointments(MailQuery query, int itemsPerPage, int itemOffset).
  • AppointmentCollection IEWSClient.ListAppointments(string folderUri, MailQuery query, int itemsPerPage, int itemOffset).

Следующий фрагмент кода показывает, как перечислить встречи с поддержкой пагинации.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
using (IEWSClient client = EWSClient.GetEWSClient("exchange.domain.com", "username", "password"))
{
try
{
Appointment[] appts = client.ListAppointments();
Console.WriteLine(appts.Length);
DateTime date = DateTime.Now;
DateTime startTime = new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0);
DateTime endTime = startTime.AddHours(1);
int appNumber = 10;
Dictionary<string, Appointment> appointmentsDict = new Dictionary<string, Appointment>();
for (int i = 0; i < appNumber; i++)
{
startTime = startTime.AddHours(1);
endTime = endTime.AddHours(1);
string timeZone = "America/New_York";
Appointment appointment = new Appointment(
"Room 112",
startTime,
endTime,
"from@domain.com",
"to@domain.com");
appointment.SetTimeZone(timeZone);
appointment.Summary = "NETWORKNET-35157_3 - " + Guid.NewGuid().ToString();
appointment.Description = "EMAILNET-35157 Move paging parameters to separate class";
string uid = client.CreateAppointment(appointment);
appointmentsDict.Add(uid, appointment);
}
AppointmentCollection totalAppointmentCol = client.ListAppointments();
///// LISTING APPOINTMENTS WITH PAGING SUPPORT ///////
int itemsPerPage = 2;
List<AppointmentPageInfo> pages = new List<AppointmentPageInfo>();
AppointmentPageInfo pagedAppointmentCol = client.ListAppointmentsByPage(itemsPerPage);
Console.WriteLine(pagedAppointmentCol.Items.Count);
pages.Add(pagedAppointmentCol);
while (!pagedAppointmentCol.LastPage)
{
pagedAppointmentCol = client.ListAppointmentsByPage(itemsPerPage, pagedAppointmentCol.PageOffset + 1);
pages.Add(pagedAppointmentCol);
}
int retrievedItems = 0;
foreach (AppointmentPageInfo folderCol in pages)
retrievedItems += folderCol.Items.Count;
}
finally
{
}
}

Добавление события во вторичный календарь на Exchange Server

API Aspose.Email позволяет вам создать вторичный каталог календаря на Exchange Server с помощью IEWSClient. Встречи можно добавлять, обновлять или отменять из вторичного календаря с использованием методов CreateAppointment, UpdateAppointment и CancelAppointment. В следующих примерах кода используются методы и свойства API, чтобы продемонстрировать функциональность этой функции. Обратите внимание, что эта функция поддерживается в Aspose.Email для .NET начиная с версии 6.5.0.

  • Метод IEWSClient.CancelAppointment(Appointment, String).
  • Метод IEWSClient.CancelAppointment(String, String).
  • Метод IEWSClient.CreateAppointment(Appointment, String).
  • Метод IEWSClient.CreateFolder(String, String, ExchangeFolderPermissionCollection, String).
  • Метод IEWSClient.FetchAppointment(String, String).
  • Метод IEWSClient.UpdateAppointment(Appointment, String).
  • Свойство IEWSClient.CurrentCalendarFolderUri.

Следующий фрагмент кода показывает, как добавить событие во вторичный календарь на Exchange Server.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
using (IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "your.username", "your.Password"))
{
try
{
// Create an appointmenta that will be added to secondary calendar folder
DateTime date = DateTime.Now;
DateTime startTime = new DateTime(date.Year, date.Month, date.Day, date.Hour, 0, 0);
DateTime endTime = startTime.AddHours(1);
string timeZone = "America/New_York";
Appointment[] listAppointments;
Appointment appointment = new Appointment("Room 121", startTime, endTime, "from@domain.com", "attendee@domain.com");
appointment.SetTimeZone(timeZone);
appointment.Summary = "EMAILNET-35198 - " + Guid.NewGuid().ToString();
appointment.Description = "EMAILNET-35198 Ability to add event to Secondary Calendar of Office 365";
// Verify that the new folder has been created
ExchangeFolderInfoCollection calendarSubFolders = client.ListSubFolders(client.MailboxInfo.CalendarUri);
string getfolderName;
string setFolderName = "New Calendar";
bool alreadyExits = false;
// Verify that the new folder has been created already exits or not
for (int i = 0; i < calendarSubFolders.Count; i++)
{
getfolderName = calendarSubFolders[i].DisplayName;
if (getfolderName.Equals(setFolderName))
{
alreadyExits = true;
}
}
if (alreadyExits)
{
Console.WriteLine("Folder Already Exists");
}
else
{
// Create new calendar folder
client.CreateFolder(client.MailboxInfo.CalendarUri, setFolderName, null, "IPF.Appointment");
Console.WriteLine(calendarSubFolders.Count);
// Get the created folder URI
string newCalendarFolderUri = calendarSubFolders[0].Uri;
// appointment api with calendar folder uri
// Create
client.CreateAppointment(appointment, newCalendarFolderUri);
appointment.Location = "Room 122";
// update
client.UpdateAppointment(appointment, newCalendarFolderUri);
// list
listAppointments = client.ListAppointments(newCalendarFolderUri);
// list default calendar folder
listAppointments = client.ListAppointments(client.MailboxInfo.CalendarUri);
// Cancel
client.CancelAppointment(appointment, newCalendarFolderUri);
listAppointments = client.ListAppointments(newCalendarFolderUri);
// appointment api with context current calendar folder uri
client.CurrentCalendarFolderUri = newCalendarFolderUri;
// Create
client.CreateAppointment(appointment);
appointment.Location = "Room 122";
// update
client.UpdateAppointment(appointment);
// list
listAppointments = client.ListAppointments();
// list default calendar folder
listAppointments = client.ListAppointments(client.MailboxInfo.CalendarUri);
// Cancel
client.CancelAppointment(appointment);
listAppointments = client.ListAppointments();
}
}
finally
{
}
}

Обмен приглашениями на календарь

Сервер Microsoft Exchange предоставляет возможность делиться календарями, отправляя приглашения на календарь другим пользователям, зарегистрированным на том же сервере Exchange. API Aspose.Email предоставляет ту же возможность, позволяя делиться календарем с использованием API EWS.

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
using (IEWSClient client = EWSClient.GetEWSClient("https://outlook.office365.com/ews/exchange.asmx", "testUser", "pwd", "domain"))
{
// delegate calendar access permission
ExchangeDelegateUser delegateUser = new ExchangeDelegateUser("sharingfrom@domain.com", ExchangeDelegateFolderPermissionLevel.NotSpecified);
delegateUser.FolderPermissions.CalendarFolderPermissionLevel = ExchangeDelegateFolderPermissionLevel.Reviewer;
client.DelegateAccess(delegateUser, "sharingfrom@domain.com");
// Create invitation
MapiMessage mapiMessage = client.CreateCalendarSharingInvitationMessage("sharingfrom@domain.com");
MailConversionOptions options = new MailConversionOptions();
options.ConvertAsTnef = true;
MailMessage mail = mapiMessage.ToMailMessage(options);
client.Send(mail);
}

Получение информации о расширенных атрибутах из элементов календаря

// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET
IEWSClient client = EWSClient.GetEWSClient("https://exchange.office365.com/Exchange.asmx", "username","password");
//Fetch all calendars from Exchange calendar's folder
string[] uriList = client.ListItems(client.MailboxInfo.CalendarUri);
//Define the Extended Attribute Property Descriptor for searching purpose
//In this case, we have a K1 Long named property for Calendar item
PropertyDescriptor propertyDescriptor = new PidNamePropertyDescriptor("K1", PropertyDataType.Integer32, new Guid("00020329-0000-0000-C000-000000000046"));
//Fetch calendars that have the custom property
IList<MapiCalendar> mapiCalendarList = client.FetchMapiCalendar(uriList, new PropertyDescriptor[] { propertyDescriptor });
foreach (MapiCalendar cal in mapiCalendarList)
{
foreach (MapiNamedProperty namedProperty in cal.NamedProperties.Values)
{
Console.WriteLine(namedProperty.NameId + " = " + namedProperty.GetInt32());
}
}

Возврат повторяющихся элементов календаря в заданном диапазоне дат

EWSClient поддерживает возврат повторяющихся элементов календаря в диапазоне, заданном параметрами StartDate и EndDate. Метод AppointmentQueryBuilder.SetCalendarView используется для определения конкретного диапазона дат и ограничения количества возвращаемых встреч для получения соответствующей информации. Установив следующие параметры, вы можете получить встречи, соответствующие указанным критериям.

  • startDate: Дата начала календарного представления. Встречи, начинающиеся с этой даты, будут включены в результат запроса.

  • endDate: Дата окончания календарного представления. Встречи, заканчивающиеся до этой даты или в этот день, будут включены в результат запроса.

  • maxEntriesReturned: Максимальное количество встреч, которые будут возвращены в результате запроса. Значение -1 указывает на то, что нет конкретного ограничения.

ExchangeQueryBuilder builder = new ExchangeQueryBuilder();
builder.Appointment.SetCalendarView(DateTime.Now, DateTime.Now.AddMonths(1), -1);

Appointment[] appointments = client.ListAppointments(builder.GetQuery());