Google Drive Api. How to get Free Space - google-api

In my project I use Google Drive API Android, now I need to know the free space.
How to get free space in Google Drive with using Google Drive API?
What should I do to get free space???
I think use it: https://developers.google.com/drive/api/v3/reference/about
but I do not understand how.

For C# admin-sdk, here is how to get it
GoogleCredential credential;
using (var stream = new FileStream(Path.Combine(AppContext.BaseDirectory,
"service_account_creds.json"), FileMode.Open, FileAccess.Read))
{
var scopes = new[] { DriveService.Scope.Drive };
credential = GoogleCredential.FromStream(stream).CreateScoped(scopes);
}
var _service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "My Application Name",
});
var aboutRequest = _service.About.Get();
aboutRequest.Fields = "storageQuota";
var about = aboutRequest.Execute();
long usedBytes = about.StorageQuota.Usage.Value;
long totalBytes = about.StorageQuota.Limit.Value;

Related

Google.APIs Change Group Owner

Looking for the proper code to change a Google email group's owner...
what I have currently (not working). The credential/service are all fine, as I'm using them to do a bunch of other GoogleAPIs stuff which is working correctly. I'm just not sure whether I should be messing with a user or the group.
String serviceAccountEmail = "asdfasdfasf#asdfasdfsdfsdf-323423.iam.gserviceaccount.com";
var certificate = new X509Certificate2(#"c:\asdf\PasswordReset2.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
User = "andy#asdfasdfa.com",
Scopes = new[] { DirectoryService.Scope.AdminDirectoryUser, DirectoryService.Scope.AdminDirectoryGroup }
}.FromCertificate(certificate));
var service = new DirectoryService
(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "jimmyjohn",
ApiKey = "asdkfjasl;dkjfaskdjfasdfasdf"
}
);
Group g = new Group();
g = service.Groups.Get(groupemail).Execute();
// NEED HELP HERE
service.Groups.Update(g, groupemail).Execute();
//Member newMember = new Member();
//newMember.Email = useremail;
//newMember.Role = "OWNER"; //MANAGER , OWNER
//newMember.Kind = "admin#directory#member";
//service.Members.Update(newMember, groupemail, useremail).Execute();```
I already had the answer, but due to a facepalm bug I was always telling it to set the owner to myself (in a previous function feeding this one), hence never seeing anything change in Google Groups...
Member newMember = new Member
{
Email = useremail,
Role = "OWNER" //MANAGER , OWNER
};
service.Members.Update(newMember, groupemail, useremail).Execute();

Using Google.Apis.Core for .NET Core, why can't i see a list of photos in my Google Photos when I specify spaces="photos"?

Sample code goes like this:
static string[] Scopes = { DriveService.Scope.Drive, DriveService.Scope.DrivePhotosReadonly };
static string ApplicationName = "Quickstart";
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;
}
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
// Define parameters of request.
FilesResource.ListRequest listRequest = service.Files.List();
listRequest.Spaces = "photos";
listRequest.PageSize = 100;
listRequest.Fields = "nextPageToken, files(id, name)";
// List files.
IList<Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;
Console.WriteLine("Files:");
if (files != null && files.Count > 0)
{
foreach (var file in files)
{
Console.WriteLine("{0} ({1})", file.Name, file.Id);
}
}
else
{
Console.WriteLine("No files found.");
}
Console.Read();
I enable the Google Drive API through the Google Console and get the credentials.json file. When I run this using listRequest.Spaces = "drive" then I can see all of my drive files, but I cannot see any photos when I make it "photos".
What other sort of undocumented magic needs to be in place here for this to work?
Thanks.
Google Drive and Google Photos have been disconnected, the space "photos" has been deprecated.
However, there is a Google Photos API that allows you to list your photos.

Creating Excel files directly on blob

I have following function which works fine when saving to disk. I am executing the code from an Azure function. Is there anyway to to write to a blob storage instead without saving to disk?
private void ExportDataSet(DataTable ds, string destination)
{
using (var workbook = SpreadsheetDocument.Create(destination, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
var workbookPart = workbook.AddWorkbookPart();
workbook.WorkbookPart.Workbook = new DocumentFormat.OpenXml.Spreadsheet.Workbook();
workbook.WorkbookPart.Workbook.Sheets = new DocumentFormat.OpenXml.Spreadsheet.Sheets();
var sheetPart = workbook.WorkbookPart.AddNewPart<WorksheetPart>();
var sheetData = new DocumentFormat.OpenXml.Spreadsheet.SheetData();
sheetPart.Worksheet = new DocumentFormat.OpenXml.Spreadsheet.Worksheet(sheetData);
DocumentFormat.OpenXml.Spreadsheet.Sheets sheets = workbook.WorkbookPart.Workbook.GetFirstChild<DocumentFormat.OpenXml.Spreadsheet.Sheets>();
string relationshipId = workbook.WorkbookPart.GetIdOfPart(sheetPart);
uint sheetId = 1;
if (sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Count() > 0)
{
sheetId =
sheets.Elements<DocumentFormat.OpenXml.Spreadsheet.Sheet>().Select(s => s.SheetId.Value).Max() + 1;
}
DocumentFormat.OpenXml.Spreadsheet.Sheet sheet = new DocumentFormat.OpenXml.Spreadsheet.Sheet() { Id = relationshipId, SheetId = sheetId, Name = "Sites" };
sheets.Append(sheet);
DocumentFormat.OpenXml.Spreadsheet.Row headerRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
List<String> columns = new List<string>();
foreach (System.Data.DataColumn column in ds.Columns)
{
columns.Add(column.ColumnName);
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(column.ColumnName);
headerRow.AppendChild(cell);
}
sheetData.AppendChild(headerRow);
foreach (System.Data.DataRow dsrow in ds.Rows)
{
DocumentFormat.OpenXml.Spreadsheet.Row newRow = new DocumentFormat.OpenXml.Spreadsheet.Row();
foreach (String col in columns)
{
DocumentFormat.OpenXml.Spreadsheet.Cell cell = new DocumentFormat.OpenXml.Spreadsheet.Cell();
cell.DataType = DocumentFormat.OpenXml.Spreadsheet.CellValues.String;
cell.CellValue = new DocumentFormat.OpenXml.Spreadsheet.CellValue(dsrow[col].ToString()); //
newRow.AppendChild(cell);
}
sheetData.AppendChild(newRow);
}
}
}
I would expect you maybe could save to a Stream?
Save to stream is the solution if you don't like to save it to a disk(In azure function, you can save it to a disk in azure function kudu like D:\home etc.).
If you choose to save to stream, just a few changes to your code, like below:
private void ExportDataSet(DataTable ds, MemoryStream memoryStream)
{
using (var workbook = SpreadsheetDocument.Create(memoryStream, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
{
//your code logic here
}
//here, the code to upload to azure blob storage.
CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("test1");
CloudBlockBlob myblob = cloudBlobContainer.GetBlockBlobReference("myexcel.xlsx");
//upload to blob storage
memoryStream.Position = 0;
myblob.UploadFromStream(memoryStream)
//or you can use Asnyc mehtod like myblob.UploadFromStreamAsync(memoryStream)
}
Note: if you're using the latest azure blob storage sdk Microsoft.Azure.Storage.Blob, version 9.4.0 or later, you can use either UploadFromStreamAsync or UploadFromStream method in azure function v2.

CreateChooser is not working in Android v5.1

I am using intent to share pdf files. I am restricting apps when share file. I want to share the file to Good document, Kindle and drop box alone. I am using the below code to achieve this.But the below code is not working in android v5.1. The device have the required app to share. But it is showing "No apps can perform this action" when share. Can you anyone suggest your ideas to resolve this?
var pathFile = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var m_documentMobiNames = shortName + "." + fileType;
var mobileFileName = Path.Combine(pathFile, m_documentMobiNames);
var shareIntentsLists = new List<Intent>();
Intent sendIntent = new Intent();
sendIntent.SetAction(Intent.ActionSend);
sendIntent.SetType("application/pdf");
var resInfos = context.PackageManager.QueryIntentActivities(sendIntent, 0);
if (resInfos.Count > 0)
{
foreach (var resInfo in resInfos)
{
string packageName = resInfo.ActivityInfo.PackageName;
if (packageName.Contains("com.google.android.apps.docs") || packageName.Contains("com.dropbox.android") || packageName.Contains("com.amazon.kindle"))
{
Intent intent = new Intent();
intent.SetComponent(new ComponentName(packageName, resInfo.ActivityInfo.Name));
intent.SetAction(Intent.ActionSend);
intent.SetType("application/pdf");
intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file://" + mobileFileName));
intent.SetPackage(packageName);
shareIntentsLists.Add(intent);
}
}
}
if (shareIntentsLists.Count > 0)
{
chooserIntent = Intent.CreateChooser(new Intent(), "Share with");
chooserIntent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse(mobileFileName));
chooserIntent.PutExtra(Intent.ExtraInitialIntents, shareIntentsLists.ToArray());
chooserIntent.SetFlags(ActivityFlags.ClearTop);
chooserIntent.SetFlags(ActivityFlags.NewTask);
context.StartActivity(chooserIntent);
await Task.FromResult(true);
}

How to get YouTube channel name and URL after authenticating

Once I have authenticated a user - such as in the code below - how can I find out their channel name and URL of channel?
I'm using the YouTube data api v3 with .NET library:
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.YoutubeReadonly },
"user",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = this.GetType().ToString()
});
Finally worked out how to do it. Once you get the token back from the authentication do this:
var channelsListRequest = _youTubeService.Channels.List("id,snippet");
channelsListRequest.Mine = true;
var channelsListResponse = channelsListRequest.Execute();
if ( (null != channelsListResponse) &&
(null != channelsListResponse.Items) &&
(channelsListResponse.Items.Count > 0) )
{
Channel userChannel = channelsListResponse.Items[0];
string youtubeUserID = userChannel.Id;
string ytChannelURL = "https://www.youtube.com/channel/" + userChannel.Id;
string name = userChannel.Snippet.Title;
}
Phew!

Resources