How to upload videos to YouTube [Xamarin.Forms (Portable) ] - google-api

I am trying to upload videos to YouTube but somehow it's not working in Xamarin.Forms (Portable) project. Is there any way to upload the Videos in YouTube through Xamarin.Forms (Portable)
var initializer = new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = Constants.API.Google.ClientID,
ClientSecret = Constants.API.Google.ClientSecret
},
Scopes = new[] { YouTubeService.Scope.Youtube }
};
var flow = new AuthorizationCodeFlow(initializer);
TokenResponse token = flow.LoadTokenAsync("user", CancellationToken.None).Result;
but every time I am getting null in TokenResponse token, I am not sure what should I pass in place of user in flow.LoadTokenAsync("user", CancellationToken.None)
Thank You.

As I had feared the Google .Net client library does not currently support Xamarin. Please see issue: Unable to Google.Apis.Auth.PlatformServices in Xamarin.Forms
It's because GoogleWebAuthorizationBroker requires several classes from Google.Apis.Auth.PlatformServices, and Google.Apis.Auth.PlatformServices is not compatible with Xamarin.

Related

How can i upload a media file to my google drive using google api?

Hey im trying to upload certain media files to my google drive using google api services can someone please tell me how can i do it, in my previous question i have given the code for getservice and clientservice you could refer to that thankyou
Uploading a file to Google drive is reasonably strait forward.
authorize the user.
create the file metadata
upload the file data itself
I have serval tutorials on this topic and a YouTube video This should get you started.
How to upload a file to Google Drive with C# .net
using Google.Apis.Auth.OAuth2;
using Google.Apis.Drive.v3;
using Google.Apis.Services;
using Google.Apis.Upload;
Console.WriteLine("Hello, World!");
// Installed file credentials from google developer console.
const string credentialsJson = #"C:\Development\FreeLance\GoogleSamples\Credentials\credentials.json";
// used to store authorization credentials.
var userName = "user";
// scope of authorization needed from the user
var scopes = new[] { DriveService.Scope.Drive };
// file to upload
var filePath = #"C:\Development\FreeLance\GoogleSamples\Data\image.png";
var fileName = Path.GetFileName(filePath);
var folderToUploadTo = "1hwRZWAi-OznYGL51Yx9BJmDp5Ayips16";
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.FromFile(credentialsJson).Secrets,
scopes,
userName,
CancellationToken.None).Result;
// Create the Drive service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Daimto Drive upload Quickstart"
});
// Upload file photo.jpg on drive.
var fileMetadata = new Google.Apis.Drive.v3.Data.File()
{
Name = fileName,
Parents = new List<string>() { folderToUploadTo }
};
var fsSource = File.OpenRead(filePath);
// Create a new file, with metadatafileName and stream.
var request = service.Files.Create(fileMetadata, fsSource, "image/jpeg");
request.Fields = "id";
var results = await request.UploadAsync(CancellationToken.None);
if (results.Status == UploadStatus.Failed)
{
Console.WriteLine($"Error uploading file: {results.Exception.Message}");
}
// the file id of the new file we created
var fileId = request.ResponseBody?.Id;
Console.WriteLine($"fileId {fileId}");
Console.ReadLine();

Adaptive Cards: Payment Request

I am currently working on a bot project where i am trying to utilize Microsoft adaptive cards to try send a PaymentRequest to the user. I created a dummy paymentrequest object and inserted it into a Hero card like the documentation says.
var methodList = new List<PaymentMethodData>();
var method = new PaymentMethodData()
{Data = new {supportedNetworks = new[] { "visa", "mastercard", "amex", "discover", "diners", "jcb", "unionpay"} }, SupportedMethods = new[] { "https://bobpay.xyz/pay" } };
methodList.Add(method);
var details = new PaymentDetails {};
var test = new PaymentRequest(null, methodList, details);
var heroCard = new HeroCard
{
Title = "Bob",
Subtitle = "The Builder",
Text = "Kunnen wij het maken!",
Images = new List<CardImage>
{
new CardImage
{
Url = "https://m.media-amazon.com/images/M/MV5BNjRlYjgwMWMtNDFmMy00OWQ0LWFhMTMtNWE3MTU4ZjQ3MjgyXkEyXkFqcGdeQXVyNzU1NzE3NTg#._V1_CR0,45,480,270_AL_UX477_CR0,0,477,268_AL_.jpg"
}
},
Buttons = new List<CardAction>
{
new CardAction
{
Title = "Buy",
Type = PaymentRequest.PaymentActionType,
Value = test,
}
}
};
replyMessage.Attachments.Add(heroCard.ToAttachment());
await context.PostAsync(replyMessage);
I took out a bunch of parameters from the PaymentRequest constructor because i was experimenting with trying to get some kind of feedback. With this i get back nothing but this url which crashed the browser when i try to run it.
"content": {
"buttons": [
{
"title": "Buy",
"type": "openUrl",
"value": "payment://{\"methodData\":[{\"supportedMethods\":[\"https://bobpay.xyz/pay\"],\"data\":{}}],\"details\":{}}"
}
],
I can't find any documentation on how to do this properly but it doesnt seem to say it is deprecated on the documention. I am using bot framework v3 if that helps. I feel like even without some parameters in the PaymentRequest it should still give me something when i click the button.
As stated in this documentation: bot-builder-dotnet-request-payment In order to use the Bot Builder Payments library, you must first:
Create and activate a Stripe account if you don't have one already.
Sign in to Seller Center with your Microsoft account.
Within Seller Center, connect your account with Stripe.
Within Seller Center, navigate to the Dashboard and copy the value of
MerchantID.
Update your bot's Web.config file to set MerchantId to the value that
you copied from the Seller Center Dashboard.
At this time, the Bot Framework SDK supports only Stripe payments directly. If you are using some other provider, you will need to add support for it manually.
Also note: as of 2.25.2019, Bot Builder V4 sdk does not have payments support built in. The Bot Builder V3 sdk does: https://github.com/Microsoft/BotBuilder-Samples/tree/v3-sdk-samples/CSharp/sample-payments (Also, the Bot Framework Emulator V4 does not yet support payments: https://github.com/Microsoft/BotFramework-Emulator/issues/1324 The V3 emulator can be downloaded from here: https://github.com/Microsoft/BotFramework-Emulator/releases/tag/v3.5.37 )

Cloud AutoML API has not been used in project 618104708054 before or it is disabled

I am trying to build a .NET small app to predict images using my model that was trianed on AutoML.
But I am getting this error:
Cloud AutoML API has not been used in project 618104708054 before or
it is disabled. Enable it by visiting
https://console.developers.google.com/apis/api/automl.googleapis.com/overview?project=618104708054
then retry. If you enabled this API recently, wait a few minutes for
the action to propagate to our systems and retry
First - this is not the project I am using.
Second - If I go to the link with my real project id - it says to me that the api is working well.
My code look like these:
public static string SendPOST(string url, string json)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
httpWebRequest.Headers.Add("Authorization", "Bearer GOOGLE_CLOUD_TOKEN");
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
//var res = new JavaScriptSerializer().Deserialize<Response>(result);
//return res;
return result;
}
}
I will appriciate your help,
Thanks.
I finally succeded to make it, the only issue is that I needed to create a service account using the web console:
https://console.cloud.google.com/projectselector/iam-admin/serviceaccounts?supportedpurview=project&project=&folder=&organizationId=
And then to download the json key and push it via the gcloud command from my PC -
gcloud auth activate-service-account --key-file="[/PATH/TO/KEY/FILE.json]
I found the solution in this post:
"(403) Forbidden" when trying to send an image to my custom AutoML model via the REST API

Upload photos to Google Photos API - Error 500

I'm getting the error below while trying to upload media to Google Photos API, following the docs
This is how i retrieve my bytes array:
And this is how i make the request:
I've tried a lot of things and none of it work...
Note: I'm consuming other Google Photos API endpoints, such as Get Albums, Create Albums, Get Media and everything work as expected. The upload media is the only one i'm having trouble with.
Note 2: The token is being sent correctly.
Note 3: All the origin endpoints were configured in the google console (localhost included) so much so that other endpoints are working correctly.
Anyone can give me a light?
I am writing something similar in C# and was able to work with the photo api. My best advice is to double check headers. I hope this helps, additionally I added a postman screenshot of a successful call to the api:
public async Task<GoogleApiResponse> UploadPhoto(StorageFile photo)
{
var userInfo = UserInfoVault.GetUserInfo();
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", userInfo.AccessToken);
client.DefaultRequestHeaders.Add("X-Goog-Upload-File-Name", photo.DisplayName);
var fileStream = await photo.OpenAsync(FileAccessMode.Read);
var reader = new DataReader(fileStream.GetInputStreamAt(0));
await reader.LoadAsync((uint)fileStream.Size);
byte[] pixels = new byte[fileStream.Size];
reader.ReadBytes(pixels);
var httpContent = new ByteArrayContent(pixels);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
HttpResponseMessage photoResponse = client.PostAsync(ApiEdnpoints.UploadPhoto, httpContent).Result;
string strResponse = await photoResponse.Content.ReadAsStringAsync();
return null;
}
Postman screenshot of successful call to upload a photo

Windows Phone Facebook (OAuthException) (#1) An unknown error occurred

I have a WP7 app using facebook SDK 5.4.1. I try to upload a photo to Facebook, but always get an error message "(OAuthException) (#1) An unknown error occurred".
Here is my code:
var app = new Facebook.FacebookApp(AuthKey);
var parameters = new Dictionary<string, object>
{
{"message","test"},
{"description","test2"}
};
FacebookMediaObject media = new FacebookMediaObject
{
FileName = "1",
ContentType = "image/jpeg"
};
WriteableBitmap wb = new WriteableBitmap(0, 0).FromResource("/Images/thumbnails/Color.png");
media.SetValue(wb.ToByteArray());
parameters.Add("source", media);
app.PostAsync("me/photos", parameters, new FacebookAsyncCallback(postResult));
I can post a message on FB wall using my app, but not for uploading photos(I tried to upload different sizes of photo). What can be wrong? Thanks
You can't use wb.toByteArray() - you need to encode the image to JPEG before uploading it.
Extensions.SaveJpeg() is what you are looking for (here)

Resources