Google.Cloud.AIPlatform.V1 Received http2 header with status: 404 - c#

We are trying to call the Google.Cloud.AIPlatform.V1 predict API using the .Net client and keep getting the following error: Received http2 header with status: 404
We setup credentials using the API key and environment variable: GOOGLE_APPLICATION_CREDENTIALS
Here is the code to call the vertex AI predict API:
const string projectId = "xxxxxx";
const string location = "us-central1";
const string endpointId = "xxxxxx";
PredictionServiceClient client = PredictionServiceClient.Create();
var structVal = Google.Protobuf.WellKnownTypes.Value.ForStruct(new Struct
{
Fields =
{
["mimeType"] = Google.Protobuf.WellKnownTypes.Value.ForString("text/plain"),
// Sample contents is a string constant defined in a separate file
["content"] = Google.Protobuf.WellKnownTypes.Value.ForString(Consts.SampleContents)
}
});
PredictRequest req = new PredictRequest()
{
EndpointAsEndpointName = EndpointName.FromProjectLocationEndpoint(projectId, location, endpointId),
Instances = { structVal }
};
PredictResponse response = client.Predict(req);
The full error returned:
Status(StatusCode="Unimplemented", Detail="Received http2 header with status: 404", DebugException="Grpc.Core.Internal.CoreErrorDetailException: {"created":"#1644947338.412000000","description":"Received http2 :status header with non-200 OK status","file":"......\src\core\ext\filters\http\client\http_client_filter.cc","file_line":134,"grpc_message":"Received http2 header with status: 404","grpc_status":12,"value":"404"}")
I validate the same call using CURL and was able to successfully make the call.
curl -X POST -H "Authorization: Bearer XXXXX" -H "Content-Type: application/json" https://us-central1-aiplatform.googleapis.com/ui/projects/XXXXXX/locations/us-central1/endpoints/XXXXXX:predict -d #payload.json
Any help would be greatly appreciated.

I think, we had same problem
and I was resolve that
PredictionServiceClient -> Need EndPoint of PredictionServiceClient Set,
PredictionServiceClient client = PredictionServiceClient.Create();
change please
PredictionServiceClientBuilder ClientBuilder = new PredictionServiceClientBuilder();
ClientBuilder .Endpoint = "us-central1-aiplatform.googleapis.com";
PredictionServiceClient client = ClientBuilder.Build();
thanks

Related

Converting JIRA API cURL to c# http request

I have a cURL with which I connect to Atlassian JIRA API and search an issue with JQL, filtering issues by project name and status.
This is the cURL command, which works pretty well:
curl -u JIRAUSER:JIRATOKEN -X POST --data '{ "jql": "project = \"QA\" AND status=\"To Do\" " }' -H "Content-Type: application/json" https://jiraserver.atlassian.net/rest/api/2/search
I'm trying to re-build it on c# with httpclient POST method. The code is given below:
static async System.Threading.Tasks.Task Main(string[] args)
{
using (var httpClient = new HttpClient())
{
using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://jiraserver.atlassian.net/rest/api/2/search"))
{
var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("JIRAUSER:JIRA TOKEN"));
request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}");
request.Content = new StringContent("{ \"jql\": \"project = \"QA\" AND status = \"To Do\" }");
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await httpClient.SendAsync(request);
Console.WriteLine(response);
}
}
}
response returns the following error:
StatusCode: 400, ReasonPhrase: '', Version: 1.1, Content:
System.Net.Http.HttpConnectionResponseContent
And in System.Diagnostics.Debug.Write I get the following error:
error CS0428: Cannot convert method group 'Write' to non-delegate type
'object'. Did you intend to invoke the method?
Please give me some hint or I'm about to hang myself...
I'd suggest using JIRA SDK to interact with your JIRA instance -> https://bitbucket.org/farmas/atlassian.net-sdk/src/master/.
Basically, set of steps are
1) initiate jira client:
var jiraClient = Jira.CreateRestClient(<jiraURL>, <jiraUserName>, <jiraUserPwd>);
2) connect to jira, and pull based on search criteria:
var jql = "project = QA + " AND status in (To Do)";
IEnumerable<Atlassian.Jira.Issue> jiraIssues = AsyncTasker.GetIssuesFromJQL(jiraClient, jql, 999);
3) then, you can enumerate in the pulled issues
...
foreach(var issue in jiraIssues)
{
/*
... for example, some of the available attributes are:
issue.Key.Value
issue.Summary
issue.Description
issue.Updated
String.Format("{0}/browse/{1}", jiraURL.TrimEnd('/') , issue.Key.Value)
...
*/
}
on the side note, it's advisable not to use using(... = new HttpClient()){....}

Browserstack restSharp cURL PUT request conversion

I am trying to convert the following cURL command to C# using restSharp
so that I can mark my automated Browserstack tests passed or failed.
curl -u "user:password" -X PUT -H "Content-Type: application/json" -d "{\"status\":\"<new-status>\", \"reason\":\"<reason text>\"}" https://www.browserstack.com/automate/sessions/<session-id>.json
Please note I am very new to C# I have the following code that currently returns an empty json response, I know I am on the right path as changing the request method to POST returns details (as expected) for my session/test:
private string markTestPassedorFail(string sesID)
{
var Client = new RestClient();
var Request = new RestRequest();
string sResponse = "";
Client.BaseUrl = new Uri(CapConf.BROWSERSTACK_SESSIONS_URL);
Client.Authenticator = new HttpBasicAuthenticator(CapConf.BROWSERSTACK_USER_NAME, CapConf.BROWSERSTACK_KEY_PASS);
Request.Resource = sesID + ".json";
Request.Method = Method.PUT;
Request.AddHeader("Content-Type", "application/json");
Request.AddJsonBody("{\"status\":\"failed\", \"reason\":\"failed\"}");
try
{
IRestResponse response = Client.Execute(Request);
sResponse = response.Content;
}
catch (Exception ex)
{
Console.WriteLine("Error Marking Test Passed or Fail : \n" + ex.Message);
}
return sResponse;
}
Have you tried the sample code snippet shared in their documentation here - https://www.browserstack.com/automate/c-sharp
I just pulled up bits of the code snippet there and was able to setup a sample test run, fetch the session ID and later update the session status via REST API.
Sample test -
https://www.browserstack.com/automate/c-sharp#getting-started
Session ID -
https://www.browserstack.com/automate/c-sharp#session-id
Session status update via REST API -
https://www.browserstack.com/automate/c-sharp#rest-api
Refer to the following gist:
https://gist.github.com/ashwingonsalves/56d7724671054bf623081bdcb30d40b8

Connecting to a SOAP WSDL in Visual Studio C#

I am trying to connet my C# console application with a thridparty SOAP WSDL API however I cannot get it working.
I connect to the service with the WSDL string as a Service recourse in Visual studio: https://domain.tld/SimpleAPI/SimpleAPIService.svc?singleWsdl
The documentation says:
Authentication is sessions based. The requester must provide a valid session token in the Authenticate field of each request. A session has access to the same resources and capabilities as the given user. To get a session token, use the GetSessionToken method. To validate a session, use the PingPong method.
The documentation focuses on the REST API, which is not an option for me. The two methods for connecting is as follows:
curl \ -H "Content-Type: application/json" \ -X POST -d '{ "username": "admin#domain.com", "password": "VerySecure123" }' \ https://domain.tld/SimpleAPI/SimpleAPIService.svc/rest/GetSessionToken
This should return something like this: C9C5MlqrpMwG/6bQ3mAVlm0Z6hi/eh1vsQs4i1I/g==
This part is okay, I get a token back. However when I try the PingPong method, I get an error saying that it is a wrong token or the session has expired.
curl \ -H "Content-Type: application/json" \ -H "Authenticate:CCPSessionId C9C5MlqrpMwG/6bQ3mAVlm0Z6hi/eh1vsQs4i1I/g==" \ -X POST -d '{}' \ https://domain.tld/SimpleAPI/SimpleAPIService.svc/rest/PingPong
My code is as follows:
static void Main(string[] args)
{
string apiUsername = "user";
string apiPassword = "pass";
using (var client = new acmp.SimpleAPIServiceClient())
{
client.ClientCredentials.UserName.UserName = apiUsername;
client.ClientCredentials.UserName.Password = apiPassword;
string token = client.GetSessionToken(apiUsername, apiPassword);
string tokenText = string.Format("CCPSessionId {0}", token);
using (OperationContextScope contextScope = new OperationContextScope(client.InnerChannel))
{
var httpRequestProperty = new HttpRequestMessageProperty();
httpRequestProperty.Headers[HttpRequestHeader.Authorization] = token; //tokenText
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
client.PingPong();
}
}
Console.WriteLine("End...");
Console.ReadLine();
}
The theory right now is that my script is not passing the correct header.
Please help, we have spend so much time debugging.
Did a little reading up, and I can't find a token text of "CCPSessionsid " anywhere.
I see "bearer", token.AccessToken
Along the lines of:
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", token.AccessToken);
I also came across this issue while working with the same API. Cutting the quotation marks off the string solved this for me.
request.Headers.TryAddWithoutValidation("Authenticate", token.Trim(new Char[] {'"'}));

Curl request written in C# doesn't work

I'm trying to write a specific curl request in C#, and I keep getting a 500 server error response from the server. This curl request essentially makes a post request to an API by the company Highwinds. This request sends json data, and sets the Auth Bearer token header.
This is the curl request that works fine (note that I've replaced my actual bearer token with {token} and my actual account id with {accountId} to obfuscate that info):
curl -H "Authorization: Bearer {token}" -H "Content-Type: application/json" -d "#data.json" "https://striketracker.highwinds.com/api/accounts/{accountId}/purge"
Here's the C# code that gives me a generic 500 server error from the Highwinds API (note that I've replaced my actual bearer token with {token}, my actual account id with {accountId}, and the url in the json string with {url}, in order to obfuscate that personal info):
var accountId = "{accountId}";
var purgeURI = string.Format("https://striketracker.highwinds.com/api/accounts/{0}/purge", {accountId});
var query =
#"{""list"": [{""url"": ""{url}"",""recursive"": true}]}";
var token = {token};
using (var httpClient = new HttpClient())
{
var url = new Uri(purgeURI);
using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, url))
{
httpRequestMessage.Headers.Add(System.Net.HttpRequestHeader.Authorization.ToString(),
string.Format("Bearer {0}", token));
httpRequestMessage.Content = new StringContent(query,
Encoding.UTF8,
"application/json");
await httpClient.SendAsync(httpRequestMessage).ContinueWith(task =>
{
var response = task.Result;
var blah = response.Content.ReadAsStringAsync().Result;
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
});
}
}
Thanks!
*Update: The following line of code was added to remove the Expect header that HttpRequest adds to a request by default. After removing this header I was able to get Highwinds API to accept the request without bombing.
"request.ServicePoint.Expect100Continue = false;"
My best recommendation would be to proxy both requests through something like tcpmon http://archive.apache.org/dist/ws/tcpmon/1.0/ (Basically run the server and point to local host and have tcpmon redirect the request to striketracker.highwinds.com). Try it from curl and from your source and you should be able to see what's different between the requests.

CURL command to C# code Dropbox API

I am using Dropbox APIs to upload a file to dropbox cloud. I have the access token and I need to execute the following curl command:
curl -H "Authorization: Bearer NBNBNSBJHDKHDKJJGGD" https://api-content.dropbox.com/1/files_put/auto/ -T "C:\Tm\dd.jpg"
Could someone please let me know how to do the above in C#
Thanks for your help
Thanks for all your support. This got resolved. I feel this will be definitely useful for some one.
string filePath="C:\\Tim\\sundar.jpg";
RestClient client = new RestClient("https://api-content.dropbox.com/1/");
IRestRequest request = new RestRequest("files_put/auto/{path}", Method.PUT);
FileInfo fileInfo = new FileInfo(filePath);
long fileLength = fileInfo.Length;
request.AddHeader("Authorization", "Bearer FTXXXXXXXXXXXXXXXXXXXisqFXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
request.AddHeader("Content-Length", fileLength.ToString());
request.AddUrlSegment("path", string.Format("Public/{0}", fileInfo.Name));
byte[] data = File.ReadAllBytes(filePath);
var body = new Parameter
{
Name = "file",
Value = data,
Type = ParameterType.RequestBody,
};
request.Parameters.Add(body);
IRestResponse response = client.Execute(request);

Categories

Resources