I am currently trying to use Google Cloud Vision API on C#.
After downloading JSON file for google cloud authentication, I have set the system environment variable as the path of the JSON file and compiled my code. It was all good.
However, when I created DLL with the source it seems like the DLL could not get the Google Application Credentials value from the system environment variable.
So that I studied some of the Google Credential Authentication documents to put a code at the very first line of C# code to deliver my JSON file path to recognize my vision api calls.
However, the code is not working to properly authenticating my JSON file to call Google Vision API.
Please enlighten me with your knowledge! Thanks.
Here is my code.
using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
using Google.Cloud.Vision.V1;
using Image = Google.Cloud.Vision.V1.Image;
using Grpc.Core;
using Grpc.Auth;
namespace dotNetFramework461_Console
{
class Program
{
public string GVA_API()
{
string jsonPath = "D:\\blablablah\\abcdefghijk.json";
string imgPath = "C:\\Users\\blablablah\\image.jpg";
var stream = new FileStream(jsonPath, FileMode.Open, FileAccess.Read);
var credential = GoogleCredential.FromStream(stream).CreateScoped(ImageAnnotatorClient.DefaultScopes);
var channel = new Grpc.Core.Channel(ImageAnnotatorClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials());
var client = ImageAnnotatorClient.Create(channel);
var image = Image.FromFile(imgPath);
TextAnnotation text = client.DetectDocumentText(image);
return text.Text;
}
}
}
Related
I am trying to use Mailjet to send messages via email, but why is the word version not recognized in it? I downloaded the mailgate package
I'm practicing programming using the asp.net core5.0 framework.
Are there other distinct ways to send messages via e-mail?
Any advice from you?
using Mailjet.Client;
using Mailjet.Client.Resources;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.UI.Services;
using Newtonsoft.Json.Linq; ][1]
If you have Version = ApiVersion.V3_1, as part of your sample code, comment it out and add the appropriate BaseAdress line in the example below:
MailjetClient client = new MailjetClient("xxx-example-xxx", "xxx-example-xxx")
{
BaseAdress = "https://api.mailjet.com",
//BaseAdress = "https://api.us.mailjet.com",
//Version = ApiVersion.V3_1,
};
Hi I'm creating a desktop application with unity to take a photo and upload it to a public google drive account.
I have followed the instructions to create the project in google cloud of this page:
https://developers.google.com/drive/api/v3/quickstart/dotnet
And I've used the unity package from this repository, also following the instructions:
https://github.com/Elringus/UnityGoogleDrive
The problem is that when I try to access from my program to unity for upload the photo to the repository I get this error:
Authorization Error
Error 400: redirect_uri_mismatch
You can't log in to this app because it doesn't comply with Google's OAuth 2.0 policy.
If you are the developer of the application, register the redirect URI in the Google Cloud console.
Learn more
Request Details
The content in this section has been provided by the app developer. This content has not been reviewed or verified by Google.
If you're the app developer, make sure that these request details comply with Google policies.
redirect_uri: http: // localhost: 54201
But I have already set the URLs to Authorized redirect URIs
from Google Cloud, however in the error shows me the url of my localhost changes in each request (example: redirect_uri: http://localhost:59708 and redirect_uri: http://localhost:55683), so I would appreciate it if you would help me to know which url I should set on Google Cloud or how I can configure that my url doesn't change in every request.
In add I can't change the project to webgl or mobile as android, so this is a solution only for a desktop app in unity.That means than I've .json credentials from google cloud.
This my C # code that I'm using in unity.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityGoogleDrive;
using System.IO;
public class UploadGoogle : MonoBehaviour
{
public string UploadFilePath;
private GoogleDriveFiles.CreateRequest request;
private string result;
public void OnButtonClick()
{
UploadFilePath = string.Format("{0}/Snapshots/snap.jpg", Application.dataPath);
var content = File.ReadAllBytes(UploadFilePath);
var file = new UnityGoogleDrive.Data.File { Name = "Image.jpg", Content = content };
GoogleDriveFiles.Create(file).Send();
request = GoogleDriveFiles.Create(file);
request.Fields = new List<string> { "id", "name", "size", "createdTime" };
request.Send().OnDone += PrintResult;
}
private void PrintResult(UnityGoogleDrive.Data.File file)
{
result = string.Format("Name: {0} Size: {1:0.00}MB Created: {2:dd.MM.yyyy HH:MM:ss}\nID: {3}",
file.Name,
file.Size * .000001f,
file.CreatedTime,
file.Id);
}
}
Thank you
Preface:
This is a part of my personal project of building a control GUI for several communication devices - using WinForms unfortunately.
The part of code running into trouble is rested inside the Constructor of a Form.
Additional NuGet packages installed are: Newtonsoft.Json, RestSharp, SpecFlow and SpecFlow.Assist.Dynamic.
LoginForm and SeatsInfo are two basic classes created only to store and organize my data, they have no additional coding besides properties declartions.
Execution code:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CONTROL_UI
{
public partial class RunningConfig : Form
{
public RunningConfig()
{
InitializeComponent();
var client = new RestClient("CLIENT_URL");
var loginRequest = new RestRequest("api/login", Method.POST);
loginRequest.RequestFormat = DataFormat.Json;
loginRequest.AddHeader("Content-type", "application/json");
loginRequest.AddJsonBody(new LoginForm() { username = "admin", password = "", #override = true });
var loginRespone = client.Execute(loginRequest);
JObject sessionInfo = JObject.Parse(loginRespone.Content);
var sessionID = sessionInfo["sid"];
var seatAvailRequest = new RestRequest("api/seats", Method.GET);
seatAvailRequest.AddHeader("sid", sessionID.ToString());
seatAvailRequest.AddHeader("Cookie", "sid = " + sessionID.ToString());
var seatResponse = client.Execute(seatAvailRequest);
List<SeatsInfo> seatsInfo = JsonConvert.DeserializeObject<List<SeatsInfo>>(seatResponse.Content);
//Further Implementation
}
}
}
Expected packet view in WireShark:
Actual packet view in WireShark:
sids are generated each time I successfully authorized to connect to the device, so they obviously differ.
The screenshot of my expected view is taken from the exact same block of codes in a plain console app. Everything works fine there. All the NuGet packages installed on the two programmes are of the same version, I even tried running them side-by-side but it did not help.
Debugging screenshots showed that the Parameters did, in fact, contain the Cookie header:
The header just did not go through for some reason. Would love to hear some thoughts in regards to this issue, many thanks in advance!
Current solution, just add another AddCookie() method:
seatAvailRequest.AddHeader("sid", sessionID.ToString());
seatAvailRequest.AddHeader("Cookie","sid = " + sessionID.ToString());
seatAvailRequest.AddCookie("sid", sessionID.ToString());
This somehow does not work with just AddCookie() or AddHeader(), so for now they are both going in. Hope this helps someone, and thank yall for reading!
So, in recap I was lacking the Cookie Header in the API call thus making the call being unsuccessful (the device did not authorized it).
After messing around with the AddCookie() method, particularly:
seatAvailRequest.AddCookie("sid", sessionID.ToString());
The device gave me a different error - 404 Not Found, before was 401 Unauthorized:
Finally my dumb mind resorted using both the AddCookie() along with AddHeader() and voilĂ :
It works! Only after 5 hours of painful debugging and mind-numbing searches. Although the new packet is a bit larger, but I do not have to worry about that for now, or in the future realistically speaking.
Thanks you all for just following along, still open for suggestions and improvements!
I have developed an Android game which successfully gets a ServerAuthCode from the Google Play API. I want to send this ServerAuthCode to my custom game server, which I have wrote in C# and validate it to authenticate the player.
There is a documentation by Google for Java available (part "Exchange the server auth code for an access token on the server"): https://developers.google.com/games/services/android/offline-access
Unfortunately I can not adapt this for C#.
I have the client_secret.json which seems to include all API authentication data and I have the ServerAuthCode (which seems to be a token).
There is also a NuGet package available for C#, but it does not contain all the classes from the above documentation: https://www.nuget.org/packages/Google.Apis.AndroidPublisher.v3/
How can I validate the token? I would also welcome a simple Postman example.
I figured it out by trial and error. One important thing to note is that the Server Auth Code expires fast. In case you are debugging and copy & pasting by hand, it may happen that until you run the code, the Server Auth Code is already expired. In this case, Google API returns "invalid_grant" as error, which for me was misleading.
In my example solution you need to have a file "client_secret.json" in your project, which is copied on build to the output directory (file properties -> "Build Action" = "Content", "Copy to Output Directory" = "Copy always").
You get your client_secret.json file from the Google API console (https://console.developers.google.com/apis/credentials?project=, click on the download icon on the right side of your project, under "OAuth 2.0-Client-IDs").
Important: The redirect url must match the redirect url configured in your project. For me, it was just empty, so just use an empty string.
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Requests;
using System;
using System.IO;
using System.Reflection;
using System.Text;
namespace GoogleApiTest
{
// Source: https://developers.google.com/identity/sign-in/android/offline-access
class Program
{
static void Main(string[] args)
{
var authCode = "YOUR_FRESH_SERVER_AUTH_CODE";
var path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"client_secret.json");
var config = File.ReadAllText(path, Encoding.UTF8);
GoogleClientSecrets clientSecrets = GoogleClientSecrets.Load(new FileStream(path, FileMode.Open));
var request = new AuthorizationCodeTokenRequest()
{
ClientId = clientSecrets.Secrets.ClientId,
ClientSecret = clientSecrets.Secrets.ClientSecret,
RedirectUri = "",
Code = authCode,
GrantType = "authorization_code"
};
var tokenResponse = request.ExecuteAsync(new System.Net.Http.HttpClient(), "https://www.googleapis.com/oauth2/v4/token", new System.Threading.CancellationToken(), Google.Apis.Util.SystemClock.Default).GetAwaiter().GetResult();
Console.ReadLine();
}
}
}
UPDATE: I still haven't solved it, my my current work around is to not do a desktop client. I've switched back to a web app for now, and everything is working again. I don't know, I'm stumped.
I've been able to get my Twitter web app working just fine, but I've recently decided to add Tweeting functionality from a Windows Form, but I'm having no luck sending tweets. No errors are thrown or anything. Mind looking over my code?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TweetSharp;
namespace TwitterAdvirtiser
{
public partial class Form1 : Form
{
private string cKey = "xxx";
private string cSecret = "xxx";
private string oToken = "xxx";
private string aToken = "xxx";
public Form1()
{
InitializeComponent();
OnStart();
}
private void OnStart()
{
//Authenticate with Twitter
TwitterService service = new TwitterService(cKey, cSecret);
service.AuthenticateWith(oToken, aToken);
service.SendTweet("testing");
}
}
}
It seems like I'm authenticating just fine, I can walk through debug mode and see all my details in the TwitterUser structure, and yet my tweets never show up on my feed. Whats up?
By the way, I'm using Visual Studios 2010, and .NET 4.0. I have verified that the oToken and aToken strings have my developer tokens.
As far as I can see you're only authenticating using the Consumer Key, Consumer Secret, Token Key and Token Secret. You also need to include the verifier pin with the signature base.