I hope you can help me:
I have a database with several phone numbers and names
I need to create a process in C# that runs automatically and inserts these values into a Google account that is linked to WhatsApp.
With the result that when opening WhatsApp, the contacts appear with the name
Can you give me indications what to look for or where to start, because I have not been able to find anything useful
Thank you very much in advance
If you have the ability to ask the user to sign-in to their google account you can use the people.createContact api endpoint to create contacts in their google contacts account.
While there will be a delay until the contacts update thought these various systems this is likely the best you can do. HttpClient should be able to make the required API calls :)
sources:
https://developers.google.com/people/api/rest/v1/people/createContact
https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=net-6.0
I leave you the answer, which contains: get the contacts from google and be able to insert. If someone has the functions to update and delete it would be great, that would be everything
// Genéricas
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util.Store;
// People API
//using Google.Apis.People.v1;
//using Google.Apis.People.v1.Data;
using Google.Apis.PeopleService.v1;
using Google.Apis.PeopleService.v1.Data;
// Docs API
using Google.Apis.Docs.v1;
using Google.Apis.Docs.v1.Data;
// Drive API
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data; // Para el tipo File
using System;
using System.Collections.Generic;
//using System.IO;
using System.Threading;
using System.Text;
using System.Linq;
//using System.Collections.Immutable;
using Person = Google.Apis.PeopleService.v1.OtherContactsResource;
using Google.Apis.Requests;
using insert_contacts_google.Mediador;
using System.Net;
using System.Net.Security;
namespace insert_contacts_google
{
class Program
{
// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/docs.googleapis.com-dotnet-quickstart.json
static string[] Scopes = { DocsService.Scope.Documents,
DocsService.Scope.DriveFile,
PeopleServiceService.Scope.Contacts };
static string ApplicationName = "importGoogle";
static PeopleServiceService peopleService;
static UserCredential Credential;
private static int total = 0;
public static List<String> lNumG = new List<String>();
public static Dictionary<string, string> dDatWs = new Dictionary<string, string>();
public static Tools_CPE tools = new Tools_CPE() { Credentials = glbCredenciales, Url = glbWebService };
// Los datos del proyecto creado para VB
static ClientSecrets secrets = new ClientSecrets()
{
ClientId = ".....",
ClientSecret = ".."
};
static void Main(string[] args)
{
Console.WriteLine("Main");
string credPath = System.Environment.GetFolderPath(
Environment.SpecialFolder.Personal);
// Directorio donde se guardarán las credenciales
credPath = System.IO.Path.Combine(credPath, ".credentials/Tutorial-Google-APIs-VB");
Credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
//Console.WriteLine("Credential file saved to: " + credPath);
// Mostrar los contactos
getContactGoole();
getContactWs();
setPeople(peopleService);
}
private static void getContactGoole()
{
// Create Drive API service.
peopleService = new PeopleServiceService(new BaseClientService.Initializer()
{
HttpClientInitializer = Credential,
ApplicationName = ApplicationName,
});
// Lista de los contactos (People)
Console.WriteLine("Contactos:");
// Este muestra todos los contactos
GetPeople(peopleService, null);
Console.WriteLine();
Console.WriteLine($"Hay {total} contactos / People");
Console.WriteLine();
}
static bool GetPeople(PeopleServiceService service, string pageToken)
{
bool control = true;
// Define parameters of request.
PeopleResource.ConnectionsResource.ListRequest peopleRequest =
service.People.Connections.List("people/me");
//
// Lista de campos a usar en RequestMaskIncludeField:
// https://developers.google.com/people/api/rest/v1/people/get
//
peopleRequest.RequestMaskIncludeField = new List<string>()
{"person.names", "person.phoneNumbers", "person.emailAddresses",
"person.birthdays", "person.Addresses"
};
if (pageToken != null)
{
peopleRequest.PageToken = pageToken;
}
ListConnectionsResponse people = peopleRequest.Execute();
if (people != null && people.Connections != null && people.Connections.Count > 0)
{
total += people.Connections.Count;
foreach (var person in people.Connections)
{
/*
Console.Write(person.PhoneNumbers != null ? ($"{person.PhoneNumbers.FirstOrDefault().Value} - ") : "");
Console.Write(person.EmailAddresses != null ? ($"{person.EmailAddresses.FirstOrDefault().Value} - ") : "");
Console.Write(person.Addresses != null ? ($"{person.Addresses.FirstOrDefault()?.City} - ") : "");
Console.Write(person.Names != null ? ($"{person.Names.FirstOrDefault().DisplayName} - ") : "");
*/
if (person.PhoneNumbers != null)
{
String num = person.PhoneNumbers.FirstOrDefault().Value;
lNumG.Add(num);
}
Console.WriteLine();
}
if (people.NextPageToken != null)
{
Console.WriteLine();
Console.WriteLine($"{total} contactos mostrados hasta ahora. Pulsa una tecla para seguir mostrando contactos.");
Console.WriteLine();
GetPeople(service, people.NextPageToken);
}
}
else
{
control = false;
Console.WriteLine("No se han encontrado contactos.");
}
return control;
}
static void setPeople(PeopleServiceService service)
{
Google.Apis.PeopleService.v1.Data.Person person = new Google.Apis.PeopleService.v1.Data.Person();
Name chef = new Name();
chef.GivenName = "FirstName2";
chef.FamilyName = "FamilyName3";
person.Names = new List<Name>();
person.Names.Add(chef);
PhoneNumber phone = new PhoneNumber();
phone.Value = "04040404";
phone.Type = "mobile";
person.PhoneNumbers = new List<PhoneNumber>();
person.PhoneNumbers.Add(phone);
EmailAddress email = new EmailAddress();
email.Type = "work";
email.Value = "firstname2.familyname2#something.com";
person.EmailAddresses = new List<EmailAddress>();
person.EmailAddresses.Add(email);
ContactToCreate contactToCreate = new ContactToCreate();
contactToCreate.ContactPerson = person;
BatchCreateContactsRequest request = new BatchCreateContactsRequest();
request.Contacts = new List<ContactToCreate>();
request.Contacts.Add(contactToCreate);
request.ReadMask = "names";
BatchCreateContactsResponse reply = service.People.BatchCreateContacts(request).Execute();
}
}
}
Related
I am trying to read google sheets data in my xamarin forms ios project. I followed this tutorial: https://www.youtube.com/watch?v=afTiNU6EoA8&t=325s
To no avail.
My program says it can't find the client_secret.json file, and I can't find a solution to my problem.
it gives me this exception error
Here is my code:
using System;
using Google.Apis.Sheets.v4;
using Google.Apis.Auth.OAuth2;
using System.IO;
using Google.Apis.Services;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace CUapp
{
public class GoogleSheets
{
static readonly string[] Scopes = { SheetsService.Scope.Spreadsheets };
static readonly string SpreadsheetId = "1Me8q2o54xphoO_L1l-aK6_qzwIX2AAmmZzCCxvmGbl8";
static readonly string ApplicationName = "CUapp";
static readonly string sheet = "Sheet1";
static SheetsService service;
public GoogleSheets()
{
GoogleCredential credential;
using (
var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
//var stream = Assembly.GetManifestResourceStream("client_secret.json"))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(Scopes);
}
// Create Google Sheets API service.
service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential, ApplicationName = ApplicationName
});
ReadEntries();
}
static public void ReadEntries()
{
var range = $"{sheet}!B1:B30";
SpreadsheetsResource.ValuesResource.GetRequest request = service.Spreadsheets.Values.Get(SpreadsheetId, range);
request.MajorDimension = SpreadsheetsResource.ValuesResource.GetRequest.MajorDimensionEnum.COLUMNS;
var response = request.Execute();
var values = response.Values;
if (values != null && values.Count > 0)
{
foreach (var column in values)
{
string title = (string)column[0];
int i = (int)column[1];
//string buttonImg = $"{title}.jpeg";
//labels
char[] seperator = new char[] { ' ', ',' };
string labels_ = (string)column[3];
List<string> labels = labels_.Split(seperator, StringSplitOptions.RemoveEmptyEntries).ToList();
//_nums
int ingredients_num = (int)column[4];
int howto_num = (int)column[5];
int nutritionTips_num = (int)column[6];
int cookingTips_num = (int)column[7];
//ingredients
List<string> ingredients_raw = (List<string>)column.Skip(8).Take(ingredients_num);
List<ingredientBlock> ingredients = new List<ingredientBlock>();
foreach (var value_raw in ingredients_raw)
{
ingredientBlock ingredient = new ingredientBlock { text = value_raw };
ingredients.Add(ingredient);
}
//howto
List<string> howto_raw = (List<string>)column.Skip(8 + 1 + ingredients_num).Take(howto_num);
List<ingredientBlock> howto = new List<ingredientBlock>();
char howtoSeperator = '#';
foreach (string value_raw in howto_raw)
{
var value = value_raw.Split(howtoSeperator).ToList();
ingredientBlock ingredient = new ingredientBlock { step = value[0], text = value[1] };
howto.Add(ingredient);
}
recipeList.list.Add(new recipeModel { title = title, howto = howto, i = i, ingredients = ingredients, labels = labels });
//nutritionTips
//cookingTips_
// create new recipemodel
// title = 0, index = 1, buttonImg = 2, labels = 3
// ingredients_num = 4, methods_num = 5, nutritionTips_num = 6
// cookingTips_num = 7, ingredients = 8:8+ingredients_num-1,
}
}
}
}
}
Any response is appreciated :D
My program says it can't find the client_secret.json file, and I can't find a solution to my problem.
Firstly, put your client_secret.json file in shared code, make sure to set Build Action to EmbeddedResource
Then using the following code to parse our local json file.
var assembly = typeof(listviewsample.Page24).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("FormsSample.user.json");
using (var reader = new System.IO.StreamReader(stream))
{
var jsonString = reader.ReadToEnd();
//........
}
Update:
I test the code in simple sample, and you can take a look the following screenshot.
public partial class Page2 : ContentPage
{
public Page2()
{
InitializeComponent();
var assembly = typeof(Page2).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("mediasample.user.json");
using (var reader = new System.IO.StreamReader(stream))
{
var jsonString = reader.ReadToEnd();
//Converting JSON Array Objects into generic list
}
}
}
screenshot:
Thanks to Cherry BU, I overcame this hurdle. Here is my code:
public GoogleSheets()
{
GoogleCredential credential;
var assembly = typeof(GoogleSheets).GetTypeInfo().Assembly;
Stream stream = assembly.GetManifestResourceStream("CUapp.client_secret.json");
using (var reader = new StreamReader(stream))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(Scopes);
}
// Create Google Sheets API service.
service = new SheetsService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential, ApplicationName = ApplicationName
});
ReadEntries();
}
I am trying to create a domain shared contact in GSuite via the Contacts API in C# but unable to figure out how to POST the atom XML entry to the Feed URL as mentioned here : https://developers.google.com/admin-sdk/domain-shared-contacts/#Creating
I have tried following the older GData way mentioned here https://developers.google.com/gdata/client-cs but I get a "Execution of authentication request returned unexpected result: 404" error.
static void Main(string[] args)
{
Console.WriteLine("Hello !! ");
//Get Auth
OAuth2Parameters p = ContactsAuth();
//Create a domain shared contact
try
{
RequestSettings settings = new RequestSettings("GSuiteAdminApp", p);
ContactsRequest cr = new ContactsRequest(settings);
ContactEntry cn = new ContactEntry();
Name n = new Name();
n.GivenName = "Ice";
n.FamilyName = "Cold001";
n.FullName = "Ice Cold001";
EMail e = new EMail();
e.Rel = "http://schemas.google.com/g/2005#work";
e.Primary = true;
e.Address = "ice.cold001#xyz.com";
cn.Name = n;
cn.Emails.Add(e);
}
catch (Exception e44)
{
Console.WriteLine(e44.Message);
}
}
//Auth for Contacts API
public static OAuth2Parameters ContactsAuth()
{
string clientId = "xxxxxxxxxxxxxx.apps.googleusercontent.com";
string clientSecret = "xxxxxxxxxxxxx";
string[] scopes = new string[] { "https://www.google.com/m8/feeds/" };
try
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
}, scopes, "super-admin#mydomain.com", CancellationToken.None, new FileDataStore("C:\\Temp\\A\\SharedContactsOauth")).Result;
// Translate the Oauth permissions to something the old client libray can read
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.AccessToken = credential.Token.AccessToken;
parameters.RefreshToken = credential.Token.RefreshToken;
return parameters;
}
catch (Exception ex33)
{
Console.WriteLine(ex33.Message);
return null;
}
}
This gives a "request failed" error.
I was finally able to figure it out by stringing along code snippets from few different sources and some modifications of my own. Linda Lawton's https://www.daimto.com/google-contacts-with-c/ for the OAuth2 part using older GData API. Google's documentation on Contacts API v3.0 https://developers.google.com/contacts/v3/ for mechanics of using the .NET client library for contacts and their (bit sketchy) documentation on "domain shared contacts", especially on using the proper FeedUri and Atom entries for new contact https://developers.google.com/admin-sdk/domain-shared-contacts/#Creating.
Basically what it boils down to is this -
Use a GSuite Super Admin account to authrorize to Contacts API using OAuth2.0, then use GData Contacts .NET client library to create the new contact
by suppying your Gsuite domain in the method and you are done.
Here's the full code which I have it working for me now:
using System;
using System.Threading;
using Google.Contacts;
using Google.GData.Contacts;
using Google.GData.Client;
using Google.GData.Extensions;
using Google.Apis.Auth;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
namespace SharedContactsAPI
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello !! ");
//Get Auth
OAuth2Parameters p = ContactsAuth();
////Create a domain shared contact
try
{
RequestSettings settings = new RequestSettings("GSuiteAdminApp", p);
ContactsRequest contactreq = new ContactsRequest(settings);
Console.WriteLine("Attempting to create a Domain Shared Contact in GSuite");
Console.WriteLine(" ");
CreateContact(contactreq);
}
catch (Exception e44)
{
Console.WriteLine(e44.Message);
}
}
//Create Shared Contact
public static Contact CreateContacttest(ContactsRequest cr)
{
Contact newEntry = new Contact();
// Set the contact's name.
newEntry.Name = new Name()
{
FullName = "Ice Cold005",
GivenName = "Ice",
FamilyName = "Cold005"
};
newEntry.Content = "Notes";
// Set the contact's e-mail addresses.
newEntry.Emails.Add(new EMail()
{
Primary = true,
Rel = ContactsRelationships.IsWork,
Address = "ice.cold005#xyz.com"
});
//Insert the contact
Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("test.com"));
Contact createdEntry = cr.Insert(feedUri, newEntry);
Console.WriteLine("New Contact created successfully with ContactID = " + createdEntry.Id);
return createdEntry;
}
//Auth for Contacts API
public static OAuth2Parameters ContactsAuthtest()
{
string clientId = "xxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com";
string clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
string[] scopes = new string[] { "https://www.google.com/m8/feeds/contacts/" };
try
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
}, scopes, "super-admin#test.com", CancellationToken.None, new FileDataStore("C:\\Temp\\A\\SharedContactsOauth")).Result;
// Translate the Oauth permissions to something the old client libray can read
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.AccessToken = credential.Token.AccessToken;
parameters.RefreshToken = credential.Token.RefreshToken;
return parameters;
}
catch (Exception ex33)
{
Console.WriteLine(ex33.Message);
return null;
}
}
}
}
If it is possible to integrate Google big query with C# console application?.
If yes how we can do, i searched over internet i could not find proper answer for that.
I want connection string format? I have created Client ID from Google Developer console how authentication has done? It is one time configuration or every time we need to login in google account to authenticate.
If there is any sample application to connect sample data it would be helpful.
Thanks,
Selvakumar S
Here's a working sample based on another question in StackOverflow:
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using Google.Apis.Util;
using System;
using System.Diagnostics;
using System.Collections.Generic;
namespace BigQueryConsole
{
public class BigQueryConsole
{
// Put your client ID and secret here (from https://developers.google.com/console)
// Use the installed app flow here.
// Client ID looks like "9999999.apps.googleusercontent.com"
static string clientId = "YOURCLIENTID";
static string clientSecret = "YOURSECRET";
// Project ID is in the URL of your project on the APIs Console
// Project ID looks like "999999";
static string projectId = "YOURPROJECTID";
// Query in SQL-like form
static string query = "SELECT state, count(*) from [publicdata:samples.natality] GROUP BY state ORDER BY state ASC";
public static void Main(string[] args)
{
// Register an authenticator.
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description);
provider.ClientIdentifier = clientId;
provider.ClientSecret = clientSecret;
// Initiate an OAuth 2.0 flow to get an access token
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
// Create the service.
var service = new BigqueryService(auth);
JobsResource j = service.Jobs;
QueryRequest qr = new QueryRequest();
qr.Query = query;
QueryResponse response = j.Query(qr, projectId).Fetch();
foreach (TableRow row in response.Rows)
{
List<string> list = new List<string>();
foreach (TableRow.FData field in row.F)
{
list.Add(field.V);
}
Console.WriteLine(String.Join("\t", list));
}
Console.WriteLine("\nPress enter to exit");
Console.ReadLine();
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient arg)
{
// Get the auth URL:
IAuthorizationState state = new AuthorizationState(new[] { BigqueryService.Scopes.Bigquery.GetStringValue() });
state.Callback = new Uri(NativeApplicationClient.OutOfBandCallbackUrl);
Uri authUri = arg.RequestUserAuthorization(state);
// Request authorization from the user (by opening a browser window):
Process.Start(authUri.ToString());
Console.Write(" Authorization Code: ");
string authCode = Console.ReadLine();
Console.WriteLine();
// Retrieve the access token by using the authorization code:
return arg.ProcessUserAuthorization(authCode, state);
}
}
}
In your answer i could not able to add namespace
"using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;"
But i manage to retrieve results from BigQuery using below code, you need to update Project Name, Project Id and Query.
Download Client ID (I am using Installed Application - Other category ) generate JSON file and add into your Debug folder.
using Google.Apis.Auth.OAuth2;
using System.IO;
using System.Threading;
using Google.Apis.Bigquery.v2;
using Google.Apis.Bigquery.v2.Data;
using System.Data;
using Google.Apis.Services;
using System;
namespace GoogleBigQuery
{
public class Class1
{
private static void Main()
{
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open,
FileAccess.Read))
{
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { BigqueryService.Scope.Bigquery },
"user", CancellationToken.None).Result;
}
// Create and initialize the Bigquery service. Use the Project Name value
// from the New Project window for the ApplicationName variable.
BigqueryService Service = new BigqueryService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "PROJECT NAME"
});
string query = "YOUR QUERY";
JobsResource j = Service.Jobs;
QueryRequest qr = new QueryRequest();
qr.Query = query;
DataTable DT = new DataTable();
int i = 0;
QueryResponse response = j.Query(qr, "PROJECT ID").Execute();
if (response != null)
{
int colCount = response.Schema.Fields.Count;
foreach (var Column in response.Schema.Fields)
{
DT.Columns.Add(Column.Name);
}
foreach (TableRow row in response.Rows)
{
DataRow dr = DT.NewRow();
for (i = 0; i < colCount; i++)
{
dr[i] = row.F[i].V;
}
DT.Rows.Add(dr);
}
}
else
{
Console.WriteLine("Response is null");
}
}
}
}
Thanks.
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
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