Trabajando con elementos de calendario en Exchange Server

Enviando Solicitudes de Reunión

Este artículo muestra cómo enviar una solicitud de reunión a múltiples destinatarios utilizando Exchange Web Services y Aspose.Email.

  1. Cree una solicitud de reunión utilizando la clase Appointment y establezca la ubicación, la hora y los asistentes.
  2. Cree una instancia de la clase MailMessage y establezca la cita utilizando el método MailMessage->AddAlternateView() .
  3. Conéctese al Exchange Server y envíe la solicitud de reunión utilizando el método IEWSClient->Send(MailMessage) .

La clase EWSClient se puede utilizar para conectarse a servidores de Exchange con soporte para Exchange Web Services (EWS). Para que esto funcione, el servidor debe ser Exchange Server 2007 o posterior. El siguiente fragmento de código muestra cómo utilizar EWS para enviar las solicitudes de reunión.

// 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());
}

Trabajando con elementos de calendario usando EWS

Aspose.Email proporciona la capacidad de agregar, actualizar y cancelar citas utilizando el cliente de Exchange Web Service (EWS). Los métodos IEWSClient->CreateAppointment, IEWSClient->UpdateAppointment y IEWSClient->CancelAppointment permiten manipular elementos de calendario utilizando EWS. Este artículo proporciona un ejemplo de código detallado sobre cómo trabajar con elementos de calendario. El siguiente ejemplo de código muestra cómo:

  1. Crear una cita.
  2. Actualizar una cita.
  3. Eliminar/Cancela una cita.
// 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());

Listando Citas con Soporte de Paginación

El método ListAppointments expuesto por la API IEWSClient recupera la lista completa de citas del servidor de Exchange. Esto puede tomar tiempo si hay un gran número de citas en el servidor de Exchange. La API proporciona métodos sobrecargados del método ListAppointmentsByPage que brinda soporte de paginación a la operación. Esto se puede utilizar en diferentes combinaciones con la función de consulta también. Los siguientes métodos sobrecargados están disponibles para listar citas desde el servidor de Exchange con soporte de paginación.

El siguiente fragmento de código muestra cómo listar citas con soporte de paginación.

// 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());
}

Agregando Evento a la Carpeta de Calendario Secundaria en Exchange Server

La API de Aspose.Email le permite crear una carpeta de calendario secundaria en el servidor de Exchange utilizando el IEWSClient. Las citas pueden ser agregadas, actualizadas o canceladas desde el calendario secundario utilizando los métodos IEWSClient->CreateAppointmentIEWSClient->UpdateAppointment y IEWSClient->CancelAppointment

El siguiente fragmento de código muestra cómo agregar un evento a una carpeta de calendario secundaria en el servidor de 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());
}

Compartiendo Invitaciones de Calendario

El servidor Microsoft Exchange proporciona la capacidad de compartir calendarios enviando invitaciones de calendario a otros usuarios, registrados en el mismo servidor de Exchange. La API de Aspose.Email proporciona la misma capacidad al permitir compartir el calendario utilizando la API de 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);

Recuperando Información de Atributos Extendidos de los Elementos de Calendario

// 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());
}
}