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

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

Related

How to connect Stanford Core Server from dotnet

I am trying to use Stanford NLP for.NET. I am very new to this.
How can I connect Stanford core NLP server from c# program
My NLP server runs on localhost:9000
You can connect via the .NET HTTPClient or other equivalent .NET call to a web endpoint. You need to set up your NLP endpoint, properties for the NLP server, and the text content you want it to parse. There is additional information on the Stanford NLP Server page, as well as information on what properties can be set depending on what NLP pipeline you want to run.
The following code is from a .NET Core console application using the following call to return Named Entity Recognition, Dependency Parser and OpenIE results.
FYI I've had some occasions where my NLP endpoint didn't work when waking a laptop from sleep mode (Docker for Windows pre 17.12 on Win10). Resetting Docker did the trick for me... if you can't browse to your http://localhost:9000 website, then the endpoint definitely won't work either!
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
// String to process
string s = "This is the sentence to provide to NLP."
// Set up the endpoint
string nlpBaseAddress = "http://localhost:9000"
// Create the query string params for NLPCore
string jsonOptions = "{\"annotators\": \"ner, depparse, openie\", \"outputformat\": \"json\"}";
Dictionary qstringProperties = new Dictionary();
qstringProperties.Add("properties", jsonOptions);
string qString = ToQueryString(qstringProperties);
// Add the query string to the base address
string urlPlusQuery = nlpBaseAddress + qString;
// Create the content to submit
var content = new StringContent(s);
content.Headers.Clear();
content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
// Submit for processing
var client = new HttpClient();
HttpResponseMessage response;
Task tResponse = client.PostAsync(urlPlusQuery, content);
tResponse.Wait();
response = tResponse.Result;
// Check the response
if (response.StatusCode != System.Net.HttpStatusCode.OK)
{
// Do something better than throwing an app exception here!
throw new ApplicationException("Subject-Object tuple extraction returned an unexpected response from the subject-object service");
}
Task rString = response.Content.ReadAsStringAsync();
rString.Wait();
string jsonResult = rString.Result;
Utility function used within this call to generate a QueryString:
private string ToQueryString(Dictionary nvc)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder("?");
bool first = true;
foreach (KeyValuePair key in nvc)
{
// CHeck if this is the first value
if (!first)
{
sb.Append("&");
}
sb.AppendFormat("{0}={1}", Uri.EscapeDataString(key.Key), Uri.EscapeDataString(key.Value));
first = false;
}
return sb.ToString();
}

Authenticating a Xamarin Android app using Azure Active Directory fails with 401 Unauthorzed

I am trying to Authenticate a Xamarin Android app using Azure Active Directory by following article here:
https://blog.xamarin.com/authenticate-xamarin-mobile-apps-using-azure-active-directory/
I have registered a native application with AAD; note that i havent given it any additional permissions beyond creating it.
Then i use the below code to authenticate the APP with AAD
button.Click += async (sender, args) =>
{
var authContext = new AuthenticationContext(commonAuthority);
if (authContext.TokenCache.Count > 0)
authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().GetEnumerator().Current.Authority);
authResult = await authContext.AcquireTokenAsync(graphResourceUri, clientId, returnUri, new PlatformParameters(this));
SetContentView(Resource.Layout.Main);
doGET("https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/OPSLABRG/providers/Microsoft.Compute/virtualMachines/LABVM?api-version=2015-08-01", authResult.AccessToken);
};
private string doGET(string URI, String token)
{
Uri uri = new Uri(String.Format(URI));
// Create the request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(uri);
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "GET";
// Get the response
HttpWebResponse httpResponse = null;
try
{
httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
}
catch (Exception ex)
{
Toast.MakeText(this, "Error from : " + uri + ": " + ex.Message, ToastLength.Long).Show();
return null;
}
}
This seems to be getting a token when using a Work account.
Using a valid hotmail account throws error A Bad Request was received.
However the main problem is when i try to retrieve VM details using REST.
the REST GET method fails with 401 Unauthorized error even when using the Work account.
I am not sure if the code is lacking something or if i need to give some additional permissions for the App. This needs to be able to support authenticating users from other tenants to get VM details.
Any guidance is appreciated.
note that i havent given it any additional permissions beyond creating
it.
This is the problem here.
In order for you to call the Azure Management API https://management.azure.com/, you must first register your application to have permissions to call this API.
You can do that as a part of your app registration like so:
Only at that point, will your app be authorized to call ARM, and your calls should start to work.
According to your description, I checked this issue on my side. As Shawn Tabrizi mentioned that you need to assign the delegated permission for accessing ARM Rest API. Here is my code snippet, you could refer to it:
var context = new AuthenticationContext($"https://login.windows.net/{tenantId}");
result = await context.AcquireTokenAsync(
"https://management.azure.com/"
, clientId, new Uri("{redirectUrl}"), platformParameter);
I would recommend you using Fiddler or Postman to simulate the request against ARM with the access_token to narrow this issue. If any errors, you could check the detailed response for troubleshooting the cause.
Here is my test for retrieving the basic information of my Azure VM:
Additionally, you could leverage jwt.io for decoding your access_token and check the related properties (e.g. aud, iss, etc.) as follows to narrow this issue.

Get "API key is missing" error when querying account details to Mailchimp API 3.0 using RestSharp

When using RestSharp to query account details in your MailChimp account I get a "401: unauthorized" with "API key is missing", even though it clearly isn't!
We're using the same method to create our RestClient with several different methods, and in all requests it is working flawlessly. However, when we're trying to request the account details, meaning the RestRequest URI is empty, we get this weird error and message.
Examples:
private static RestClient CreateApi3Client(string apikey)
{
var client = new RestClient("https://us2.api.mailchimp.com/3.0");
client.Authenticator = new HttpBasicAuthenticator(null, apiKey);
return client;
}
public void TestCases() {
var client = CreateApi3Client(_account.MailChimpApiKey);
var req1 = new RestRequest($"lists/{_account.MailChimpList}/webhooks", Method.GET);
var res1 = client.Execute(req1); // works perfectly
var req2 = new RestRequest($"automations/{account.MailChimpTriggerEmail}/emails", Method.GET);
var res2 = client.Execute(req2); // no problem
var req3 = new RestRequest(Method.GET);
var res3 = client.Execute(req3); // will give 401, api key missing
var req4 = new RestRequest(string.Empty, Method.GET);
var res4 = client.Execute(req4); // same here, 401
}
When trying the api call in Postman all is well. https://us2.api.mailchimp.com/3.0, GET with basic auth gives me all the account information and when debugging in c# all looks identical.
I'm trying to decide whether to point blame to a bug in either RestSharp or MailChimp API. Has anyone had a similar problem?
After several hours we finally found what was causing this..
When RestSharp is making the request to https://us2.api.mailchimp.com/3.0/ it's opting to omit the trailing '/'
(even if you specifically add this in the RestRequest, like: new RestRequest("/", Method.GET))
so the request was made to https://us2.api.mailchimp.com/3.0
This caused a serverside redirect to 'https://us2.api.mailchimp.com/3.0/' (with the trailing '/') and for some reason this redirect scrubbed away the authentication header.
So we tried making a
new RestRequest("/", Method.GET)
with some parameters (req.AddParameter("fields", "email")) to make it not scrub the trailing '/', but this to was failing.
The only way we were able to "fool" RestSharp was to write it a bit less sexy like:
new RestRequest("/?fields=email", Method.GET)

How to export a Confluence "Space" to PDF using remote API

How can I export a Confluence 'space' as a pdf? It looks like it might still be supported in Confluence 5.0 using the XML-RPC API. I cannot find an example of what to call, though.
https://developer.atlassian.com/display/CONFDEV/Remote+API+Specification+for+PDF+Export#RemoteAPISpecificationforPDFExport-XML-RPCInformation
That link says calls should be prefixed with pdfexport, but then doesn't list any of the calls or give an example.
This works using Bob Swift's SOAP library ('org.swift.common:confluence-soap:5.4.1'). I'm using this in a gradle plugin, so you'll need to change a few things
void exportSpaceAsPdf(spaceKey, File outputFile) {
// Setup Pdf Export Service
PdfExportRpcServiceLocator serviceLocator = new PdfExportRpcServiceLocator()
serviceLocator.setpdfexportEndpointAddress("${url}/rpc/soap-axis/pdfexport")
serviceLocator.setMaintainSession(true)
def pdfService = serviceLocator.getpdfexport()
// Login
def token = pdfService.login(user, password)
// Perform Export
def pdfUrl = pdfService.exportSpace(token, spaceKey)
// Download Pdf
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(pdfUrl)
httpget.addHeader(
BasicScheme.authenticate(
new UsernamePasswordCredentials(user,password),"UTF-8", false))
HttpResponse response = client.execute(httpget)
HttpEntity entity = response.getEntity()
if (entity != null) {
InputStream inputStream = entity.getContent()
FileOutputStream fos = new FileOutputStream(outputFile)
int inByte
while ((inByte = inputStream.read()) != -1)
fos.write(inByte)
inputStream.close()
fos.close()
} else {
throw new GradleException("""Cannot Export Space to PDF:
Space: ${spaceKey}
Dest: ${outputFile.absolutePath}
URL: ${pdfUrl}
Status: ${response.getStatusLine()}
""")
}
}
I know this is a PHP example, not Ruby, but you can check out the XML-RPC example in VoycerAG's PHP project on Github at https://github.com/VoycerAG/confluence-xmlrpc-pdf-export/blob/master/src/Voycer/Confluence/Command/PdfExportCommand.php ... hope it helps.
Basically you just need to make a call to the login method and user the authentication token returned to make a call to the exportSpace method. That in turn gives you back a URL which an authenticated user can then download the PDF from.
Turns out the soap API is the only currently available api for exporting a space
Using the Savon library in Ruby here:
require 'savon'
# create a client for the service
# http://<confluence-install>/rpc/soap-axis/pdfexport?wsdll
client = Savon.client(wsdl: 'https://example.atlassian.net/wiki/rpc/soap-axis/pdfexport?wsdl', read_timeout: 200)
# call the 'findUser' operation
response = client.call(:login, message: {username: "user", password: "pass"})
token = response.body[:login_response][:login_return]
response = client.call(:export_space, message:{token: token, space_key: "SPACE KEY"})

WebService ASP.NET MVC 3 Send and Receive

I've been racking my brain for a couple of days now on how to approach a new requirement.
I have two websites. The first one lets the user fill out an application. The second website is an internal website use to manage the users applications. I need to develop a "web service" that sends the application data from website 1 to website 2 and return a response to website 2 of success or failure. I have never done a web service before and I'm a bit confused on where to start. I've been reading various examples online but they all seem to be just a starting point for building a webservice... no specific examples.
So for posting the data website 1, what would my controller method look like? Do I use Json to post the data to website 2? What would and example of that look like? Is there some form of redirect in the method that points to website 2?
So for posting the response back to website 2 what would that controller method look like? I assume I would use Json again to send the response back to website 1? Is there some form of redirect in the method that points back to website 1?
I would use JSON and POST the application to the web service.
First I am assuming the application data is contained in some type of object. Use JSON.Net to serialize the object into JSON. It will look something like the following code.
var application = new Application();
string serializedApplication = JsonConvert.Serialize(application);
Second is to POST the code your endpoint(webservice, mvc action). To this you'll need to make a HTTPRequest to the endpoint. The following code is what I use to make to POST the code.
public bool Post(string url, string body)
{
//Make the post
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
var bytes = Encoding.Default.GetBytes(body);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
Stream stream = null;
try
{
request.KeepAlive = false;
request.ContentLength = bytes.Length;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = -1;
request.Method = "POST";
stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
}
finally
{
if (stream != null)
{
stream.Flush();
stream.Close();
}
}
bool success = GetResponse(request);
return success;
}
public bool GetResponse(HttpWebRequest request)
{
bool success;
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
{
throw new HttpException((int)response.StatusCode, response.StatusDescription);
}
var end = string.Empty;
using (StreamReader reader = new StreamReader(responseStream))
{
end = reader.ReadToEnd();
reader.Close();
success = JsonConvert.DeserializeObject<bool>(end);
}
response.Close();
}
}
return success;
}
So now you have can POST JSON to an endpoint and receive a response the next step is to create the endpoint. The following code will get you started on an endpoint in mvc that will receive an application and process it.
[HttpPost]
public ActionResult SubmitApplication()
{
//Retrieve the POSTed payload
string body;
using (StreamReader reader = new StreamReader(Request.InputStream))
{
body = reader.ReadToEnd();
reader.Close();
}
var application = JsonConvert.Deserialize<Application>(body);
//Save the application
bool success = SaveApplication(application);
//Send the server a response of success or failure.
return Json(success);
}
The above code is a good start. Please note, I have not tested this code.
You have obviously more than one client for the data & operations. so a service is what you are looking for.
ASP.NET MVC is a good candidate for developing RESTful services. If you (and your Manager) are ready to use beta version, Then Checkout ASP.NET-Web API.
If you want to stay with a stable product, Go for MVC3. you may need to write some custom code to return the data in XML as well as JSON to server different kind of clients. There are some tutorials out there.
So create a Service (ASP.NET MVC / WCF Service) .You may then create 2 client apps, one for the external clients and another for the Internal users. Both of this apps can call methods in the Service to Create/ Read the user accounts / or whatever operation you want to do.
To make the apps more interactive and lively , you may conside including a wonderful thing called SiganalR, which helps you to get some real time data without continuosly polling the data base/ middle tier very in every n seconds !

Resources