Проблема исключения перенаправления API Календаря Google - PullRequest
0 голосов
/ 09 июня 2011

Я сталкиваюсь со специфической проблемой при доступе к Календарю Google - иногда он генерирует «исключение перенаправления», но в большинстве случаев работает просто отлично.

Я понятия не имею, как перенаправить вызов, и из того, что я прочитал после некоторого поиска, он должен обрабатываться самим API Google, невидимым для вызывающей функции (но, очевидно, нет.)

Код получает доступ к календарю Google, получает список всех дополнительных календарей и количество событий в каждом календаре.

API версия 1.8.0.0 (http://code.google.com/p/google-gdata/downloads/list)

Сообщение об ошибке:

        Execution resulted in a redirect from https://www.google.com/calendar/feeds/tlf1juohv473hh0jhm046do5g9@group.calendar.google.com/private/full?gsessionid=MGsId0ULhyO_DkKlGa9DHw
        at Google.GData.Client.GDataRequest.Execute()
        at Google.GData.Client.GDataGAuthRequest.Execute(Int32 retryCounter)
        at Google.GData.Client.GDataGAuthRequest.Execute()
        at Google.GData.Client.Service.Query(Uri queryUri, DateTime ifModifiedSince, String etag, Int64& contentLength)
        at Google.GData.Client.Service.Query(Uri queryUri, DateTime ifModifiedSince)
        at Google.GData.Client.Service.Query(FeedQuery feedQuery)
        at GoogleDataTool.CalendarActions.GetSecondaryCalendars(Boolean IncludeEventCount, List`1& calendarlist) in D:\GoogleDataTool\classes\CalendarActions.cs:line 65

        Response.Message: "Stream was not readable."
        at Google.GData.Client.GDataRequest.Execute()
        at Google.GData.Client.GDataGAuthRequest.Execute(Int32 retryCounter)
        at Google.GData.Client.GDataGAuthRequest.Execute()
        at Google.GData.Client.Service.Query(Uri queryUri, DateTime ifModifiedSince, String etag, Int64& contentLength)
        at Google.GData.Client.Service.Query(Uri queryUri, DateTime ifModifiedSince)
        at Google.GData.Client.Service.Query(FeedQuery feedQuery)
        at GoogleDataTool.CalendarActions.GetSecondaryCalendars(Boolean IncludeEventCount, List`1& calendarlist) in  D:\GoogleDataTool\classes\CalendarActions.cs:line 84
        at GoogleDataTool.Program.DoActions() in D:\GoogleDataTool\Program.cs:line 34
        at GoogleDataTool.Program.Main(String[] args) in D:\GoogleDataTool\Program.cs:line 14
        at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
        at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
        at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
        at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
        at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
        at System.Threading.ThreadHelper.ThreadStart()

Код (он просто собирает календари, заголовки и количество событий в коллекции):

        public bool GetSecondaryCalendars(out List<CalendarData> calendarlist)
    {
        Console.WriteLine( "Starting calendarlist retrieval..." );

        calendarlist = new List<CalendarData>();

        CalendarService myService = new CalendarService( "Calendar-application" );
        myService.setUserCredentials( "MyAccount@google.com", "MyPassword" );

        CalendarQuery cQuery = new CalendarQuery();
        cQuery.Uri = new Uri( "https://www.google.com/calendar/feeds/default/allcalendars/full" );

        try
        {
            CalendarFeed cFeed = (CalendarFeed)myService.Query( cQuery );

            foreach (CalendarEntry entry in cFeed.Entries)
            {
                // We don't want the primary calendar; just the secondary ones
                if (!entry.Id.Uri.ToString().Contains( HttpUtility.UrlEncode( "MyAccount@google.com" ) ))
                {
                    String calendarid = entry.Id.Uri.ToString().Substring( entry.Id.Uri.ToString().LastIndexOf( "/" ) + 1 );
                    calendarlist.Add( new CalendarData()
                    {
                        Text = entry.Title.Text,
                        Id = calendarid
                    } );
                }

                // Grab each calendar to count the number of events it has (not pretty, but I wish I could just ask the cFeed entries...)
                foreach (CalendarData calendar in calendarlist)
                {
                    FeedQuery query = new FeedQuery();

                    // Create the query object:
                    query.Uri = new Uri( string.Format( "https://www.google.com/calendar/feeds/{0}/private/full", calendar.Id ) );

                    // Tell the service to query:
                    AtomFeed calFeed = myService.Query( query );
                    calendar.EventCount = calFeed.Entries.Count;
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine( ex.Message );
            return false;
        }
        return true;
    }

    public class CalendarData
    {
        public string Id { get; set; }
        public string Text { get; set; }
        public int EventCount { get; set; }
    }

Любые предложения приветствуются.

1 Ответ

0 голосов
/ 10 июня 2011

Из моего pov вы работаете через Интернет - таким образом, вы должны планировать все как минимум дважды, прежде чем сдаться ;-)
Таким образом, я сделал бы одну повторную попытку, а затем поднял фактическое исключение, видимое для конечного пользователя.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...