从Google日历中删除活动

时间:2017-01-31 04:57:12

标签: c# google-api google-calendar-api google-oauth google-api-dotnet-client

我想使用他的电子邮件ID删除用户Google日历的活动 我尝试了以下代码来删除事件。

CalendarService service = new CalendarService();
                            string calendarId = "primary";
                            service.Events.Delete(calendarId, eventId).Execute();

但它给了我以下异常

Google.Apis.Requests.RequestError
Login Required [401]
Errors [
    Message[Login Required] Location[Authorization - header] Reason[required] Domain[global]
]

我如何实现这一点并避免例外?

1 个答案:

答案 0 :(得分:1)

您无法创建一个需要首先进行身份验证的空日历服务对象。

var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Calendar Oauth2 Authentication Sample"
            });

您必须使用Oauth2创建凭据才能访问用户日历。

 /// <summary>
    /// This method requests Authentcation from a user using Oauth2.  
    /// Credentials are stored in System.Environment.SpecialFolder.Personal
    /// Documentation https://developers.google.com/accounts/docs/OAuth2
    /// </summary>
    /// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
    /// <param name="userName">Identifying string for the user who is being authentcated.</param>
    /// <returns>DriveService used to make requests against the Drive API</returns>
    public static CalendarService AuthenticateOauth(string clientSecretJson, string userName)
    {
        try
        {
            if (string.IsNullOrEmpty(userName))
                throw new ArgumentNullException("userName");
            if (string.IsNullOrEmpty(clientSecretJson))
                throw new ArgumentNullException("clientSecretJson");
            if (!File.Exists(clientSecretJson))
                throw new Exception("clientSecretJson file does not exist.");

            // These are the scopes of permissions you need. It is best to request only what you need and not all of them
            string[] scopes = new string[] { CalendarService.Scope.CalendarReadonly,    //View your calendars
                                             CalendarService.Scope.Calendar};           //Manage your calendars
            UserCredential credential;
            using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

                // Requesting Authentication or loading previously stored authentication for userName
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                         scopes,
                                                                         userName,
                                                                         CancellationToken.None,
                                                                         new FileDataStore(credPath, true)).Result;
            }

            // Create Drive API service.
            return new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "Calendar Oauth2 Authentication Sample"
            });
        }
        catch (Exception ex)
        {
            Console.WriteLine("Create Oauth2 account CalendarService failed" + ex.Message);
            throw new Exception("CreateServiceAccountCalendarFailed", ex);
        }
    }

github上从我的Google Calendar API示例项目中删除了代码,如果您需要,可以提供更多代码。