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"? - google-api

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.

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();

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.

Google Drive Api. How to get Free Space

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;

Android post image to Facebook comment

This is a followup to my previous question: Xamarin.Forms App return data to calling App
That works perfectly and I can share images to anywhere, except to Facebook comments. When I click the camera on the content box the app can be selected, I can select the image, Set result and Finish are called, and the app closes and it sends data to Facebook, and then however I then get the error : The image could not be uploaded, try again?
I can't find any fundamental differences between posting to a status or a comment, so I'm guessing it's subtle. Any thoughts on how I can change my intent to post properly?
Adding for completeness:
Bitmap b = null;
string url;
if (!string.IsNullOrEmpty(this.saleItems[i].ImageUrl))
{
url = this.saleItems[i].ImageUrl;
}
else
{
url = await FileHelper.GetLocalFilePathAsync(this.saleItems[i].Id);
}
//download
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
b = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
//set local path
var tempFilename = "test.png";
var sdCardPath = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filePath = System.IO.Path.Combine(sdCardPath, tempFilename);
using (var os = new FileStream(filePath, FileMode.Create))
{
b.Compress(Bitmap.CompressFormat.Png, 100, os);
}
b.Dispose();
var imageUri = Android.Net.Uri.Parse($"file://{sdCardPath}/{tempFilename}");
var sharingIntent = new Intent();
sharingIntent.SetAction(Intent.ActionSend);
sharingIntent.SetType("image/*");
sharingIntent.PutExtra(Intent.ExtraText, "some txt content");
sharingIntent.PutExtra(Intent.ExtraStream, imageUri);
sharingIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
//await SaleItemDataService.Instance.BuySaleItemAsync(this.saleItem);
SetResult(Result.Ok, sharingIntent);
Finish();
Use below:
Intent sharingIntent = new Intent();
string imageUri = "file://" + requestedUri;
sharingIntent.SetData(Android.Net.Uri.Parse(imageUri));

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