Quản lý Google Calendar bằng Gmail Client

Thêm, Chỉnh sửa và Xóa Lịch Gmail

Aspose.Email cho phép các ứng dụng quản lý các lịch Gmail bằng cách sử dụng IGmailClient cung cấp các tính năng như thêm, xóa và cập nhật lịch Gmail. Lớp client này trả về một danh sách các đối tượng kiểu ExtendedCalendar chứa thông tin về các mục lịch Gmail. IGmailClient lớp cung cấp các hàm sau cho lịch:

  • CreateCalendar Nó có thể được dùng để chèn lịch mới
  • ListCalendars Nó có thể được dùng để lấy danh sách tất cả các lịch của một client
  • DeleteCalendar Nó có thể được dùng để xóa một lịch
  • FetchCalendar Nó có thể được dùng để lấy lịch cụ thể của một khách hàng
  • UpdateCalendar Hàm này được dùng để chèn lại lịch đã chỉnh sửa của một client

Để Truy cập các lịch, GoogleTestUser được khởi tạo bằng thông tin đăng nhập tài khoản gmail. GoogleOAuthHelper được sử dụng để lấy token truy cập cho người dùng, sau đó token này được dùng để khởi tạo IGmailClient.

Chèn, Lấy và Cập nhật Lịch Gmail

Đối với việc chèn một lịch, khởi tạo một đối tượng kiểu Calendar và chèn nó bằng cách sử dụng CreateCalendar() hàm. CreateCalendar() trả về id của lịch mới được chèn. Id này có thể được dùng để lấy lịch từ máy chủ. Đoạn mã sau cho bạn thấy cách chèn, lấy và cập nhật lịch.

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

Xóa Lịch Google Cụ thể

Để xóa một lịch cụ thể, chúng ta cần lấy danh sách tất cả các lịch của một khách hàng và sau đó xóa theo yêu cầu. ListCalendars() trả về danh sách của ExtendedCalendar chứa các lịch Gmail. Đoạn mã sau cho bạn thấy cách xóa một lịch cụ thể.

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

Kiểm soát Truy cập Lịch

Aspose.Email cung cấp quyền kiểm soát đầy đủ đối với việc truy cập các mục lịch. ListAccessRules() hàm được công khai bởi IGmailClient trong đó trả về danh sách của AccessControlRule. Thông tin quy tắc cá nhân có thể được lấy, chỉnh sửa và lưu lại cho lịch của một khách hàng. IGmailClient chứa các hàm sau để quản lý các quy tắc kiểm soát truy cập.

  • ListAccessRules Hàm này cung cấp danh sách AccessControlRule
  • CreateAccessRule Hàm này tạo một quy tắc truy cập mới cho lịch.
  • UpdateAccessRule Hàm này được dùng để cập nhật một quy tắc truy cập.
  • FetchAccessRule Nó có thể được dùng để lấy quy tắc truy cập cụ thể cho lịch của một khách hàng
  • DeleteAccessRule Hàm này được dùng để xóa một quy tắc truy cập.

Đoạn mã dưới đây cho bạn thấy cách sử dụng các hàm để quản lý các quy tắc truy cập:

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

Cài đặt Client Lịch và Thông tin Màu

Aspose.Email hỗ trợ truy cập cài đặt Khách hàng bằng cách sử dụng IGmailClient.GetSettings(). Nó trả về danh sách các thiết lập như dưới đây:

  1. dateFieldOrder
  2. displayAllTimezones
  3. hideInvitations
  4. format24HourTime
  5. defaultCalendarMode
  6. defaultEventLength
  7. locale
  8. remindOnRespondedEventsOnly
  9. alternateCalendar
  10. userLocation
  11. hideWeekends
  12. showDeclinedEvents
  13. weekStart
  14. weather
  15. customCalendarMode
  16. timezoneLabel
  17. timezone
  18. useKeyboardShortcuts
  19. quốc gia

Tương tự, thông tin màu cho khách hàng cũng có thể được lấy bằng cách sử dụng IGmailClient.GetColors(). Đối tượng thông tin màu này trả về danh sách các màu tiền cảnh, màu nền và ngày giờ cập nhật.

Truy cập Cài đặt Khách hàng

Đoạn mã dưới đây cho bạn thấy cách các hàm có thể được sử dụng để truy cập các thiết lập của client:

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

Truy cập Thông tin Màu

Đoạn mã dưới đây cho bạn thấy cách các hàm có thể được sử dụng để truy cập các cài đặt màu của client.

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

Quản lý Cuộc hẹn Lịch Google

Aspose.Email cung cấp các tính năng để làm việc với Cuộc hẹn trong lịch Google. Các tác vụ sau có thể được thực hiện trên các cuộc hẹn trong lịch Google:

  1. Thêm các cuộc hẹn.
  2. Lấy danh sách các cuộc hẹn.
  3. Lấy thông tin cuộc hẹn cụ thể.
  4. Cập nhật một cuộc hẹn.
  5. Di chuyển cuộc hẹn từ lịch này sang lịch khác.
  6. Xóa cuộc hẹn.

IGmailClient cung cấp các hàm như CreateAppointment, FetchAppointment, UpdateAppointment, ListAppointments, MoveAppointmentDeleteAppointment.

Thêm Cuộc hẹn vào Google Calendar

Mẫu mã dưới đây minh họa tính năng thêm một cuộc hẹn vào lịch. Để thực hiện, làm theo các bước:

  1. Tạo và chèn một lịch.
  2. Lấy danh sách các cuộc hẹn từ một lịch mới.
  3. Tạo một cuộc hẹn.
  4. Chèn một cuộc hẹn.

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

Lấy và Cập nhật Cuộc hẹn Lịch Google

Ở đây việc lấy và cập nhật lịch được minh họa như sau:

  1. Lấy cuộc hẹn cụ thể.
  2. Sửa đổi cuộc hẹn.
  3. Cập nhật cuộc hẹn trong lịch.

Giả sử rằng một lịch có id "calendarId" và một cuộc hẹn có id duy nhất "AppointmentUniqueId" đã được trích xuất. Đoạn mã sau cho bạn thấy cách lấy và cập nhật một cuộc hẹn.

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

Di chuyển và Xóa Cuộc hẹn trong Lịch Google

Cuộc hẹn có thể được di chuyển bằng cách cung cấp lịch nguồn, lịch đích và id duy nhất của cuộc hẹn trong lịch nguồn. Đoạn mã sau cho bạn thấy cách di chuyển và xóa một cuộc hẹn.

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

Truy vấn FreeBusy cho Lịch Google

Aspose.Email cung cấp cơ chế truy vấn để kiểm tra xem một cuộc hẹn có đến hạn hay không theo tiêu chí. Lớp FreebusyQuery được cung cấp cho mục đích này, cho phép chuẩn bị một truy vấn cho một lịch cụ thể.

Ví dụ mã này trình bày tính năng truy vấn lịch. Các tác vụ sau được thực hiện trong mẫu này:

  1. Tạo và chèn một lịch
  2. Tạo một cuộc hẹn
  3. Chèn cuộc hẹn
  4. Chuẩn bị một FreeBusyQuery
  5. Lấy FreebusyResponse

// Use the GoogleUser and GoogleOAuthHelper classes below to receive an access token
using (IGmailClient client = GmailClient.GetInstance(accessToken, user.Email))
{
    // Initialize calendar item
    Aspose.Email.Clients.Google.Calendar calendar1 = new Aspose.Email.Clients.Google.Calendar("summary - " + Guid.NewGuid().ToString(), null, null, "Europe/Kiev");

    // Insert calendar and get back id of newly inserted calendar and Fetch the same calendar using calendar id
    string id = client.CreateCalendar(calendar1);
    Aspose.Email.Clients.Google.Calendar cal1 = client.FetchCalendar(id);
    string calendarId1 = cal1.Id;
    try
    {
        // Get list of appointments in newly inserted calendar. It should be zero
        Appointment[] appointments = client.ListAppointments(calendarId1);
        if (appointments.Length != 0)
        {
            Console.WriteLine("Wrong number of appointments");
            return;
        }

        // Create a new appointment and Calculate appointment start and finish time
        DateTime startDate = DateTime.Now;
        DateTime endDate = startDate.AddHours(1);

        // Create attendees list for appointment
        MailAddressCollection attendees = new MailAddressCollection();
        attendees.Add("user1@domain.com");
        attendees.Add("user2@domain.com");

        // Create appointment
        Appointment app1 = new Appointment("Location - " + Guid.NewGuid().ToString(), startDate, endDate, "user2@domain.com", attendees);
        app1.Summary = "Summary - " + Guid.NewGuid().ToString();
        app1.Description = "Description - " + Guid.NewGuid().ToString();
        app1.StartTimeZone = "Europe/Kiev";
        app1.EndTimeZone = "Europe/Kiev";

        // Insert the newly created appointment and get back the same in case of successful insertion
        Appointment app2 = client.CreateAppointment(calendarId1, app1);

        // Create Freebusy query by setting min/max timeand time zone
        FreebusyQuery query = new FreebusyQuery();
        query.TimeMin = DateTime.Now.AddDays(-1);
        query.TimeMax = DateTime.Now.AddDays(1);
        query.TimeZone = "Europe/Kiev";

        // Set calendar item to search and Get the reponse of query containing 
        query.Items.Add(cal1.Id);
        FreebusyResponse resp = client.GetFreebusyInfo(query);
        // Delete the appointment
        client.DeleteAppointment(calendarId1, app2.UniqueId);
    }
    finally
    {
        // Delete the calendar
        client.DeleteCalendar(cal1.Id);
    }
}