Reputation: 43
We have tested demo code of Google Drive (for console application) and that went correct, after that we are trying to implement the same to Web Application which at present is hosted at localhost. The application is giving us this exception:
An exception of type 'System.InvalidOperationException' occurred in Google.Apis.Auth.dll but was not handled in user code Additional information: At least one client secrets (Installed or Web) should be set
The code we are trying to run is this:
UserCredential credential;
GoogleClientSecrets s= new GoogleClientSecrets();
s.Secrets.ClientId="xxxxxxxxxx-xxxxxxxx.apps.googleusercontent.com";
s.Secrets.ClientSecret="yyyyyyyyyyyyyyyyyyyyy";
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(s.Secrets,Scopes,"user",CancellationToken.None,null).Result;
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
//ApplicationName = ApplicationName,
});
Before this we have put refresh token to get access token. We are also not aware what to do with this access token stores in a string variable.
We are trying to have it accessed unattanded, we used google playground to get first refresh token.
Please help us out, we are trying to get it done from last 7 days with no success.
Upvotes: 0
Views: 3963
Reputation: 117331
Code for a service account:
string[] scopes = new string[] {DriveService.Scope.Drive}; // Full access
var keyFilePath = @"c:\file.p12" ; // Downloaded from https://console.developers.google.com
var serviceAccountEmail = "[email protected]"; // found https://console.developers.google.com
//loading the Key file
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail) {
Scopes = scopes}.FromCertificate(certificate));
code ripped from Google Drive Authentication C# which also incudes an example for using Oauth2
Upload file
/// <summary>
/// Uploads a file
/// Documentation: https://developers.google.com/drive/v2/reference/files/insert
/// </summary>
/// <param name="_service">a Valid authenticated DriveService</param>
/// <param name="_uploadFile">path to the file to upload</param>
/// <param name="_parent">Collection of parent folders which contain this file.
/// Setting this field will put the file in all of the provided folders. root folder.</param>
/// <returns>If upload succeeded returns the File resource of the uploaded file
/// If the upload fails returns null</returns>
public static File uploadFile(DriveService _service, string _uploadFile, string _parent) {
if (System.IO.File.Exists(_uploadFile))
{
File body = new File();
body.Title = System.IO.Path.GetFileName(_uploadFile);
body.Description = "File uploaded by Diamto Drive Sample";
body.MimeType = GetMimeType(_uploadFile);
body.Parents = new List<ParentReference>() { new ParentReference() { Id = _parent } };
// File's content.
byte[] byteArray = System.IO.File.ReadAllBytes(_uploadFile);
System.IO.MemoryStream stream = new System.IO.MemoryStream(byteArray);
try
{
FilesResource.InsertMediaUpload request = _service.Files.Insert(body, stream, GetMimeType(_uploadFile));
//request.Convert = true; // uncomment this line if you want files to be converted to Drive format
request.Upload();
return request.ResponseBody;
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
return null;
}
}
else {
Console.WriteLine("File does not exist: " + _uploadFile);
return null;
}
}
Code ripped from DaimtoGoogleDriveHelper.cs
Tip:
The thing to remember with a service account is that it is not you, it is a dummy user account. A service account has its own google drive account so uploading files to it will upload to its account not yours. What you can do is take the service account email address add it as a user on a folder in YOUR personal google drive account giving it write access. This will then allow the Service account to upload a file to your personal google drive account. Remember to patch the file after upload granting yourself permissions to the file other wise the owner of the file will be the service account. There is currently a bug in the Google Drive api you have to patch the permissions on the file after you upload the file you cant do it at the time you upload it its a two step process. (been there done that)
Google drive sample project can be found on GitHub
Upvotes: 3