Trabalhando com Calendários do Gmail
Adicionar, Editar e Excluir um Calendário
Aspose.Email permite que aplicativos gerenciem os calendários do Gmail usando IGmailClient, que fornece recursos como adicionar, excluir e atualizar calendários do Gmail. Esta classe cliente retorna uma lista de objetos do tipo ExtendedCalendar, que contêm informações sobre os itens do calendário do Gmail. A classe IGmailClient expõe as seguintes funções para calendários:
- CreateCalendar Pode ser usada para inserir um novo calendário
- ListCalendars Pode ser usada para obter a lista de todos os calendários de um cliente
- DeleteCalendar Pode ser usada para excluir um calendário
- FetchCalendar Pode ser usada para buscar um calendário específico de um cliente
- UpdateCalendar Esta função é usada para reinserir um calendário modificado de um cliente
Para acessar os calendários, GoogleTestUser é inicializado usando as credenciais da conta gmail. GoogleOAuthHelper é usado para obter o token de acesso para o usuário, que é posteriormente utilizado para inicializar o IGmailClient.
Inserir, Buscar e Atualizar
Para inserir um calendário, inicialize um objeto do tipo Calendar e insira-o usando a função CreateCalendar(). A função CreateCalendar() retorna o id do calendário recém-inserido. Este id pode ser usado para buscar o calendário do servidor. O seguinte trecho de código mostra como inserir, buscar e atualizar um calendário.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// Get access token | |
GoogleTestUser User2 = new GoogleTestUser("user", "email address", "password", "clientId", "client secret"); | |
string accessToken; | |
string refreshToken; | |
GoogleOAuthHelper.GetAccessToken(User2, out accessToken, out refreshToken); | |
using (IGmailClient client = GmailClient.GetInstance(accessToken, User2.EMail)) | |
{ | |
// Insert, get and update calendar | |
Aspose.Email.Clients.Google.Calendar calendar = new Aspose.Email.Clients.Google.Calendar("summary - " + Guid.NewGuid().ToString(), null, null, "America/Los_Angeles"); | |
// Insert calendar and Retrieve same calendar using id | |
string id = client.CreateCalendar(calendar); | |
Aspose.Email.Clients.Google.Calendar cal = client.FetchCalendar(id); | |
//Match the retrieved calendar info with local calendar | |
if ((calendar.Summary == cal.Summary) && (calendar.TimeZone == cal.TimeZone)) | |
{ | |
Console.WriteLine("fetched calendar information matches"); | |
} | |
else | |
{ | |
Console.WriteLine("fetched calendar information does not match"); | |
} | |
// Change information in the fetched calendar and Update calendar | |
cal.Description = "Description - " + Guid.NewGuid().ToString(); | |
cal.Location = "Location - " + Guid.NewGuid().ToString(); | |
client.UpdateCalendar(cal); | |
} | |
Excluir calendário específico
Para excluir um calendário específico, precisamos obter a lista de todos os calendários de um cliente e, em seguida, excluir conforme necessário. A função ListCalendars() retorna a lista de ExtendedCalendar que contém os calendários do Gmail. O seguinte trecho de código mostra como excluir um calendário específico.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
// Get access token | |
GoogleTestUser User2 = new GoogleTestUser("user", "email address", "password", "clientId", "client secret"); | |
string accessToken; | |
string refreshToken; | |
GoogleOAuthHelper.GetAccessToken(User2, out accessToken, out refreshToken); | |
using (IGmailClient client = GmailClient.GetInstance(accessToken, User2.EMail)) | |
{ | |
// Access and delete calendar with summary starting from "Calendar summary - " | |
string summary = "Calendar summary - "; | |
// Get calendars list | |
ExtendedCalendar[] lst0 = client.ListCalendars(); | |
foreach (ExtendedCalendar extCal in lst0) | |
{ | |
// Delete selected calendars | |
if (extCal.Summary.StartsWith(summary)) | |
client.DeleteCalendar(extCal.Id); | |
} | |
} |
Trabalhando com Controle de Acesso ao Calendário
Aspose.Email fornece controle total sobre o acesso aos itens do calendário. A função ListAccessRules() é exposta pelo IGmailClient e retorna a lista de AccessControlRule. Informações sobre regras individuais podem ser recuperadas, modificadas e salvas novamente para o calendário de um cliente. O IGmailClient contém as seguintes funções para gerenciar as regras de controle de acesso.
- ListAccessRules Esta função fornece a lista de AccessControlRule
- CreateAccessRule Esta função cria uma nova regra de acesso para um calendário.
- UpdateAccessRule Esta função é usada para atualizar uma regra de acesso.
- FetchAccessRule Pode ser usada para buscar uma regra de acesso específica para o calendário de um cliente
- DeleteAccessRule Esta função é usada para excluir uma regra de acesso.
O seguinte trecho de código mostra como usar funções para gerenciar as regras de acesso:
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
GoogleTestUser User2 = new GoogleTestUser("user", "email address", "password", "clientId", "client secret"); | |
string accessToken; | |
string refreshToken; | |
GoogleOAuthHelper.GetAccessToken(User2, out accessToken, out refreshToken); | |
using (IGmailClient client = GmailClient.GetInstance(accessToken, User2.EMail)) | |
{ | |
// Retrieve list of calendars for the current client | |
ExtendedCalendar[] calendarList = client.ListCalendars(); | |
// Get first calendar id and retrieve list of AccessControlRule for the first calendar | |
string calendarId = calendarList[0].Id; | |
AccessControlRule[] roles1 = client.ListAccessRules(calendarId); | |
// Create a local access control rule and Set rule properties | |
AccessControlRule rule = new AccessControlRule(); | |
rule.Role = AccessRole.reader; | |
rule.Scope = new AclScope(AclScopeType.user, User2.EMail); | |
// Insert new rule for the calendar. It returns the newly created rule | |
AccessControlRule createdRule = client.CreateAccessRule(calendarId, rule); | |
// Confirm if local created rule and returned rule are equal | |
if ((rule.Role == createdRule.Role) && (rule.Scope.Type == createdRule.Scope.Type) && (rule.Scope.Value.ToLower() == createdRule.Scope.Value.ToLower())) | |
{ | |
Console.WriteLine("local rule and returned rule after creation are equal"); | |
} | |
else | |
{ | |
Console.WriteLine("Rule could not be created successfully"); | |
return; | |
} | |
// Get list of rules | |
AccessControlRule[] roles2 = client.ListAccessRules(calendarId); | |
// Current list length should be 1 more than the earlier one | |
if (roles1.Length + 1 == roles2.Length) | |
{ | |
Console.WriteLine("List lengths are ok"); | |
} | |
else | |
{ | |
Console.WriteLine("List lengths are not ok"); | |
return; | |
} | |
// Change rule and Update the rule for the selected calendar | |
createdRule.Role = AccessRole.writer; | |
AccessControlRule updatedRule = client.UpdateAccessRule(calendarId, createdRule); | |
// Check if returned access control rule after update is ok | |
if ((createdRule.Role == updatedRule.Role) && (createdRule.Id == updatedRule.Id)) | |
{ | |
Console.WriteLine("Rule is updated successfully"); | |
} | |
else | |
{ | |
Console.WriteLine("Rule is not updated"); | |
return; | |
} | |
// Retrieve individaul rule against a calendar | |
AccessControlRule fetchedRule = client.FetchAccessRule(calendarId, createdRule.Id); | |
//Check if rule parameters are ok | |
if ((updatedRule.Id == fetchedRule.Id) && (updatedRule.Role == fetchedRule.Role) && (updatedRule.Scope.Type == fetchedRule.Scope.Type) && (updatedRule.Scope.Value.ToLower() == fetchedRule.Scope.Value.ToLower())) | |
{ | |
Console.WriteLine("Rule parameters are ok"); | |
} | |
else | |
{ | |
Console.WriteLine("Rule parameters are not ok"); | |
} | |
// Delete particular rule against a given calendar and Retrieve the all rules list for the same calendar | |
client.DeleteAccessRule(calendarId, createdRule.Id); | |
AccessControlRule[] roles3 = client.ListAccessRules(calendarId); | |
// Check that current rules list length should be equal to the original list length before adding and deleting the rule | |
if (roles1.Length == roles3.Length) | |
{ | |
Console.WriteLine("List lengths are same"); | |
} | |
else | |
{ | |
Console.WriteLine("List lengths are not equal"); | |
return; | |
} | |
} |
Trabalhando com Configurações do Cliente e Informações de Cor
Aspose.Email suporta o acesso às configurações do Cliente usando IGmailClient.GetSettings(). Ele retorna a lista de configurações conforme listado abaixo:
- dateFieldOrder
- displayAllTimezones
- hideInvitations
- format24HourTime
- defaultCalendarMode
- defaultEventLength
- locale
- remindOnRespondedEventsOnly
- alternateCalendar
- userLocation
- hideWeekends
- showDeclinedEvents
- weekStart
- weather
- customCalendarMode
- timezoneLabel
- timezone
- useKeyboardShortcuts
- country
Da mesma forma, informações de cor para clientes também podem ser recuperadas usando IGmailClient.GetColors(). Este objeto de informações de cor retorna a lista de cores de primeiro plano, cores de fundo e data e hora da atualização.
Acessar configurações do cliente
O seguinte trecho de código mostra como as funções podem ser usadas para acessar as configurações do cliente:
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
GoogleTestUser User2 = new GoogleTestUser("user", "email address", "password", "clientId", "client secret"); | |
string accessToken; | |
string refreshToken; | |
GoogleOAuthHelper.GetAccessToken(User2, out accessToken, out refreshToken); | |
using (IGmailClient client = GmailClient.GetInstance(accessToken, User2.EMail)) | |
{ | |
// Retrieve client settings | |
Dictionary<string, string> settings = client.GetSettings(); | |
if (settings.Count < 1) | |
{ | |
Console.WriteLine("No settings are available."); | |
return; | |
} | |
// Traverse the settings list | |
foreach (KeyValuePair<string, string> pair in settings) | |
{ | |
// Get the setting value and test if settings are ok | |
string value = client.GetSetting(pair.Key); | |
if (pair.Value == value) | |
{ | |
Console.WriteLine("Key = " + pair.Key + ", Value = " + pair.Value); | |
} | |
else | |
{ | |
Console.WriteLine("Settings could not be retrieved"); | |
} | |
} | |
} |
Acessar informações de cor
O seguinte trecho de código mostra como as funções podem ser usadas para acessar as configurações de cor do cliente.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
GoogleTestUser User2 = new GoogleTestUser("user", "email address", "password", "clientId", "client secret"); | |
string accessToken; | |
string refreshToken; | |
GoogleOAuthHelper.GetAccessToken(User2, out accessToken, out refreshToken); | |
using (IGmailClient client = GmailClient.GetInstance(accessToken, User2.EMail)) | |
{ | |
ColorsInfo colors = client.GetColors(); | |
Dictionary<string, Colors> palettes = colors.Calendar; | |
// Traverse the settings list | |
foreach (KeyValuePair<string, Colors> pair in palettes) | |
{ | |
Console.WriteLine("Key = " + pair.Key + ", Color = " + pair.Value); | |
} | |
Console.WriteLine("Update Date = " + colors.Updated); | |
} |
Trabalhando com Compromissos
Aspose.Email fornece recursos para trabalhar com compromissos em calendários do Google. A seguir está a lista de tarefas que podem ser realizadas em compromissos no calendário do Google:
- Adicionar Compromissos.
- Recuperar lista de compromissos.
- Recuperar compromisso específico.
- Atualizar um compromisso.
- Mover compromisso de um calendário para outro.
- Excluir compromisso.
IGmailClient fornece funções como CreateAppointment, FetchAppointment, UpdateAppointment, ListAppointments, MoveAppointment e DeleteAppointment.
Adicionando um compromisso
O seguinte exemplo de código demonstra o recurso de adicionar um compromisso em um calendário. Para conseguir isso, siga os passos:
- Criar e inserir um calendário.
- Recuperar a lista de compromissos de um novo calendário.
- Criar um compromisso.
- Inserir um compromisso.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
GoogleTestUser User2 = new GoogleTestUser("user", "email address", "password", "clientId", "client secret"); | |
string accessToken; | |
string refreshToken; | |
GoogleOAuthHelper.GetAccessToken(User2, out accessToken, out refreshToken); | |
// Get IGmailclient | |
using (IGmailClient client = GmailClient.GetInstance(accessToken, User2.EMail)) | |
{ | |
// Create local calendar | |
Aspose.Email.Clients.Google.Calendar calendar1 = new Aspose.Email.Clients.Google.Calendar("summary - " + Guid.NewGuid().ToString(), null, null, "Europe/Kiev"); | |
// Insert calendar and get id of inserted calendar and Get back calendar using an id | |
string id = client.CreateCalendar(calendar1); | |
Aspose.Email.Clients.Google.Calendar cal1 = client.FetchCalendar(id); | |
string calendarId1 = cal1.Id; | |
try | |
{ | |
// Retrieve list of appointments from the first calendar | |
Appointment[] appointments = client.ListAppointments(calendarId1); | |
if (appointments.Length > 0) | |
{ | |
Console.WriteLine("Wrong number of appointments"); | |
return; | |
} | |
// Get current time and Calculate time after an hour from now | |
DateTime startDate = DateTime.Now; | |
DateTime endDate = startDate.AddHours(1); | |
// Initialize a mail address collection and set attendees mail address | |
MailAddressCollection attendees = new MailAddressCollection(); | |
attendees.Add("User1.EMail@domain.com"); | |
attendees.Add("User3.EMail@domain.com"); | |
// Create an appointment with above attendees | |
Appointment app1 = new Appointment("Location - " + Guid.NewGuid().ToString(), startDate, endDate, User2.EMail, attendees); | |
// Set appointment summary, description, start/end time zone | |
app1.Summary = "Summary - " + Guid.NewGuid().ToString(); | |
app1.Description = "Description - " + Guid.NewGuid().ToString(); | |
app1.StartTimeZone = "Europe/Kiev"; | |
app1.EndTimeZone = "Europe/Kiev"; | |
// Insert appointment in the first calendar inserted above and get back inserted appointment | |
Appointment app2 = client.CreateAppointment(calendarId1, app1); | |
// Retrieve appointment using unique id | |
Appointment app3 = client.FetchAppointment(calendarId1, app2.UniqueId); | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine(ex.Message); | |
} | |
} |
Recuperar e atualizar um compromisso
Aqui a recuperação e atualização de um calendário são demonstradas da seguinte forma:
- Recuperar compromisso específico.
- Modificar o compromisso.
- Atualizar o compromisso no calendário.
Assume-se que um calendário com id “calendarId” e id único de compromisso “AppointmentUniqueId” já foram extraídos. O seguinte trecho de código mostra como recuperar e atualizar um compromisso.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
GoogleTestUser User2 = new GoogleTestUser("user", "email address", "password", "clientId", "client secret"); | |
string accessToken; | |
string refreshToken; | |
GoogleOAuthHelper.GetAccessToken(User2, out accessToken, out refreshToken); | |
// Get IGmailclient | |
using (IGmailClient client = GmailClient.GetInstance(accessToken, User2.EMail)) | |
{ | |
string calendarId = client.ListCalendars()[0].Id; | |
string AppointmentUniqueId = client.ListAppointments(calendarId)[0].UniqueId; | |
// Retrieve Appointment | |
Appointment app3 = client.FetchAppointment(calendarId, AppointmentUniqueId); | |
// Change the appointment information | |
app3.Summary = "New Summary - " + Guid.NewGuid().ToString(); | |
app3.Description = "New Description - " + Guid.NewGuid().ToString(); | |
app3.Location = "New Location - " + Guid.NewGuid().ToString(); | |
app3.Flags = AppointmentFlags.AllDayEvent; | |
app3.StartDate = DateTime.Now.AddHours(2); | |
app3.EndDate = app3.StartDate.AddHours(1); | |
app3.StartTimeZone = "Europe/Kiev"; | |
app3.EndTimeZone = "Europe/Kiev"; | |
// Update the appointment and get back updated appointment | |
Appointment app4 = client.UpdateAppointment(calendarId, app3); | |
} |
Mover e Excluir um compromisso
Um compromisso pode ser movido fornecendo o calendário de origem, o calendário de destino e o id único de um compromisso no calendário de origem. O seguinte trecho de código mostra como mover e excluir um compromisso.
// For complete examples and data files, please go to https://github.com/aspose-email/Aspose.Email-for-.NET | |
GoogleTestUser User2 = new GoogleTestUser("user", "email address", "password", "clientId", "client secret"); | |
string accessToken; | |
string refreshToken; | |
GoogleOAuthHelper.GetAccessToken(User2, out accessToken, out refreshToken); | |
// Get IGmailclient | |
using (IGmailClient client = Aspose.Email.Clients.Google.GmailClient.GetInstance(accessToken, User2.EMail)) | |
{ | |
string SourceCalendarId = client.ListCalendars()[0].Id; | |
string DestinationCalendarId = client.ListCalendars()[1].Id; | |
string TargetAppUniqueId = client.ListAppointments(SourceCalendarId)[0].UniqueId; | |
// Retrieve the list of appointments in the destination calendar before moving the appointment | |
Appointment[] appointments = client.ListAppointments(DestinationCalendarId); | |
Console.WriteLine("Before moving count = " + appointments.Length); | |
Appointment Movedapp = client.MoveAppointment(SourceCalendarId, DestinationCalendarId, TargetAppUniqueId); | |
// Retrieve the list of appointments in the destination calendar after moving the appointment | |
appointments = client.ListAppointments(DestinationCalendarId); | |
Console.WriteLine("After moving count = " + appointments.Length); | |
// Delete particular appointment from a calendar using unique id | |
client.DeleteAppointment(DestinationCalendarId, Movedapp.UniqueId); | |
// Retrieve the list of appointments. It should be one less than the earlier appointments in the destination calendar | |
appointments = client.ListAppointments(DestinationCalendarId); | |
Console.WriteLine("After deleting count = " + appointments.Length); | |
} | |