2014-01-15 64 views
1

對Google日曆進行身份驗證,搜索和添加事件/樣例正如預期的那樣工作,但在400錯誤請求錯誤中刪除結果。爲什麼刪除Google日曆條目/事件時entry.delete()爲400?

該代碼主要是從google's documentation複製。

低於googleUri是應該刪除的日曆項(由相同的應用程序/用戶創建,標題爲「要刪除的事件」)的鏈接,並且ConfigurationManager.AppSettings包含認證信息。

調試輸出顯示找到日曆條目,但刪除不成功。

這使用谷歌日曆API v2應該仍然運作,直到10/2014。移動到V3會很好,但據我所知,沒有辦法使用已知的用戶名+密碼進行身份驗證(而是使用需要手動輸入Google憑據(?)的過期令牌)。

Debug.Write ("want to remove: " + googleURI); 

// autheticate and get service 
CalendarService svc = new CalendarService(ConfigurationManager.AppSettings["GoogleCalendarName"]); 
svc.setUserCredentials(ConfigurationManager.AppSettings["GoogleCalendarUsername"], ConfigurationManager.AppSettings["GoogleCalendarPassword"]); 
svc.QueryClientLoginToken(); 

// find the event(s) -- should only be one that can match the googleuri 
EventQuery evtquery = new EventQuery(ConfigurationManager.AppSettings["GoogleCalendarPostURI"]); 
evtquery.Uri = new Uri(googleURI); 
EventFeed evtfeed = svc.Query (evtquery); 

//should only be one event in the query 
if (evtfeed == null || evtfeed.Entries.Count != 1) { 
Debug.Write ("No match or too many matches for " + googleURI); // if this is less than 1, we should panic 
    return; 
} 

// we found the right one 
EventEntry entry = (EventEntry)(evtfeed.Entries[0]); 
Debug.Write ("Title: " + entry.Title.Text); 

//hangs here until "The remote server returned an error: (400) Bad Request. 
entry.Delete(); 

輸出是:

[0:] want to remove: https://www.google.com/calendar/feeds/default/private/full/77e0tr0e3b4ctlirug30igeop0 
[0:] Title: Event To Delete 

我還使用批處理方法來嘗試沒有avial

// https://developers.google.com/google-apps/calendar/v2/developers_guide_dotnet?csw=1#batch 
// Create an batch entry to delete an the appointment 
EventEntry toDelete = (EventEntry)calfeed.Entries[0]; 
toDelete.Id = new AtomId(toDelete.EditUri.ToString()); 
toDelete.BatchData = new GDataBatchEntryData("Deleting Appointment", GDataBatchOperationType.delete); 


// add the entry to batch 

AtomFeed batchFeed = new AtomFeed(calfeed); 

batchFeed.Entries.Add(toDelete); 


// run the batch 

EventFeed batchResultFeed = (EventFeed)svc.Batch(batchFeed, new Uri(ConfigurationManager.AppSettings["GoogleCalendarPostURI"] )); 


// check for succses 

Debug.Write (batchResultFeed.Entries [0].BatchData.Status.Code); 

if (batchResultFeed.Entries [0].BatchData.Status.Code != 200) { 
    return; 
} 

回答

0

無法弄清楚發生了什麼事情與v2,但是我能夠使用服務帳戶移至API的第3版進行身份驗證。

using System; 

using Google.Apis.Calendar.v3; 
using Google.Apis.Calendar.v3.Data; 
// for BaseClientService.Initializer 
using Google.Apis.Services; 
// provides ServiceAccountCredential 
using Google.Apis.Auth.OAuth2; 
// read in cert 
using System.Security.Cryptography.X509Certificates; 


namespace LunaIntraDBCalTest 
{ 
    public class Program 
    { 
     public static string calendarname = "[email protected]"; //address is default calendar 
     public static string serviceAccountEmail = "[email protected]"; 

     public static CalendarService getCalendarService(){ 



      // certificate downloaded after creating service account access at could.google.com 
      var certificate = new X509Certificate2(@"key.p12", "notasecret", X509KeyStorageFlags.Exportable); 

      // autheticate 
      ServiceAccountCredential credential = new ServiceAccountCredential(
       new ServiceAccountCredential.Initializer(serviceAccountEmail) 
       { 
        Scopes = new[] { CalendarService.Scope.Calendar } 
       }.FromCertificate(certificate)); 

      // Create the service. 
      var service = new CalendarService(new BaseClientService.Initializer() 
       { 
        HttpClientInitializer = credential, 
        ApplicationName = "LunaIntraDB", 
       }); 

      return service; 
     } 

     // create event object that will later be inserted 
     public static Event createEvent(string Summary, string Location, string Description, DateTime ApptDateTime, double duration){ 
      // create an event 
      Event entry= new Event 
      { 
       Summary = Summary, 
       Location = Location, 
       Description = Description, 
       Start = new EventDateTime { DateTime = ApptDateTime }, 
       End = new EventDateTime { DateTime = ApptDateTime.AddHours(duration) }, 
      }; 

      return entry; 
     } 

     // capture event ID after inserting 
     public static string insertEvent(Event entry){ 
      var service = getCalendarService(); 
      EventsResource.InsertRequest insert = service.Events.Insert (entry, calendarname); 
      // TODO: try catch here; will be throw exception if bad datetime 
      return insert.Execute().Id; 
     } 

     public static void deleteEvent(string id){ 
      // TODO CATCH IF NOT FOUND 
      // to have access to this calendar, serviceAccountEmail needed permission set by ownner in google calendar 
      //Calendar cal1 = service.Calendars.Get (calnedarname).Execute(); 
      var service = getCalendarService(); 
      service.Events.Delete (calendarname, id).Execute(); 
     } 

     public static void Main(string[] args) 
     { 

      // create event 
      var entry = createEvent ("TEST", "here", "this is a test", DateTime.Now, 1.5); 

      string id = insertEvent (entry); 
      Console.WriteLine("Run to your calendar to see that this event was created... (any key after checking)"); 
      Console.ReadKey(); 

      deleteEvent (id); 
      Console.WriteLine("Should now be deleted!... (any key to close)"); 
      Console.ReadKey(); 
     } 
    } 
}