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 usando Exchange Web Services y Aspose.Email.
- Crea una solicitud de reunión utilizando la clase Appointment y establece la ubicación, la hora y los asistentes.
- Crea una instancia de la clase MailMessage y establece la cita usando el método MailMessage.AddAlternateView().
- Conéctate al Exchange Server y envía la solicitud de reunión usando el método Send(MailMessage) .
La clase EWSClient se puede utilizar para conectarse a un Exchange Server 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 te muestra cómo utilizar EWS para enviar solicitudes de reunión.
// 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); | |
} |
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, UpdateAppointment, y CancelAppointment permiten manipular elementos de calendario usando 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:
- Crear una cita.
- Actualizar una cita.
- Eliminar/Cancela una cita.
// 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); |
Listando Citas con Soporte de Paginación
El método ListAppointments expuesto por la API IEWSClient recupera la lista completa de citas del servidor Exchange. Esto puede tomar tiempo si hay un gran número de citas en el Exchange Server. La API proporciona métodos sobrecargados del método ListAppointments que otorgan soporte de paginación a la operación. Esto se puede usar en diferentes combinaciones con la característica de consulta también. Los siguientes métodos sobrecargados están disponibles para listar citas desde el Exchange Server con soporte de paginación.
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)
.
El siguiente fragmento de código te 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-.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 | |
{ | |
} | |
} |
Agregando Evento a la Carpeta de Calendario Secundario en Exchange Server
La API Aspose.Email te permite crear una carpeta de Calendario secundaria en Exchange Server usando el IEWSClient. Las citas pueden ser agregadas, actualizadas o canceladas desde el calendario secundario usando los métodos CreateAppointment, UpdateAppointment y CancelAppointment. Los siguientes métodos y propiedades de la API se utilizan en los ejemplos de código a continuación para mostrar la funcionalidad de esta característica. Ten en cuenta que esta característica es compatible con Aspose.Email para .NET 6.5.0 en adelante.
- Método
IEWSClient.CancelAppointment(Appointment, String)
. - Método
IEWSClient.CancelAppointment(String, String)
. - Método
IEWSClient.CreateAppointment(Appointment, String)
. - Método
IEWSClient.CreateFolder(String, String, ExchangeFolderPermissionCollection, String)
. - Método
IEWSClient.FetchAppointment(String, String)
. - Método
IEWSClient.UpdateAppointment(Appointment, String)
. - Propiedad
IEWSClient.CurrentCalendarFolderUri
.
El siguiente fragmento de código te muestra cómo agregar un evento a la carpeta de calendario secundaria en el servidor de intercambio.
// 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 | |
{ | |
} | |
} |
Compartiendo Invitación 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 Aspose.Email proporciona la misma capacidad permitiendo compartir el calendario mediante la 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); | |
} |
Recuperando Información de Atributos Extendidos de Elementos de Calendario
// 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()); | |
} | |
} |
Devolviendo los Elementos de Calendario Recurrentes Dentro del Rango de Fechas Especificado
EWSClient admite el retorno de los elementos de calendario recurrentes dentro del rango especificado por StartDate y EndDate. El método AppointmentQueryBuilder.SetCalendarView se utiliza para definir un rango de fechas específico y limitar el número de citas devueltas para recuperar información relevante. Al establecer los siguientes parámetros, puedes recuperar las citas que coinciden con los criterios especificados.
-
startDate: La fecha de inicio de la vista del calendario. Las citas que comienzan a partir de esta fecha se incluirán en el resultado de la consulta.
-
endDate: La fecha de finalización de la vista del calendario. Las citas que terminan antes o en esta fecha se incluirán en el resultado de la consulta.
-
maxEntriesReturned: El número máximo de citas que se devolverán en el resultado de la consulta. El valor de -1 indica que no hay un límite específico.
ExchangeQueryBuilder builder = new ExchangeQueryBuilder();
builder.Appointment.SetCalendarView(DateTime.Now, DateTime.Now.AddMonths(1), -1);
Appointment[] appointments = client.ListAppointments(builder.GetQuery());