Trabalhando com Itens de Calendário no Exchange Server

Enviando Solicitações de Reunião

Este artigo mostra como enviar uma solicitação de reunião para vários destinatários usando Exchange Web Services e Aspose.Email.

  1. Crie uma solicitação de reunião usando a classe Appointment e defina a localização, horário e participantes.
  2. Crie uma instância da classe MailMessage e defina a nomeação usando o método MailMessage.AddAlternateView().
  3. Conecte-se ao Exchange Server e envie a solicitação de reunião usando o método Send(MailMessage).

A classe EWSClient pode ser usada para conectar-se a um Exchange Server com suporte a Exchange Web Services (EWS). Para que isso funcione, o servidor deve ser o Exchange Server 2007 ou posterior. O seguinte trecho de código mostra como usar EWS para enviar solicitações de reunião.

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

Trabalhando com Itens de Calendário usando EWS

Aspose.Email fornece a capacidade de adicionar, atualizar e cancelar compromissos usando o cliente Exchange Web Service (EWS). Os métodos IEWSClient CreateAppointment, UpdateAppointment e CancelAppointment permitem manipular itens de calendário usando EWS. Este artigo fornece um exemplo de código detalhado sobre como trabalhar com itens de calendário. O seguinte exemplo de código mostra como:

  1. Criar um compromisso.
  2. Atualizar um compromisso.
  3. Excluir/Cancelar um compromisso.
// 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 Compromissos com Suporte a Paginação

O método ListAppointments exposto pela API IEWSClient recupera a lista completa de compromissos do servidor Exchange. Isso pode demorar se houver um grande número de compromissos no Exchange Server. A API fornece métodos sobrecarregados do método ListAppointments que dão suporte à paginação da operação. Isso pode ser usado em diferentes combinações com o recurso de consulta também. Os seguintes métodos sobrecarregados estão disponíveis para listar compromissos do Exchange Server com suporte a paginação.

  • 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).

O seguinte trecho de código mostra como listar compromissos com suporte a paginação.

// 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
{
}
}

Adicionando Evento à Pasta de Calendário Secundária no Exchange Server

A API Aspose.Email permite criar uma pasta de Calendário secundária no Exchange Server usando o IEWSClient. Em seguida, os compromissos podem ser adicionados, atualizados ou cancelados a partir do calendário secundário usando os métodos CreateAppointment, UpdateAppointment e CancelAppointment. Os seguintes métodos e propriedades da API são usados nos exemplos de código abaixo para mostrar a funcionalidade desse recurso. Observe que esse recurso é suportado pelo Aspose.Email para .NET 6.5.0 ou posterior.

  • 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).
  • Propriedade IEWSClient.CurrentCalendarFolderUri.

O seguinte trecho de código mostra como adicionar um evento à pasta de calendário secundária no servidor Exchange.

// 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
{
}
}

Compartilhando Convite de Calendário

O servidor Microsoft Exchange fornece a capacidade de compartilhar calendários enviando convites de calendário para outros usuários, registrados no mesmo servidor Exchange. A API Aspose.Email fornece a mesma capacidade, permitindo compartilhar o calendário usando a 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 Informações de Atributos Estendidos de Itens de Calendário

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

Retornando os Itens de Calendário Recorrentes Dentro do Intervalo de Datas Especificado

O EWSClient suporta o retorno dos itens de calendário recorrentes dentro do intervalo especificado por StartDate e EndDate. O método AppointmentQueryBuilder.SetCalendarView é usado para definir um intervalo de datas específico e limitar o número de compromissos retornados para recuperar informações relevantes. Ao definir os seguintes parâmetros, você pode recuperar os compromissos correspondentes aos critérios especificados.

  • startDate: A data de início da visualização do calendário. Compromissos iniciando a partir desta data serão incluídos no resultado da consulta.

  • endDate: A data de término da visualização do calendário. Compromissos terminando antes ou nesta data serão incluídos no resultado da consulta.

  • maxEntriesReturned: O número máximo de compromissos a serem retornados no resultado da consulta. O valor de -1 indica que não há limite específico.

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

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