Page keeps loading, Google Calendar API - c#

I have created an ASP.Net Core MVC project and integrated the Google Calendar API:
Google.Apis.Calendar.v3 with a NuGet package
I followed this guide.
it seems to work since i see some records from my calendar in the output window of my visual studio
but the page themself never stops loading?
i removed the default pages and events in the HomeController only Index is left
and replaced the code from the program.cs with the code from google.
namespace CalendarQuickstart
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-dotnet-quickstart.json
static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
static string ApplicationName = "Google Calendar API .NET Quickstart";`
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
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.
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.");
}
Console.Read();
}
}
}
so I can't see my index view.

replacing the List Events with :
CreateWebHostBuilder(args).Build().Run();
and adding :
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
i am able to see the Index Page/View again

Related

How to create an event in Google Calendar using c# and Google API?

UPDATE: I solved this problem and posted the solution as an answer below! ;)
I need to create an event and add it to Google Calendar using Google API.
For now I only know how to get all the events I have from Google Calendar. This is what I've got so far:
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;
namespace CalendarQuickstart
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-dotnet-quickstart.json
static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
static string ApplicationName = "Google Calendar API .NET Quickstart";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
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.
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.");
}
Console.Read();
}
}
}
What I am trying to do must be looking something like this:
var ev = new Event();
EventDateTime start = new EventDateTime();
start.DateTime = new DateTime(2019, 3, 11, 10, 0, 0);
EventDateTime end = new EventDateTime();
end.DateTime = new DateTime(2019, 3, 11, 10, 30, 0);
ev.Start = start;
ev.End = end;
ev.Description = "Description...";
events.Items.Insert(0, ev);
I've spent the entire day searching any .NET samples but got nothing.
Any help appreciated! ;)
I've solved this problem! So before building the project change
static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
to
static string[] Scopes = { CalendarService.Scope.Calendar };
If you already built the solution then delete credentials.json file and then reload it. The code for adding an event is here:
var ev = new Event();
EventDateTime start = new EventDateTime();
start.DateTime = new DateTime(2019, 3, 11, 10, 0, 0);
EventDateTime end = new EventDateTime();
end.DateTime = new DateTime(2019, 3, 11, 10, 30, 0);
ev.Start = start;
ev.End = end;
ev.Summary = "New Event";
ev.Description = "Description...";
var calendarId = "primary";
Event recurringEvent = service.Events.Insert(ev, calendarId).Execute();
Console.WriteLine("Event created: %s\n", e.HtmlLink);
This is my first try with Google API so don't judge me ;) Hope it helps somebody one day!
Note : You also need to remove the 'token.json' folder from \bin\debug folder

Connect o google spreadsheet from .NET and Python

Trying to get Google spreadsheet table content by using C# client and Python.
C# client works fine while python returns error:
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://sheets.googleapis.com/v4/spreadsheets/IAD2okAWZD7anbt5L4ybgD2dxHBGmsY6IkNIWHBQkBM/values/new%20first%20sheet%21A1?alt=json returned "Requested entity was not found.">
If I open link in error in browser I see error:
{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"status": "PERMISSION_DENIED"
}
}
What might be wrong in Python client?
C# client:
private void button1_Click(object sender, EventArgs e)
{
string ApplicationName = "aaa";
UserCredential credential;
using (var stream =new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
String range = "new first sheet!A2:E";//mano
SpreadsheetsResource.ValuesResource.GetRequest request =service.Spreadsheets.Values.Get(spreadsheetId, range);
// https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
ValueRange response = request.Execute();
IList<IList<Object>> values = response.Values;
if (values != null && values.Count > 0)
{
Console.WriteLine("Name, Major");
foreach (var row in values)
{
// Print columns A and E, which correspond to indices 0 and 4.
if (row.Count==1 ) Console.WriteLine("{0}", row[0]);
else
Console.WriteLine("{0}, {1}", row[0], row[1]);
}
}
else
{
Console.WriteLine("No data found.");
}
Console.Read();
}
Python client:
class SS:
store = file.Storage('token.json')
try:
creds = store.get()
except Exception as e:
print(traceback.format_exc())
if not creds or creds.invalid:
flow = client.flow_from_clientsecrets('credentials.json', SCOPES)
creds = tools.run_flow(flow, store)
service = build('sheets', 'v4', http=creds.authorize(Http()))
# Call the Sheets API
SPREADSHEET_ID = 'IAD2okAWZD7anbt5L4ybgD2dxHBGmsY6IkNIWHBQkBM' #my
RANGE_NAME = 'new first sheet!A1' #my
def __init__(self):
print("Constructing")
def get(self):
print("starting get")
result = self.service.spreadsheets().values().get( spreadsheetId=self.SPREADSHEET_ID, range=self.RANGE_NAME).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Name, Major:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print('%s, %s' % (row[0], row[4]))

Access a public Google Calendar with C#

I have a WPF application in which a want to access a public Google Calendar that I have added to my Google account in order to look for upcoming events. I used the quickstart provided by Google but I can't figure out how to select which calendar I want to access. How do I choose which calendar to get events from?
UPDATE: Moved code and solution to a separate answer.
Get a calendar list using the CalenderList API .
As per documentation:
Calendar List - A list of all calendars on a user's calendar list in the Calendar UI.
scrolling further down you find:
About calendarList entry resources
A calendar in a user's calendar list is a calendar that is visible in the Google Calendar web interface under My calendars or Other calendars:
Turns out it was simple to access the calendar! I just had to change the primary in
EventsResource.ListRequest request = service.Events.List("primary");
to the calendar ID for the calendar I want to access. Now I can get my events from my primary calendar!
Solution:
public class GoogleCalendar
{
static string[] Scopes = { CalendarService.Scope.CalendarReadonly };
static string ApplicationName = "Calendar API Quickstart";
public static string GetEvents()
{
UserCredential credential = Login();
return GetData(credential);
}
private static string GetData(UserCredential credential)
{
// Create Calendar Service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
EventsResource.ListRequest request = service.Events.List("The calendar ID to the calender I want to access");
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
Console.WriteLine("Upcoming events:");
Events events = request.Execute();
if (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.");
}
return "See console log for upcoming events";
}
static UserCredential Login()
{
UserCredential credential;
using (var stream = new FileStream(#"Components\client_secret.json", FileMode.Open,
FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment
.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
}
return credential;
}
}

Google Cloud Datastore request returns Error 400 in my browser

After many trials and errors I managed to compile a piece of code which should return Entities' values from Google Datastore (it's SQL-like db). Code I used:
static async void Run()
{
UserCredential credential;
using (var stream = new FileStream(#"c:/fakepath/client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { DatastoreService.Scope.Datastore }, "user", CancellationToken.None);
}
// Create the service.
var service = new DatastoreService(new BaseClientService.Initializer
{
ApplicationName = "My Project",
HttpClientInitializer = credential
});
// Run the request.
Console.WriteLine("Executing a list request...");
var request = new LookupRequest();
var key = new Google.Apis.Datastore.v1beta2.Data.Key();
key.Path = new List<KeyPathElement> { new KeyPathElement() { Kind = "book", Name = "title42" } };
request.Keys = new List<Key>() { key };
var lookup = service.Datasets.Lookup(request, "project-name-192"); //yea
var response = lookup.Execute();
// Display the results.
if (response.Found != null)
{
foreach (var x in response.Found)
{
foreach (var y in x.Entity.Properties)
{
Console.WriteLine(y.Key.FirstOrDefault() + " " + y.Value);
}
}
}
}
Error I get:
So, what am I missing? I did just like in example on docs.
You need to go to:
https://console.developers.google.com/project/apps~{your-app-name}/apiui/credential
and use http://localhost:63324/authorize/ as the redirect url.
Remember to change it to your production url when you deploy

C# DateTime to EventDateTime

Currently I'm working with the v3 google calendar API. I have a specification which the local object needs to use dateTime, but google uses EventDateTime. I just wonder if there is a clever way to convert one to the other? I know it is possible to use tostring, but currently I have a hard time figuring out what prefixes I need to do so.
Thanks for any help.
According to the documentation it is possible to use a string formatted datetime.
setDate
public EventDateTime setDate(DateTime date)
The date, in the format "yyyy-mm-dd", if this is an all-day event.
Parameters:
date - date or null for none
Sample:
DateTime myDateTime = DateTime.Now();
string dateTimeString = myDateTime.ToString("yyyy-MM-dd HH:mm");
For the google calendar, your would probably create a EventDateTime object, and then set the date using the setDate(string datetime) method.
EventDateTime eventDateTime = new EventDateTime();
eventDateTime.setDate(dateTimeString);
To use a full day eventdatetime, you will omit the "HH:mm" from the ToString() method. I have never used this API, so something may be a bit off.
I hope this can help someone...building on scheien's answer above.
Im just gonna post all the code..as it might help someone messing with Google Calender.
I have Method Extension that converts DateTime to EventDateTime.
Example from code
evntNew.Start = oCalEvent.Start.ToEventDateTime();
Here the whole source. (feel free to edit)
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;
using System;
using System.IO;
using System.Threading;
namespace GoogleCalendarAPI
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/calendar-dotnet-quickstart.json
static string[] Scopes = { CalendarService.Scope.CalendarReadonly,
CalendarService.Scope.CalendarEvents,
CalendarService.Scope.Calendar};
static string ApplicationName = System.AppDomain.CurrentDomain.FriendlyName;
static void Main(string[] args)
{
CalendarEvent oCalEvent = new CalendarEvent();
oCalEvent.Summary = "Hello Calendar";
oCalEvent.Description = "Just another day";
oCalEvent.Location = "Earth";
oCalEvent.Start = DateTime.Now.AddDays(31);
oCalEvent.Stop = DateTime.Now.AddDays(31);
AddCalendarEvent(oCalEvent);
ListUpComing();
Console.Read();
}
static void ListUpComing()
{
UserCredential credential;
using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
// The file token.json stores the user's access and refresh tokens, and is created
// automatically when the authorization flow completes for the first time.
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"admin",
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.
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.");
}
Console.Read();
}
static void AddCalendarEvent(CalendarEvent oCalEvent)
{
UserCredential credential;
using (var stream = new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
{
string credPath = "token.json";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"admin",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
var service = new CalendarService(new BaseClientService.Initializer()
{ HttpClientInitializer = credential, ApplicationName = ApplicationName, }); // Create Google Calendar API service.
Event evntNew = new Event();
evntNew.Summary = oCalEvent.Summary;
evntNew.Location = oCalEvent.Location;
evntNew.Description = oCalEvent.Description;
evntNew.Start = oCalEvent.Start.ToEventDateTime();
evntNew.End = oCalEvent.Stop.ToEventDateTime();
EventsResource.InsertRequest insertRequest = service.Events.Insert(evntNew, "primary");
insertRequest.Execute();
}
}
}
public static class Extensions
{
public static EventDateTime ToEventDateTime(this DateTime dDateTime)
{
EventDateTime edtDateTime = new EventDateTime();
edtDateTime.DateTime = DateTime.ParseExact(dDateTime.ToString("MM/dd/yyyy HH:mm"), "MM/dd/yyyy HH:mm", null);
return edtDateTime;
}
}
public class CalendarEvent
{
public CalendarEvent() { }
public string Summary { get; set; }
public string Description { get; set; }
public string Location { get; set; }
public DateTime Start { get; set; }
public DateTime Stop { get; set; }
}
// END

Categories

Resources