locked
google calendar api RRS feed

  • Question

  • User1119553929 posted

    How to activate google calendar API on azure without Active Directory?

    i have this code running on local host:

    using PagedList;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.Entity;
    using System.Globalization;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Web;
    using System.Web.Mvc;
    using Turismo.Models;
    using Google.Apis.Auth.OAuth2;
    using Google.Apis.Calendar.v3;
    using Google.Apis.Calendar.v3.Data;
    using Google.Apis.Services;
    using Google.Apis.Util.Store;

    // GET: Events

    [AllowAnonymous]
    public ActionResult Calendar(int? Id, string Gmail) {

    // If modifying these scopes, delete your previously saved credentials
    // at ~/.credentials/calendar-dotnet-quickstart.json
    string[] Scopes = { CalendarService.Scope.Calendar };
    string ApplicationName = "Google Calendar API .NET Quickstart";


    var agendar = db.Events.Where(o => o.ID_Evento == Id).FirstOrDefault();

    UserCredential credential;

    using (var stream =
    new FileStream(Server.MapPath("../client_secret.json"), FileMode.Open, FileAccess.Read))
    {
    string credPath = System.Environment.GetFolderPath(
    System.Environment.SpecialFolder.Personal);
    credPath = Server.MapPath("/calendar-dotnet-quickstart.json");

    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
    GoogleClientSecrets.Load(stream).Secrets,
    Scopes,
    Gmail,
    CancellationToken.None,
    new FileDataStore(credPath, true)).Result;
    Console.WriteLine("Credential file saved to: " + credPath);
    }

    // Create Google Calendar API service.
    var service = new CalendarService(new BaseClientService.Initializer()
    {
    HttpClientInitializer = credential,
    ApplicationName = ApplicationName,
    });

    // Define parameters of request.
    EventsResource.ListRequest request = service.Events.List("primary");
    request.TimeMin = DateTime.Now;
    request.ShowDeleted = false;
    request.SingleEvents = true;
    request.MaxResults = 10;
    request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;

    // List events.
    Google.Apis.Calendar.v3.Data.Events events = request.Execute();
    Console.WriteLine("Upcoming events:");
    if (events.Items != null && events.Items.Count > 0)
    {
    foreach (var eventItem in events.Items)
    {
    string when = eventItem.Start.DateTime.ToString();
    if (String.IsNullOrEmpty(when))
    {
    when = eventItem.Start.Date;
    }
    Console.WriteLine("{0} ({1})", eventItem.Summary, when);
    }
    }
    else
    {
    Console.WriteLine("No upcoming events found.");
    }

    Event evnt = new Event();
    evnt.Summary = agendar.Título;
    evnt.Location = agendar.Local;
    evnt.Description = agendar.Descrição;

    //


    EventDateTime startTime = new EventDateTime() { DateTime = new DateTime(agendar.Data_Início.Value.Year,agendar.Data_Início.Value.Month,agendar.Data_Início.Value.Day,19,00,00)};
    evnt.Start = startTime;
    if (agendar.Data_Fim != null)
    {
    EventDateTime endTime = new EventDateTime() { DateTime = new DateTime(agendar.Data_Fim.Value.Year, agendar.Data_Fim.Value.Month, agendar.Data_Fim.Value.Day, 19, 00, 00) };
    evnt.End = endTime;
    }
    else
    {
    evnt.End = startTime;
    }


    String calendarId = "primary";
    EventsResource er = new EventsResource(service);

    //
    service.Events.Insert(evnt, calendarId).Execute();
    //

    return View();
    }

    When i Deploy it to Azure i have OAUTH denied.....

    can u help?

    Monday, January 8, 2018 7:15 PM

All replies

  • User475983607 posted

    I imagine the URL changed when deployed to Azure so you'll need to update your Google OAuth setting to include the new URL or perhaps create a new account for the Azure app.  Anyway, see the Google docs for more information.

    Monday, January 8, 2018 8:57 PM
  • User1119553929 posted

    Server Error in '/' Application.


    Access is denied

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.Net.HttpListenerException: Access is denied

    Source Error:

    An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.


    Stack Trace:

    [HttpListenerException (0x5): Access is denied]
       System.Net.HttpListener.SetupV2Config() +335
       System.Net.HttpListener.Start() +303
       Google.Apis.Auth.OAuth2.LocalServerCodeReceiver.StartListener() +61
       Google.Apis.Auth.OAuth2.<ReceiveCodeAsync>d__14.MoveNext() +76
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
       Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__8.MoveNext() +479
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
       Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__4.MoveNext() +392
       System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +99
       System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +61
       Google.Apis.Auth.OAuth2.<AuthorizeAsync>d__1.MoveNext() +286
    
    [AggregateException: One or more errors occurred.]
       System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions) +4330309
       System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification) +12844771
       System.Threading.Tasks.Task`1.get_Result() +33
       Turismo.Controllers.EventsController.Calendar(Nullable`1 Id, String Gmail) in C:\Users\Nando\source\repos\Turismo\Turismo\Controllers\EventsController.cs:48
       lambda_method(Closure , ControllerBase , Object[] ) +150
       System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
       System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +169
       System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
       System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
       System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
       System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
       System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +228
       System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
       System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
       System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
       System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
       System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
       System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
       System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
       System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
       System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
       System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
       System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
       System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
       System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
       System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +577
       System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step) +132
       System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +163
    

     


    Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.2558.0

    Monday, January 8, 2018 9:15 PM
  • User283571144 posted

    Hi zulurl,

    [HttpListenerException (0x5): Access is denied]

    As far as I know, if you create the google oauth credential's application type is other. It will set the auto redirect url to localhost.

    When use other application type  google auth, the google auth library will auto call the process to create a new browser page to show the auth page.

    But after you have published the application to azure web app, you don't have the permission to allow your application call process to create a new browser page to show the auth page.

    So it will show the access denied error.

    Normally, we will use asp.net identity external login to achieve google auth.

    Then we could use the userid and token to create the request to google calendar api to ask for the user calendar information.

    Google has already create a MVC sample. 

    I suggest you could modify your application with that demo.

    https://github.com/google/google-api-dotnet-client-samples/tree/master/Calendar.ASP.NET.MVC5

    I have also created a test, it could work well in azure web app.

    The result like this:

    Best Regards,

    Brando

    Tuesday, January 9, 2018 8:04 AM