Работа с календарями Gmail
Добавление, редактирование и удаление календаря
Aspose.Email позволяет приложениям управлять календарями Gmail с помощью IGmailClient, который предоставляет такие функции, как добавление, удаление и обновление календарей Gmail. Этот класс клиента возвращает список объектов типа ExtendedCalendar, которые содержат информацию о элементах календаря Gmail. Класс IGmailClient предоставляет следующие функции для работы с календарями:
- CreateCalendar Его можно использовать для добавления нового календаря
- ListCalendars Его можно использовать для получения списка всех календарей клиента
- DeleteCalendar Его можно использовать для удаления календаря
- FetchCalendar Его можно использовать для получения конкретного календаря клиента
- UpdateCalendar Эта функция используется для повторного добавления измененного календаря клиента
Для доступа к календарям GoogleTestUser инициализируется с использованием учетных данных gmail. GoogleOAuthHelper используется для получения токена доступа для пользователя, который затем используется для инициализации IGmailClient.
Вставка, получение и обновление
Для добавления календаря инициализируйте объект типа Calendar и вставьте его с помощью функции CreateCalendar(). CreateCalendar() возвращает id новосозданного календаря. Этот id можно использовать для получения календаря с сервера. Следующий фрагмент кода показывает, как вставить, получить и обновить календарь.
// 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); | |
} | |
Удаление конкретного календаря
Для удаления конкретного календаря необходимо получить список всех календарей клиента, а затем удалить по мере необходимости. ListCalendars() возвращает список ExtendedCalendar, который содержит календари Gmail. Следующий фрагмент кода показывает, как удалить конкретный календарь.
// 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); | |
} | |
} |
Работа с управлением доступом к календарю
Aspose.Email обеспечивает полный контроль над доступом к элементам календаря. Функция ListAccessRules() доступна через IGmailClient, которая возвращает список AccessControlRule. Индивидуальная информация о правилах может быть извлечена, изменена и сохранена обратно для календаря клиента. IGmailClient содержит следующие функции для управления правилами доступа.
- ListAccessRules Эта функция предоставляет список AccessControlRule
- CreateAccessRule Эта функция создает новое правило доступа для календаря.
- UpdateAccessRule Эта функция используется для обновления правила доступа.
- FetchAccessRule Его можно использовать для получения конкретного правила доступа для календаря клиента
- DeleteAccessRule Эта функция используется для удаления правила доступа.
Следующий фрагмент кода показывает, как использовать функции для управления правилами доступа:
// 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; | |
} | |
} |
Работа с настройками клиента и цветовой информацией
Aspose.Email поддерживает доступ к настройкам клиента с помощью IGmailClient.GetSettings(). Он возвращает список настроек, указанных ниже:
- dateFieldOrder
- displayAllTimezones
- hideInvitations
- format24HourTime
- defaultCalendarMode
- defaultEventLength
- locale
- remindOnRespondedEventsOnly
- alternateCalendar
- userLocation
- hideWeekends
- showDeclinedEvents
- weekStart
- weather
- customCalendarMode
- timezoneLabel
- timezone
- useKeyboardShortcuts
- country
Аналогично, цветовая информация для клиентов также может быть извлечена с помощью IGmailClient.GetColors(). Этот объект цветовой информации возвращает список цветов переднего плана, цветов фона и даты и времени обновления.
Доступ к настройкам клиента
Следующий фрагмент кода показывает, как можно использовать функции для доступа к настройкам клиента:
// 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"); | |
} | |
} | |
} |
Доступ к цветовой информации
Следующий фрагмент кода показывает, как можно использовать функции для доступа к настройкам цвета клиента.
// 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); | |
} |
Работа с встречами
Aspose.Email предоставляет функции для работы с встречами в календарях Google. Следующий список задач, которые можно выполнить с встречами в календаре Google:
- Добавить встречи.
- Получить список встреч.
- Получить конкретную встречу.
- Обновить встречу.
- Переместить встречу из одного календаря в другой.
- Удалить встречу.
IGmailClient предоставляет функции, такие как CreateAppointment, FetchAppointment, UpdateAppointment, ListAppointments, MoveAppointment и DeleteAppointment.
Добавление встречи
Следующий пример кода демонстрирует функцию добавления встречи в календарь. Для этого выполните следующие шаги:
- Создайте и вставьте календарь.
- Получите список встреч из нового календаря.
- Создайте встречу.
- Вставьте встречу.
// 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); | |
} | |
} |
Получение и обновление встречи
Здесь демонстрируется получение и обновление календаря следующим образом:
- Извлеките конкретную встречу.
- Измените встречу.
- Обновите встречу в календаре.
Предполагается, что календарь с id “calendarId” и уникальный идентификатор встречи “AppointmentUniqueId” уже извлечены. Следующий фрагмент кода показывает, как получить и обновить встречу.
// 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); | |
} |
Перемещение и удаление встречи
Встречу можно переместить, указав исходный календарь, целевой календарь и уникальный идентификатор встречи в исходном календаре. Следующий фрагмент кода показывает, как переместить и удалить встречу.
// 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); | |
} | |