TeamDrive in Google Drive API - c#

I'm trying the code below, obtained from their docs here. I'm unable to compile, I get an exception message:
Maybe I'm not understanding the TeamDrive concept correctly?
I'm not sure where the issue is. Below is the code snippet I have:
var teamDriveMetadata = new TeamDrive()
{
Name = "Project Resources"
};
var requestId = System.Guid.NewGuid().ToString();
var request = service.Teamdrives.Create(teamDriveMetadata, requestId);
request.Fields = "id";
var teamDrive = request.Execute();
Console.WriteLine("Team Drive ID: " + teamDrive.Id);
Console.WriteLine("Done.");
Console.Read();
Below is the auth setup:
using (var stream =
new FileStream("client_secret.json", FileMode.Open, FileAccess.ReadWrite))
{
string credPath = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"MyKey",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName
});

FYI: I ran the sample code linked without issue. I have a test project that has the proper permissions already established. I pasted the linked code into that project, and had to resolve "var request" conflicting with the same in my existing code. Once resolved the code ran without issue.
As previously suggested I would recommend focusing on resolving your permissions/scopes.

Related

c# Google.Apis.Gmail GmailService delete message

I have problem with delete message from gmail server using google.apis
I can login and read messages but when I use
GmailService.Users.Messages.Delete("my-email#gmail.com", email.Id);
GmailService.Users.Threads.Delete("my-email#gmail.com", email.ThreadId);
i only delete message 'localy' in instance GmailService. When I repeat checking mail, messagess still they are...
email.Id and email.ThreadId are ok, I can read messages.
I have fully rights. When I loading .json (first clean run) to authorize, gmail give me a full access.
"Read, compose, send and permanently delete all emails from Gmail."
Any ideas? Some code..
private static readonly string[] Scopes = { GmailService.Scope.MailGoogleCom};
....
GmailService GmailService = new();
using (FileStream stream = new("client_secret.json", FileMode.Open, FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = System.IO.Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");
UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromStream(stream).Secrets, Scopes, "ma-email#gmail.com", CancellationToken.None, new FileDataStore(credPath, true)).Result;
this.GmailService = new(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "AppName"
});
}
...
UsersResource.MessagesResource.ListRequest inboxlistRequest = GmailService.Users.Messages.List("my-email#gmail.com");
inboxlistRequest.LabelIds = "INBOX";
inboxlistRequest.IncludeSpamTrash = false;
ListMessagesResponse EmailListResponse = inboxlistRequest.Execute();
So i have 'email.Id' and 'email.ThreadId', but why i can't pernamently delete these messagess?
Any ideas?
These calls:
GmailService.Users.Messages.Delete("my-email#gmail.com", email.Id);
GmailService.Users.Threads.Delete("my-email#gmail.com", email.ThreadId);
... create requests, but don't execute them. Try:
GmailService.Users.Messages.Delete("my-email#gmail.com", email.Id).Execute();
GmailService.Users.Threads.Delete("my-email#gmail.com", email.ThreadId).Execute();

Get account name or email when using Google Drive Rest API in C# app

I'm new to C# and I'm creating a WPF C# app. I want use Google Drive Rest API to send backup file to Google Drive. But this isn't problem. When I wrote Android app in Java, getting account name was very easy. But in C# and my desktop app, I don't now how do this. I read many topic and Google documentation, but I didn't find answer.
Here is my code for Helper class. I only want to get the account name or address and display it in the main window.
I found a solution with Google+ API, but now it doesn't work because Google+ doesn't exist.
Is there any way to do this?
UserCredential credential;
public DriveService GetGoogleDriveService()
{
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 = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/menadzer_zespolow_token.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
return service;
}
}
public String GetAccountEmail()
{
// code to get account name or email there
return accountNameOrEmail;
}

Error when login to Gmail with Imap client using Gmail API C#

im working on a project that need to access Gmail using Gmail API .
but i keep getting this error when trying to login Imap:
{"status":"400","schemes":"Bearer","scope":"https://mail.google.com/"}
i sew here OAuth 2 SASL string error ,that someone asked about this issue and said that it solved by puting the right token scope
in my case it didnt work , the error is still popping .
static string[] Scopes = { GmailService.Scope.GmailReadonly };
static string ApplicationName = "Gmail API .NET Quickstart";
static void Main(string[] args)
{
UserCredential credential;
using (var stream =
new FileStream("client_secret.json", FileMode.Open,FileAccess.Read))
{
string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets, Scopes, "Sapir", CancellationToken.None, new FileDataStore(credPath, true)).Result;
Console.WriteLine("Credential file saved to: " + credPath);
}
// Create Gmail API service.
var service = new GmailService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");
credential.Token.Scope = "https://mail.google.com/";
ImapClient ic = new ImapClient("imap.gmail.com","astechnetivot#gmail.com", credential.Token.AccessToken,AuthMethods.SaslOAuth, 993, true);
ic.SelectMailbox("INBOX");
Console.WriteLine(ic.GetMessageCount());
MailMessage[] mm = ic.GetMessages(0, 1);
foreach (MailMessage m in mm)
{
Console.WriteLine(m.Subject + " " + m.Date.ToString());
}
ic.Dispose();
Console.Read();
}
Error message seems to happen when you use an expired access token, check your access token and make sure that it is not expired. Here's a related issue having status 400: Gmail XOAUTH 2.0, IMAP AUTHENTICATE returns "status":"400"

Authentication using Google API v3 OAuth 2.0 for Blogger API using C#

I'm working on an Web application to post blogs to blogger.com. I referenced Blogger API v3 client library and Google Oauth 2.0 to my project. Also created Credentials on Google Console.
Now i have Client ID,Client secret and API Key. I have given Redirect URIs as http://Localhost and http://localhost:52892.
I'm using .JSON file.
My code is Here:
using (var stream = new FileStream(Server.MapPath("~/client_secret.json"), FileMode.Open,FileAccess.Read))
{
//string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string credPath = Server.MapPath("~/Credentials");
credPath = Path.Combine(credPath, ".credentials");
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
Scopes,
"user",
CancellationToken.None,
new FileDataStore(credPath, true)).Result;
lblBlogTitle.Text = "Credential File Saved to :"+credPath;
}
// Create Blogger API service.
var service = new BloggerService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
// get blog by ID
BlogsResource.GetRequest blogByID = service.Blogs.Get("BlogID");
// List blog by name.
//IList<Google.Apis.Blogger.v3.Data.Blog> blogs =
string blogName = blogByID.Execute().Name;
lblNoti.Text = blogName;
Can some please tell me where i'm missing? I'm new to DotNet. Code level answer with a description will be very helpful for me.
Thanks in Advance!!

How do you create a new Google Drive Service in C# using OAuth

I'm trying to write a simple command line application that will upload a file to Google Drive. I'm following along with the steps provided here: https://developers.google.com/drive/web/quickstart/quickstart-cs
The sample code they provide doesn't compile, specifically the line:
var service = new DriveService(new BaseClientService.Initializer()
{
Authenticator = auth
});
This returns the error:
"'Google.Apis.Services.BaseClientService.Initalizer' does not contain a definition for 'Authenticator'"
obviously the APIs have changed but I can't find the new way to do this.
First off you are missing the autentication code. Also the tutorial you are refering to uses an older version of the libary if you are using apis.drive.v2 that wont work. This one works with the newer libarys: My Tutorial Google Drive api C# (there is also a winform sample project)
But heres some Examples of how you can get it working:
UserCredential credential;
credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets { ClientId = "YourClientId", ClientSecret = "YourClientSecret" },
new[] { DriveService.Scope.Drive,
DriveService.Scope.DriveFile },
"user",
CancellationToken.None,
new FileDataStore("Drive.Auth.Store")).Result; }
The code above will get you the User Credentials. It pops up a new browser window asking the user to autorise your app. My Tutorial here
BaseClientService service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Drive API Sample",
});
The code above allow you to access the Drive Service. See how we send it the credential that we got from the Oauth call? Then to upload its a matter of calling service.files.insert
// File's metadata.
File body = new File();
body.Title = "NewDirectory2";
body.Description = "Test Directory";
body.MimeType = "application/vnd.google-apps.folder";
body.Parents = new List<ParentReference>() { new ParentReference() { Id = "root" } };
try
{
FilesResource.InsertRequest request = service.Files.Insert(body);
request.Execute();
}
catch (Exception e)
{
Console.WriteLine("An error occurred: " + e.Message);
}

Categories

Resources