Работа с элементами календаря на Exchange Server
Отправка запросов на встречу
В этой статье показано, как отправить запрос на встречу нескольким получателям с использованием Exchange Web Services и Aspose.Email.
- Создайте запрос на встречу с использованием класса Appointment и укажите место, время и участников.
- Создайте экземпляр класса MailMessage и назначьте встречу с помощью метода MailMessage->AddAlternateView() .
- Подключитесь к серверу Exchange и отправьте запрос на встречу с помощью метода IEWSClient->Send(MailMessage) .
Класс EWSClient можно использовать для подключения к серверам Exchange с поддержкой 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-C | |
try | |
{ | |
// Create instance of IEWSClient class by giving credentials | |
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser()); | |
// Create the meeting request | |
System::SharedPtr<Appointment> app = System::MakeObject<Appointment>(u"meeting request", System::DateTime::get_Now().AddHours(1), System::DateTime::get_Now().AddHours(1.5), MailAddress::to_MailAddress(u"administrator@test.com"), MailAddressCollection::to_MailAddressCollection(u"bob@test.com")); | |
app->set_Summary(u"meeting request summary"); | |
app->set_Description(u"description"); | |
System::SharedPtr<RecurrencePattern> pattern = System::MakeObject<Aspose::Email::Calendar::Recurrences::DailyRecurrencePattern>(System::DateTime::get_Now().AddDays(5)); | |
app->set_Recurrence(pattern); | |
// Create the message and set the meeting request | |
System::SharedPtr<MailMessage> msg = System::MakeObject<MailMessage>(); | |
msg->set_From(MailAddress::to_MailAddress(u"administrator@test.com")); | |
msg->set_To(MailAddressCollection::to_MailAddressCollection(u"bob@test.com")); | |
msg->set_IsBodyHtml(true); | |
msg->set_HtmlBody(u"<h3>HTML Heading</h3><p>Email Message detail</p>"); | |
msg->set_Subject(u"meeting request"); | |
msg->AddAlternateView(app->RequestApointment(0)); | |
// send the appointment | |
client->Send(msg); | |
System::Console::WriteLine(u"Appointment request sent"); | |
} | |
catch (System::Exception& ex) | |
{ | |
System::Console::WriteLine(ex.get_Message()); | |
} |
Работа с элементами календаря с использованием EWS
Aspose.Email предоставляет возможность добавления, обновления и отмены встреч с использованием клиента Exchange Web Service (EWS). Методы IEWSClient->CreateAppointment, IEWSClient->UpdateAppointment и IEWSClient->CancelAppointment позволяют управлять элементами календаря с помощью EWS. В этой статье приведен подробный образец кода для работы с элементами календаря. Следующий образец кода показывает, как:
- Создать встречу.
- Обновить встречу.
- Удалить/отменить встречу.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C | |
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser()); | |
System::DateTime date = System::DateTime::get_Now(); | |
System::DateTime startTime(date.get_Year(), date.get_Month(), date.get_Day(), date.get_Hour(), 0, 0); | |
System::DateTime endTime = startTime.AddHours(1); | |
System::String timeZone = u"America/New_York"; | |
System::SharedPtr<Appointment> app = System::MakeObject<Appointment>(u"Room 112", startTime, endTime, MailAddress::to_MailAddress(u"organizeraspose-email.test3@domain.com"), MailAddressCollection::to_MailAddressCollection(u"attendee@gmail.com")); | |
app->SetTimeZone(timeZone); | |
app->set_Summary(System::String(u"NETWORKNET-34136") + System::ObjectExt::ToString(System::Guid::NewGuid())); | |
app->set_Description(u"NETWORKNET-34136 Exchange 2007/EWS: Provide support for Add/Update/Delete calendar items"); | |
System::String uid = client->CreateAppointment(app); | |
System::SharedPtr<Appointment> fetchedAppointment1 = client->FetchAppointment(uid); | |
app->set_Location(u"Room 115"); | |
app->set_Summary(System::String(u"New summary for ") + app->get_Summary()); | |
app->set_Description(u"New Description"); | |
client->UpdateAppointment(app); | |
System::ArrayPtr<System::SharedPtr<Appointment>> appointments1 = client->ListAppointments(); | |
System::Console::WriteLine(System::String(u"Total Appointments: ") + appointments1->get_Length()); | |
System::SharedPtr<Appointment> fetchedAppointment2 = client->FetchAppointment(uid); | |
System::Console::WriteLine(System::String(u"Summary: ") + fetchedAppointment2->get_Summary()); | |
System::Console::WriteLine(System::String(u"Location: ") + fetchedAppointment2->get_Location()); | |
System::Console::WriteLine(System::String(u"Description: ") + fetchedAppointment2->get_Description()); | |
client->CancelAppointment(app); | |
System::ArrayPtr<System::SharedPtr<Appointment>> appointments2 = client->ListAppointments(); | |
System::Console::WriteLine(System::String(u"Total Appointments: ") + appointments2->get_Length()); |
Список встреч с поддержкой постраничного отображения
Метод ListAppointments, доступный через API IEWSClient, извлекает полный список встреч с сервера Exchange. Это может занять некоторое время, если на сервере Exchange много встреч. API предоставляет перегруженные методы ListAppointmentsByPage , которые обеспечивают поддержку постраничного отображения для операции. Это можно использовать в различных комбинациях с функцией запросов. Доступны следующие перегруженные методы для списка встреч с сервера Exchange с поддержкой постраничного отображения.
IEWSClient.ListAppointmentsByPage(int itemsPerPage)
.IEWSClient.ListAppointmentsByPage(string folderUri, int itemsPerPage)
.IEWSClient.ListAppointmentsByPage(MailQuery query, int itemsPerPage)
.IEWSClient.ListAppointmentsByPage(string folderUri, MailQuery query, int itemsPerPage)
.IEWSClient.ListAppointmentsByPage(int itemsPerPage, int itemOffset)
.IEWSClient.ListAppointmentsByPage(string folderUri, int itemsPerPage, int itemOffset)
.IEWSClient.ListAppointmentsByPage(MailQuery query, int itemsPerPage, int itemOffset)
.IEWSClient.ListAppointmentsByPage(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-C | |
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser()); | |
try | |
{ | |
System::ArrayPtr<System::SharedPtr<Appointment>> appts = client->ListAppointments(); | |
System::Console::WriteLine(appts->get_Length()); | |
System::DateTime date = System::DateTime::get_Now(); | |
System::DateTime startTime(date.get_Year(), date.get_Month(), date.get_Day(), date.get_Hour(), 0, 0); | |
System::DateTime endTime = startTime.AddHours(1); | |
int32_t appNumber = 10; | |
System::SharedPtr<System::Collections::Generic::Dictionary<System::String, System::SharedPtr<Appointment>>> appointmentsDict = System::MakeObject<System::Collections::Generic::Dictionary<System::String, System::SharedPtr<Appointment>>>(); | |
for (int32_t i = 0; i < appNumber; i++) | |
{ | |
startTime = startTime.AddHours(1); | |
endTime = endTime.AddHours(1); | |
System::String timeZone = u"America/New_York"; | |
System::SharedPtr<Appointment> appointment = System::MakeObject<Appointment>(u"Room 112", startTime, endTime, MailAddress::to_MailAddress(u"from@domain.com"), MailAddressCollection::to_MailAddressCollection(u"to@domain.com")); | |
appointment->SetTimeZone(timeZone); | |
appointment->set_Summary(System::String(u"NETWORKNET-35157_3 - ") + System::ObjectExt::ToString(System::Guid::NewGuid())); | |
appointment->set_Description(u"EMAILNET-35157 Move paging parameters to separate class"); | |
System::String uid = client->CreateAppointment(appointment); | |
appointmentsDict->Add(uid, appointment); | |
} | |
System::SharedPtr<AppointmentCollection> totalAppointmentCol = AppointmentCollection::to_AppointmentCollection(client->ListAppointments()); | |
/// // LISTING APPOINTMENTS WITH PAGING SUPPORT /////// | |
int32_t itemsPerPage = 2; | |
System::SharedPtr<System::Collections::Generic::List<System::SharedPtr<AppointmentPageInfo>>> pages = System::MakeObject<System::Collections::Generic::List<System::SharedPtr<AppointmentPageInfo>>>(); | |
System::SharedPtr<AppointmentPageInfo> pagedAppointmentCol = client->ListAppointmentsByPage(itemsPerPage); | |
System::Console::WriteLine(pagedAppointmentCol->get_Items()->get_Count()); | |
pages->Add(pagedAppointmentCol); | |
while (!pagedAppointmentCol->get_LastPage()) | |
{ | |
pagedAppointmentCol = client->ListAppointmentsByPage(itemsPerPage, pagedAppointmentCol->get_PageOffset() + 1); | |
pages->Add(pagedAppointmentCol); | |
} | |
int32_t retrievedItems = 0; | |
for (auto folderCol : System::IterateOver(pages)) | |
{ | |
retrievedItems += folderCol->get_Items()->get_Count(); | |
} | |
} | |
catch (System::Exception& ex) | |
{ | |
System::Console::WriteLine(ex.get_Message()); | |
} |
Добавление события во вторичную папку календаря на Exchange Server
API Aspose.Email позволяет создать вторичную папку календаря на Exchange Server с использованием IEWSClient. Встречи затем могут быть добавлены, обновлены или отменены из вторичного календаря с использованием методов IEWSClient->CreateAppointment, IEWSClient->UpdateAppointment и IEWSClient->CancelAppointment.
Следующий фрагмент кода показывает, как добавить событие во вторичную папку календаря на сервере exchange.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-C | |
System::SharedPtr<IEWSClient> client = GetExchangeEWSClient(GetExchangeTestUser()); | |
try | |
{ | |
System::DateTime date = System::DateTime::get_Now(); | |
System::DateTime startTime(date.get_Year(), date.get_Month(), date.get_Day(), date.get_Hour(), 0, 0); | |
System::DateTime endTime = startTime.AddHours(1); | |
System::String timeZone = u"America/New_York"; | |
System::ArrayPtr<System::SharedPtr<Appointment>> listAppointments; | |
System::SharedPtr<Appointment> appointment = System::MakeObject<Appointment>(u"Room 121", startTime, endTime, MailAddress::to_MailAddress(u"from@domain.com"), MailAddressCollection::to_MailAddressCollection(u"attendee@domain.com")); | |
appointment->SetTimeZone(timeZone); | |
appointment->set_Summary(System::String(u"EMAILNET-35198 - ") + System::ObjectExt::ToString(System::Guid::NewGuid())); | |
appointment->set_Description(u"EMAILNET-35198 Ability to add event to Secondary Calendar of Office 365"); | |
// Verify that the new folder has been created | |
System::SharedPtr<ExchangeFolderInfoCollection> calendarSubFolders = client->ListSubFolders(client->get_MailboxInfo()->get_CalendarUri()); | |
System::String getfolderName; | |
System::String setFolderName = u"New Calendar"; | |
bool alreadyExits = false; | |
// Verify that the new folder has been created already exits or not | |
for (int32_t i = 0; i < calendarSubFolders->get_Count(); i++) | |
{ | |
getfolderName = calendarSubFolders->idx_get(i)->get_DisplayName(); | |
if (System::ObjectExt::Equals(getfolderName, setFolderName)) | |
{ | |
alreadyExits = true; | |
} | |
} | |
if (alreadyExits) | |
{ | |
System::Console::WriteLine(u"Folder Already Exists"); | |
} | |
else | |
{ | |
// Create new calendar folder | |
client->CreateFolder(client->get_MailboxInfo()->get_CalendarUri(), setFolderName, nullptr, u"IPF.Appointment"); | |
System::Console::WriteLine(calendarSubFolders->get_Count()); | |
// Get the created folder URI | |
System::String newCalendarFolderUri = calendarSubFolders->idx_get(0)->get_Uri(); | |
// appointment api with calendar folder uri | |
// Create | |
client->CreateAppointment(appointment, newCalendarFolderUri); | |
appointment->set_Location(u"Room 122"); | |
// update | |
client->UpdateAppointment(appointment, newCalendarFolderUri); | |
// list | |
listAppointments = client->ListAppointments(newCalendarFolderUri); | |
// list default calendar folder | |
listAppointments = client->ListAppointments(client->get_MailboxInfo()->get_CalendarUri()); | |
// Cancel | |
client->CancelAppointment(appointment, newCalendarFolderUri); | |
listAppointments = client->ListAppointments(newCalendarFolderUri); | |
// appointment api with context current calendar folder uri | |
client->set_CurrentCalendarFolderUri(newCalendarFolderUri); | |
// Create | |
client->CreateAppointment(appointment); | |
appointment->set_Location(u"Room 122"); | |
// update | |
client->UpdateAppointment(appointment); | |
// list | |
listAppointments = client->ListAppointments(); | |
// list default calendar folder | |
listAppointments = client->ListAppointments(client->get_MailboxInfo()->get_CalendarUri()); | |
// Cancel | |
client->CancelAppointment(appointment); | |
listAppointments = client->ListAppointments(); | |
} | |
} | |
catch (System::Exception& ex) | |
{ | |
System::Console::WriteLine(ex.get_Message()); | |
} |
Обмен приглашениями на календарь
Сервер 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-C | |
// delegate calendar access permission | |
System::SharedPtr<ExchangeDelegateUser> delegateUser = System::MakeObject<ExchangeDelegateUser>(u"sharingfrom@domain.com", Aspose::Email::Clients::Exchange::WebService::ExchangeDelegateFolderPermissionLevel::NotSpecified); | |
delegateUser->get_FolderPermissions()->set_CalendarFolderPermissionLevel(Aspose::Email::Clients::Exchange::WebService::ExchangeDelegateFolderPermissionLevel::Reviewer); | |
client->DelegateAccess(delegateUser, u"sharingfrom@domain.com"); | |
// Create invitation | |
System::SharedPtr<MapiMessage> mapiMessage = client->CreateCalendarSharingInvitationMessage(u"sharingfrom@domain.com"); | |
System::SharedPtr<MailConversionOptions> options = System::MakeObject<MailConversionOptions>(); | |
options->set_ConvertAsTnef(true); | |
System::SharedPtr<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-C | |
//Fetch all calendars from Exchange calendar's folder | |
System::ArrayPtr<System::String> uriList = client->ListItems(client->get_MailboxInfo()->get_CalendarUri()); | |
//Define the Extended Attribute Property Descriptor for searching purpose | |
//In this case, we have a K1 Long named property for Calendar item | |
System::SharedPtr<PropertyDescriptor> propertyDescriptor = System::MakeObject<PidNamePropertyDescriptor>(u"K1", Aspose::Email::Mapi::PropertyDataType::Integer32, System::Guid(u"00020329-0000-0000-C000-000000000046")); | |
//Fetch calendars that have the custom property | |
System::SharedPtr<System::Collections::Generic::IList<System::SharedPtr<MapiCalendar>>> mapiCalendarList = client->FetchMapiCalendar(uriList, System::MakeArray<System::SharedPtr<Aspose::Email::Mapi::PropertyDescriptor>>({propertyDescriptor})); | |
for (auto cal : System::IterateOver(mapiCalendarList)) | |
{ | |
for (auto namedProperty : System::IterateOver<MapiNamedProperty>(cal->get_NamedProperties()->get_Values())) | |
{ | |
System::Console::WriteLine(namedProperty->get_NameId() + u" = " + namedProperty->GetInt32()); | |
} | |
} |