They write:"Supported Platforms: Portable Class Libraries".
But then I write this code in portable class, I have a error:
public async void MyFuncrion()
{
UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
//new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read),
new ClientSecrets
{
ClientId = "", //"PUT_CLIENT_ID_HERE",
ClientSecret = "" //"PUT_CLIENT_SECRETS_HERE"
},
new[] { TasksService.Scope.Tasks },
"user",
CancellationToken.None);
var service = new TasksService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Tasks API Sample",
});
TaskLists results = await service.Tasklists.List().ExecuteAsync();
foreach (var tasklist in results.Items)
{
TasklistTitlesCollection.Add(tasklist.Title + " " + tasklist.Updated);
// You can get data from the file (using file.Title for example)
// and append it to a TextBox, List, etc.
}
}
Error here: "UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync()", He doen't work in portable library. How can I use library, get tasks without GoogleWebAuthorizationBroker. I already get access token myself and I need only TasksService, maybe I can past my access token and other in the constructor TasksService?
I use this article to breake this wall google .net library
Here i past some my code from PCL and windows8.
PCL:
You need provide DataStore
private async Task<GoogleAuthorizationCodeFlow.Initializer> InitInitializer()
{
_iDataStore = await _userCredential.GetDataStore(); //new StorageDataStore()
var initializer = new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = ClientId, //"PUT_CLIENT_ID_HERE",
ClientSecret = ClientSecret, //"PUT_CLIENT_SECRET_HERE"
},
Scopes = new[] { TasksService.Scope.Tasks },
DataStore = (Google.Apis.Util.Store.IDataStore)_iDataStore //new StorageDataStore()
};
return initializer;
}
Then
public async Task<TasksService> Prepare()
{
GoogleAuthorizationCodeFlow.Initializer initializer = await InitInitializer();
Object credential = new Object();
if (String.IsNullOrEmpty(_username))
{
return null;
}
TasksService service = null;
try
{
credential = await _userCredential.GetCredential(initializer, _username);
}
catch (Google.Apis.Auth.OAuth2.Responses.TokenResponseException e)
{
service = null;
return service;
}
catch
{
return null;
}
service = new TasksService(new BaseClientService.Initializer
{
HttpClientInitializer = (UserCredential)credential,
ApplicationName = _applicationName,
});
return service;
}
1) In Windows store you need provide StorageDataStore and traverse it to pcl.
2) Use
AuthorizationCodeWinRTInstalledApp(initializer).AuthorizeAsync(username, new CancellationToken(false))
from google library (Google.Apis.Auth.OAuth2) to get your credential and traverse it to pcl
You have two options:
1.Declare foo as async method:
async void Foo()
2.Remove await, and get the result of your task, so your code should look something like:
serCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
//new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read),
new ClientSecrets
{
ClientId = "", //"PUT_CLIENT_ID_HERE",
ClientSecret = "" //"PUT_CLIENT_SECRETS_HERE"
},
new[] { TasksService.Scope.Tasks },
"user",
CancellationToken.None).Result;
Related
I have an Angular 6 app that uses .net Core 2.x as backend
I have the External provider working for the explicit flow (lot of samples)
I use explicit flow since I do not whant to share the secret and client id with the web app.
I have a upload file service (domain.com/api/upload)
Witch works fine
Now I would like to save the file to a logged in user's google drive.
The google project has the google drive api permissions and all
But I can't get the drive api client to authenticate with the drive api
Controller action
private async Task<IFileStoreItem> SaveFile(IFormFile file, IFilePath path)
{
if (file == null) throw new Exception("File is null");
if (file.Length == 0) throw new Exception("File is empty");
if(path == null) throw new Exception("path is null");
IFileStoreItem item = file.Adapt<DocumentInfo>();
item.Container = path.Container;
item.Partition = path.Partition;
IFileStoreService fileStoreService = GetFileStoreService();
if (file.Length > 0)
{
using (Stream stream = new MemoryStream())
{
await file.CopyToAsync(stream);
item = await fileStoreService.Save(stream, item);
}
item.Link = Url.AbsoluteUri("DownloadFile", "File", new { container = item.Container, partition = item.Partition, id = item.Id });
}
return item;
}
Helper function
private IFileStoreService GetFileStoreService()
{
IFileStoreService ret = null;
string uploads = Path.Combine(_environment.WebRootPath, "uploads");
DocumentStorageConfiguration config = new StorageConfiguration().GetStoragetSettings();
ret = new GoogleDriveService(User.Claims.Where(c => c.Type == JwtRegisteredClaimNames.UniqueName).SingleOrDefault()?.Value);
return ret;
}
Drive service
public class GoogleDriveService : IFileStoreService
{
DriveService _service;
UserCredential credential;
public GoogleDriveService(string user)
{
string[] scopes = new string[] {
DriveService.Scope.Drive,
DriveService.Scope.DriveFile};
GoogleConfiguration config = new AuthentificationConfiguration().GetGoogleSettings();
var secrets = new ClientSecrets
{
ClientId = config.ClientId,
ClientSecret = config.ClientSecret
};
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(secrets, scopes, user, CancellationToken.None).Result;
_service = new DriveService(new Google.Apis.Services.BaseClientService.Initializer() {
HttpClientInitializer = credential
});
}
public async Task<IFileStoreItem> Save(System.IO.Stream stream, IFileStoreItem item)
{
File body = new File
{
Name = item.Name,
MimeType = item.ContentType,
Parents = new List<string>() { "Documents" }
};
FilesResource.CreateMediaUpload request = new FilesResource.CreateMediaUpload(_service,body,stream,item.ContentType);
IUploadProgress progress = await request.UploadAsync();
item.Id = body.Id;
return item;
}
}
The error I am getting is bad gateway 502
Question is if I can authenticate with google drive based on the currently logged in user (witch already is a google user)
I'm trying to use Google Calendar API v3, but i have problems while running the codes, it always gives me that error :
An exception of type 'System.AggregateException' occurred in mscorlib.ni.dll but was not handled in user code
Additional information: One or more errors occurred.
I don't know why it does, also It should work as well. Here is a screenshot for it :
Also my codes are :
UserCredential credential;
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new Uri("ms-appx:///Assets/client_secrets.json"),
Scopes,
"user",
CancellationToken.None).Result;
// Create Google Calendar API service.
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
var calendarService = new CalendarService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Windows 10 Calendar sample"
});
var calendarListResource = await calendarService.CalendarList.List().ExecuteAsync();
If you can at least help with calling it through REST API, that would be great too, but you must consider that it's UWP, so it has another way to get it work as well.
As i already tried through REST API, but i always get "Request error code 400".
Thanks for your attention.
The Google API Client Library for .NET does not support UWP by now. So we can't use Google.Apis.Calendar.v3 Client Library in UWP apps now. For more info, please see the similar question: Universal Windows Platform App with google calendar.
To use Google Calendar API in UWP, we can call it through REST API. To use the REST API, we need to authorize requests first. For how to authorize requests, please see Authorizing Requests to the Google Calendar API and Using OAuth 2.0 for Mobile and Desktop Applications.
After we have the access token, we can call Calendar API like following:
var clientId = "{Your Client Id}";
var redirectURI = "pw.oauth2:/oauth2redirect";
var scope = "https://www.googleapis.com/auth/calendar.readonly";
var SpotifyUrl = $"https://accounts.google.com/o/oauth2/auth?client_id={clientId}&redirect_uri={Uri.EscapeDataString(redirectURI)}&response_type=code&scope={Uri.EscapeDataString(scope)}";
var StartUri = new Uri(SpotifyUrl);
var EndUri = new Uri(redirectURI);
// Get Authorization code
WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(WebAuthenticationOptions.None, StartUri, EndUri);
if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success)
{
var decoder = new WwwFormUrlDecoder(new Uri(WebAuthenticationResult.ResponseData).Query);
if (decoder[0].Name != "code")
{
System.Diagnostics.Debug.WriteLine($"OAuth authorization error: {decoder.GetFirstValueByName("error")}.");
return;
}
var autorizationCode = decoder.GetFirstValueByName("code");
//Get Access Token
var pairs = new Dictionary<string, string>();
pairs.Add("code", autorizationCode);
pairs.Add("client_id", clientId);
pairs.Add("redirect_uri", redirectURI);
pairs.Add("grant_type", "authorization_code");
var formContent = new Windows.Web.Http.HttpFormUrlEncodedContent(pairs);
var client = new Windows.Web.Http.HttpClient();
var httpResponseMessage = await client.PostAsync(new Uri("https://www.googleapis.com/oauth2/v4/token"), formContent);
if (!httpResponseMessage.IsSuccessStatusCode)
{
System.Diagnostics.Debug.WriteLine($"OAuth authorization error: {httpResponseMessage.StatusCode}.");
return;
}
string jsonString = await httpResponseMessage.Content.ReadAsStringAsync();
var jsonObject = Windows.Data.Json.JsonObject.Parse(jsonString);
var accessToken = jsonObject["access_token"].GetString();
//Call Google Calendar API
using (var httpRequest = new Windows.Web.Http.HttpRequestMessage())
{
string calendarAPI = "https://www.googleapis.com/calendar/v3/users/me/calendarList";
httpRequest.Method = Windows.Web.Http.HttpMethod.Get;
httpRequest.RequestUri = new Uri(calendarAPI);
httpRequest.Headers.Authorization = new Windows.Web.Http.Headers.HttpCredentialsHeaderValue("Bearer", accessToken);
var response = await client.SendRequestAsync(httpRequest);
if (response.IsSuccessStatusCode)
{
var listString = await response.Content.ReadAsStringAsync();
//TODO
}
}
}
I have the Google .NET Client working in my UWP app. The trick is that you have to put it in a .NET Standard 2.0 Class Library, expose the API services you need, and then reference that library from your UWP app.
Also, you have to handle the getting the auth token yourself. It's not that much work and the Drive APIs and Calendar APIs work just fine (the only ones I've tried). You can see that I pass in a simple class that contains the auth token and other auth details to a method called Initialize.
Here is the single class I used in the .NET Standard 2.0 class library:
namespace GoogleProxy
{
public class GoogleService
{
public CalendarService calendarService { get; private set; }
public DriveService driveService { get; private set; }
public GoogleService()
{
}
public void Initialize(AuthResult authResult)
{
var credential = GetCredentialForApi(authResult);
var baseInitializer = new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "{your app name here}" };
calendarService = new Google.Apis.Calendar.v3.CalendarService(baseInitializer);
driveService = new Google.Apis.Drive.v3.DriveService(baseInitializer);
}
private UserCredential GetCredentialForApi(AuthResult authResult)
{
var initializer = new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "{your app client id here}",
ClientSecret = "",
},
Scopes = new string[] { "openid", "email", "profile", "https://www.googleapis.com/auth/calendar.readonly", "https://www.googleapis.com/auth/calendar.events.readonly", "https://www.googleapis.com/auth/drive.readonly" },
};
var flow = new GoogleAuthorizationCodeFlow(initializer);
var token = new TokenResponse()
{
AccessToken = authResult.AccessToken,
RefreshToken = authResult.RefreshToken,
ExpiresInSeconds = authResult.ExpirationInSeconds,
IdToken = authResult.IdToken,
IssuedUtc = authResult.IssueDateTime,
Scope = "openid email profile https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar.events.readonly https://www.googleapis.com/auth/drive.readonly",
TokenType = "bearer" };
return new UserCredential(flow, authResult.Id, token);
}
}
}
In order to get the Auth token from google, you have to use custom schemes. Register your app as an 'iOS' app on the google services console and put in a URI scheme (something unique). Then add this scheme to your UWP manifest under Declarations->Protocol. Handle it in your App.xaml.cs:
protected override void OnActivated(IActivatedEventArgs args)
{
base.OnActivated(args);
if (args.Kind == ActivationKind.Protocol)
{
ProtocolActivatedEventArgs protocolArgs = (ProtocolActivatedEventArgs)args;
Uri uri = protocolArgs.Uri;
Debug.WriteLine("Authorization Response: " + uri.AbsoluteUri);
locator.AccountsService.GoogleExternalAuthWait.Set(uri.Query);
}
}
That GoogleExternalAuthWait comes from some magical code I found about how to create an asynchronous ManualResetEvent. https://blogs.msdn.microsoft.com/pfxteam/2012/02/11/building-async-coordination-primitives-part-1-asyncmanualresetevent/ It looks like this (I only converted it to generic).
public class AsyncManualResetEvent<T>
{
private volatile TaskCompletionSource<T> m_tcs = new TaskCompletionSource<T>();
public Task<T> WaitAsync() { return m_tcs.Task; }
public void Set(T TResult) { m_tcs.TrySetResult(TResult); }
public bool IsReset => !m_tcs.Task.IsCompleted;
public void Reset()
{
while (true)
{
var tcs = m_tcs;
if (!tcs.Task.IsCompleted ||
Interlocked.CompareExchange(ref m_tcs, new TaskCompletionSource<T>(), tcs) == tcs)
return;
}
}
}
This is how you start the Google Authorization. What happens is it launches an external browser to begin the google signing process and then wait (that's what the AsyncManualResetEvent does). When you're done, Google will launch a URI using your custom scheme. You should get a message dialog saying the browser is trying to open an app... click ok and the AsyncManualResetEvent continues and finishes the auth process. You'll need to make a class that contains all the auth info to pass to your class library.
private async Task<AuthResult> AuthenticateGoogleAsync()
{
try
{
var stateGuid = Guid.NewGuid().ToString();
var expiration = DateTimeOffset.Now;
var url = $"{GoogleAuthorizationEndpoint}?client_id={WebUtility.UrlEncode(GoogleAccountClientId)}&redirect_uri={WebUtility.UrlEncode(GoogleRedirectURI)}&state={stateGuid}&scope={WebUtility.UrlEncode(GoogleScopes)}&display=popup&response_type=code";
var success = Windows.System.Launcher.LaunchUriAsync(new Uri(url));
GoogleExternalAuthWait = new AsyncManualResetEvent<string>();
var query = await GoogleExternalAuthWait.WaitAsync();
var dictionary = query.Substring(1).Split('&').ToDictionary(x => x.Split('=')[0], x => Uri.UnescapeDataString(x.Split('=')[1]));
if (dictionary.ContainsKey("error"))
{
return null;
}
if (!dictionary.ContainsKey("code") || !dictionary.ContainsKey("state"))
{
return null;
}
if (dictionary["state"] != stateGuid)
return null;
string tokenRequestBody = $"code={dictionary["code"]}&redirect_uri={Uri.EscapeDataString(GoogleRedirectURI)}&client_id={GoogleAccountClientId}&access_type=offline&scope=&grant_type=authorization_code";
StringContent content = new StringContent(tokenRequestBody, Encoding.UTF8, "application/x-www-form-urlencoded");
// Performs the authorization code exchange.
using (HttpClientHandler handler = new HttpClientHandler())
{
handler.AllowAutoRedirect = true;
using (HttpClient client = new HttpClient(handler))
{
HttpResponseMessage response = await client.PostAsync(GoogleTokenEndpoint, content);
if (response.IsSuccessStatusCode)
{
var stringResponse = await response.Content.ReadAsStringAsync();
var json = JObject.Parse(stringResponse);
var id = DecodeIdFromJWT((string)json["id_token"]);
var oauthToken = new AuthResult()
{
Provider = AccountType.Google,
AccessToken = (string)json["access_token"],
Expiration = DateTimeOffset.Now + TimeSpan.FromSeconds(int.Parse((string)json["expires_in"])),
Id = id,
IdToken = (string)json["id_token"],
ExpirationInSeconds = long.Parse((string)json["expires_in"]),
IssueDateTime = DateTime.Now,
RefreshToken = (string)json["refresh_token"]
};
return oauthToken;
}
else
{
return null;
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
Fundamentally, I'm not understanding something about OAuth, Google, and the Google Apis. I'm working the v3 library in Asp.Net Core 1.0. I use Google Authentication:
app.UseGoogleAuthentication(new GoogleOptions
{
ClientId = Configuration["Google:ClientId"],
ClientSecret = Configuration["Google:ClientSecret"],
Scope = {
"email",
"https://www.googleapis.com/auth/userinfo.email",
"profile",
"https://www.googleapis.com/auth/userinfo.profile",
"openid",
"https://www.googleapis.com/auth/calendar",
},
AccessType = "offline",
SaveTokens = true,
});
Simple enough. Then I want to use Google Calendar. However, I cannot consistently get back the Access/Refresh tokens (honestly at this point I'm not sure I understand what these are). I use this code to get back a Calendar Service from google:
private AuthorizationCodeFlow CreateFlow(IEnumerable<string> scopes)
{
return new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer()
{
ClientSecrets = new Google.Apis.Auth.OAuth2.ClientSecrets
{
ClientId = _ClientId,
ClientSecret = _ClientSecret
},
DataStore = new MemoryDataStore(),
Scopes = scopes
});
}
private async Task<UserCredential> CreateUserCredential(HttpContext context, string providerKey, IEnumerable<string> scopes)
{
var flow = CreateFlow(scopes);
var token = await context.GetGoogleTokenResponse();
UserCredential credential = new UserCredential(flow, providerKey, token);
return credential;
}
public async Task<CalendarService> CreateCalendarServiceAsync(HttpContext context, string providerKey)
{
if (string.IsNullOrWhiteSpace(providerKey)) return null;
if (context == null) return null;
var credential = await CreateUserCredential(context, providerKey, new[] { "https://www.googleapis.com/auth/calendar" });
CalendarService service = new CalendarService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = _ApplicationName,
});
return service;
}
public static async Task<TokenResponse> GetGoogleTokenResponse(this HttpContext context)
{
var info = await context.Authentication.GetAuthenticateInfoAsync("Google");
if (info == null) return null;
var token = new TokenResponse
{
AccessToken = info.Properties.Items[".Token.access_token"],
RefreshToken = info.Properties.Items[".Token.refresh_token"],
TokenType = info.Properties.Items[".Token.token_type"],
Issued = DateTime.Parse(info.Properties.Items[".issued"]),
};
return token;
}
This is the only way I know how to get back the current access/refresh tokens. What am I missing. Sometimes they exist, others times not. Documentation for the .Net Core 1.0 version is slim at best. Any help on a better way to access Google Apis via Asp.Net core?
Since you already set SaveTokens = true, you can get access_token like this: await context.Authentication.GetTokenAsync("access_token");
So changing your method like below probably solves your problem:
private async Task<UserCredential> CreateUserCredential(HttpContext context, string providerKey, IEnumerable<string> scopes)
{
var flow = CreateFlow(scopes);
var token = await context.Authentication.GetTokenAsync("access_token");
UserCredential credential = new UserCredential(flow, providerKey, token);
return credential;
}
It looks like the Application object in Microsoft.Azure.ActiveDirectory.GraphClient allows a Webapplication to be created. I cannot see how I can use this to create a new Native application.
thanks
Updates:
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
tcs.SetResult(accessToken);
var graphClient = new ActiveDirectoryClient(
new Uri($"{GraphApiBaseUrl}{tenantId}"),
async () => { return await tcs.Task; });
var password = Guid.NewGuid().ToString("N");
var cred = new PasswordCredential()
{
StartDate = DateTime.UtcNow,
EndDate = DateTime.UtcNow.AddYears(1),
Value = password
};
var app = await GetApplicationByUrlAsync(accessToken, tenantId, appName, identifierUrl);
if(app == null)
{
app = new Application()
{
DisplayName = appName,
Homepage = homePageUrl,
IdentifierUris = new List<string>() { identifierUrl },
LogoutUrl = logoutUrl,
ReplyUrls = new List<string>() { replyUrl },
PasswordCredentials = new List<PasswordCredential>() { cred },
};
await graphClient.Applications.AddApplicationAsync(app);
}
The fact that an app is a native client application is identified by the PublicClient boolean property on the Application object. (See client types from the OAuth 2.0 spec.)
So, you could register a native client app with the following code:
var app = new Application()
{
DisplayName = "My native client app",
ReplyUrls = new List<string>() { "urn:ietf:wg:oauth:2.0:oob" },
PublicClient = true
};
await graphClient.Applications.AddApplicationAsync(app);
Console.WriteLine("App created. AppId: {0}, ObjectId: {1}", app.AppId, app.ObjectId);
Note that the native client app does not have password credentials or key credentials (or any other secret).
Details about these and other properties of Application objects are available in the API reference documentation: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#application-entity
I'm following this tutorial: https://developers.google.com/google-apps/calendar/instantiate
My code:
public static void Main()
{
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets()
{
ClientId = "actualclientid",
ClientSecret = "actualclientsecret"
},
new[] { CalendarService.Scope.Calendar },
"user",
CancellationToken.None).Result;
The issue is, this part of the code throws me an exception:
{"Could not load file or assembly
'Microsoft.Threading.Tasks.Extensions.Desktop, Version=1.0.16.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its
dependencies. The system cannot find the file
specified.":"Microsoft.Threading.Tasks.Extensions.Desktop,
Version=1.0.16.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"}
PS.: While most likely irrelevant to the issue, when setting up my project on google to get the credentials, I've selected Installed Application -> Other (As I'm assuming that's what a console application is)
EDIT: Adding https://www.nuget.org/packages/Microsoft.Bcl.Async/1.0.166-beta seems to have solved that issue. Now the remained of my code:
var service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar API Test"
});
var x = service.Events.List("actualcalendarid").OauthToken;
Console.WriteLine(x);
Console.ReadLine();
returns an empty line, even though when I run the application it does request access to my calendar and such. Am I forgetting something?
Make sure you have added all the references to your project.
The following need to be installed using NuGet
-Install-Package Google.Apis.Calendar.v3 –Pre
-Install-Package Google.Apis -Pre
-Install-Package DotNetOpenAuth -Version 4.3.4.13329
-Install-Package Google.Apis.Auth.Mvc -Pre
And add reference Microsoft.Threading.Tasks.Extensions to your project.
EDIT:
You don't retrieve data because you are not executing your query.
var result = service.Events.List("primary").Execute();
private async Task<UserCredential> GetCredential()
{
UserCredential credential = null;
try
{
using(var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { CalendarService.Scope.Calendar },
"user", CancellationToken.None, new FileDataStore(""));
}
}
catch (IOException ioe)
{
Debug.WriteLine("IOException" + ioe.Message);
}
catch (Exception ex)
{
Debug.WriteLine("Exception" + ex);
}
return credential;
}
private CalendarService GetCalenderService(UserCredential credential)
{
CalendarService service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Calendar Sample"
});
return service;
}
private Events GetEvent(string CalendarId)
{
var query = this.Service.Events.List(CalendarId);
query.ShowDeleted = false;
query.SingleEvents = true;
return query.Execute();
}