Code looks like below.
String instanceId = "ocid1.instance.oc1.eu-frankfurt-1.abtheljsmrq3yox36wukah52yaeswh6jc4vwjfkc46jxe4nwgnmga7nm7bpq";
String configurationFilePath = "~/.oci/config.txt";
String profile = "DEFAULT";
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
AuthenticationDetailsProvider provider =
new ConfigFileAuthenticationDetailsProvider(configurationFilePath, profile);
System.out.println(provider.toString());
RequestSigner requestSigner = DefaultRequestSigner.createRequestSigner(provider);
Client client =
ClientBuilder.newBuilder().build().register(new SigningFilter(requestSigner));
WebTarget target =
client.target("https://iaas.eu-frankfurt-1.oraclecloud.com")
.path("20160918")
.path("instances")
.path(UrlEscapers.urlPathSegmentEscaper().escape(instanceId));
Invocation.Builder ib = target.request();
ib.accept(MediaType.APPLICATION_JSON);
Response response = ib.get();
System.out.println(target.getUri());
I double checked the instance ocid in the console.
Output response is as below
{ "code" : "NotAuthorizedOrNotFound", "message" : "instance ocid1.instance.oc1.eu-frankfurt-1.abtheljsmrq3yox36wukah52yaeswh6jc4vwjfkc46jxe4nwgnmga7nm7bpq not found"}
Any inputs?
Related
Step 1:
Created GraphServiceClient using Microsoft.Graph 4.9.0 and Microsoft.Graph.Core 2.0.5 SDK
var scopes = new[] { "https://graph.microsoft.com/.default" };
ClientSecretCredential clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, new ClientSecretCredentialOptions()
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
});`
GraphServiceClient graphServiceClient = new GraphServiceClient(clientSecretCredential, scopes);
Step 2:
And created a custom schema extension like below.
SchemaExtension schemaExtension = new SchemaExtension()
{
Id = "data1",
Description = "creating test schema extn",
TargetTypes = new List<string>()
{
"User"
},
Properties = new List<ExtensionSchemaProperty>()
{
new ExtensionSchemaProperty()
{
Name ="prop1",
Type ="String"
}
}
};
Step 3:
Updated the Schema extension status to "Available"
var updatedExtn = await graphServiceClient
.SchemaExtensions[schemaExtension.Id].Request()
.UpdateAsync(new SchemaExtension()
{
Status = "Available"
});
Step 4:
Create Class for extension data
public class data1
{
// You must serialize your property names to camelCase if your SchemaExtension describes as such.
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "prop1", Required = Newtonsoft.Json.Required.Default)]
public string Prop1 { get; set; }
}
Step 5:
Find the User and add the created schema extension to the user
IDictionary<string, object> extensionInstance = new Dictionary<string, object>();
// The below line is not working. but doesn't throw error
extensionInstance.Add(schemaExtension.Id, new data1 { prop1 = "testing" });
var usrCollection = await graphServiceClient.Users
.Request()
.Filter($"userPrincipalNames eq '{adelev_Mail}'")
.GetAsync();
var usr = usrCollection.FirstOrDefault();
if(usr != null)
{
usr.AdditionalData.Add(extensionInstance);
var updatedUser = await graphServiceClient.Users[usr.Id]
.Request()
.UpdateAsync(usr);
}
Step 6:
When you try to retrieve the extension the value is NULL.
User updatedUser = await graphServiceClient.Users[usr.Id].Request()
.Select($"id, {schemaExtension.Id}")
.GetAsync();
But it works with API using Graph Explorer.
PATCH https://graph.microsoft.com/v1.0/users/{userId}
{
"extXXXXXXXX_data1":
{
"prop1" : "testing"
}
}
Please let me know if I'm missing anything here. Any help here is much appreciated.
You should accessing the data on AdditionalData property. Try looking at user.AdditionalData in your result. Here is a screenshot with my example.
Getting User with Schema extension from Graph explorer.
While using the SDK, i access my custom data in user.AdditionalData
Check this thread - Graph SDK and SchemaExtensions for details.
I am a little new to using the REST API for Azure DevOps and have it working fine where I can send my requests that are basically the URIs I see on the website for the API. Then I get that JSON response and de-serialize it into a class from the JSON response and am off running.
Below is an example of a function I use to get a Work Item by it's ID. It uses the URI from the website.
I can also test things by pasting the URI into my browser and then see the response.
My question is, How do I use the command for Updating the Workitem (Add Link for example) which is not a URI that I can test by pasting it into my browser. Instead it is a JSON message.
here is API Website which shows the JSON message needed to add a link to a work item.
https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/update?view=azure-devops-rest-5.1#add-a-link
this is the JSON message they have there for updating a WorkItem Link:
[
{
"op": "test",
"path": "/rev",
"value": 3
},
{
"op": "add",
"path": "/relations/-",
"value": {
"rel": "System.LinkTypes.Dependency-forward",
"url": "https://dev.azure.com/fabrikam/_apis/wit/workItems/300",
"attributes": {
"comment": "Making a new link for the dependency"
}
}
}
]
Do I need a different function to send it the JSON message and then the function could return me the JSON Response? I can not find an example of what that function might look like.
Any Advice on how to send the JSON message instead of the URI to get a response would be greatly appreciated.
===================== UPDATE =====================
The one answer definitely helped me get this finally working.
I pasted in the updated function in case it helps anyone else.
I know it is tricky to find VB.NET samples for this. :)
THANKS!
UPDATED CODE==========================================================
Public Async Function GetRequestAsync(ByVal uri As String, Optional ByVal jsonMessageBody As String = "") As Task(Of String())
Dim client As HttpClient = New HttpClient()
SetUpHttpClient(client)
Dim statusCode As String = "NOTHING"
Dim responseBody As String = "NOTHING"
Try
If jsonMessageBody.Length > 0 Then
'#####################################################################
'### For all PATCH operations that have a URI and a JSON message ###
'#####################################################################
Dim patchValue = New StringContent(jsonMessageBody, Encoding.UTF8, "application/json-patch+json")
Dim method = New HttpMethod("PATCH")
Dim request = New HttpRequestMessage(method, uri) With {.Content = patchValue}
Dim response = client.SendAsync(request).Result
responseBody = response.Content.ReadAsStringAsync.Result()
Else
'#######################################################
'### For all other operations that have just a URI ###
'#######################################################
Using response As HttpResponseMessage = client.GetAsync(uri).Result
statusCode = response.StatusCode.ToString()
response.EnsureSuccessStatusCode()
responseBody = response.Content.ReadAsStringAsync().Result
End Using
End If
Catch
End Try
Dim answer As String() = {statusCode, responseBody}
Return answer
End Function
Public Function GetTestCase(organization As String, project As String, TestCaseID As String) As WorkItemApi
Dim dc As New DevCon.DevOpsConnector
Dim response As String() = dc.GetRequest($"https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{TestCaseID}?api-version=5.1&$expand=all")
If response(0) <> "OK" Then
Return Nothing
End If
Dim result As WorkItemApi = JsonConvert.DeserializeObject(Of WorkItemApi)(response(1))
Return result
End Function
Public Async Function GetRequestAsync(ByVal getRequest As String) As Task(Of String())
Dim client As HttpClient = New HttpClient()
SetUpHttpClient(client)
Dim statusCode As String = "NOTHING"
Dim responseBody As String = "NOTHING"
Try
Using response As HttpResponseMessage = client.GetAsync(getRequest).Result
statusCode = response.StatusCode.ToString()
' Console.WriteLine("Response: " & statusCode)
response.EnsureSuccessStatusCode()
responseBody = response.Content.ReadAsStringAsync().Result
End Using
Catch
End Try
Dim answer As String() = {statusCode, responseBody}
Return answer
End Function
You need to serialize the fields array into a json string. Check the following sample in C# using the HttpClient class:
public WorkItem CreateBugUsingHTTP()
{
string uri = _uri;
string personalAccessToken = _personalAccessToken;
string project = _project;
string credentials = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalAccessToken)));
Object[] patchDocument = new Object[4];
patchDocument[0] = new { op = "add", path = "/fields/System.Title", value = "Authorization Errors" };
patchDocument[1] = new { op = "add", path = "/fields/Microsoft.VSTS.TCM.ReproSteps", value = "Our authorization logic needs to allow for users with Microsoft accounts (formerly Live Ids) - http://msdn.microsoft.com/en-us/library/live/hh826547.aspx" };
patchDocument[2] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Priority", value = "1" };
patchDocument[3] = new { op = "add", path = "/fields/Microsoft.VSTS.Common.Severity", value = "2 - High" };
using (var client = new HttpClient())
{
//set our headers
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", credentials);
//serialize the fields array into a json string
var patchValue = new StringContent(JsonConvert.SerializeObject(patchDocument), Encoding.UTF8, "application/json-patch+json");
var method = new HttpMethod("POST");
var request = new HttpRequestMessage(method, uri + "/" + project + "/_apis/wit/workitems/$Bug?api-version=5.1") { Content = patchValue };
var response = client.SendAsync(request).Result;
//if the response is successfull, set the result to the workitem object
if (response.IsSuccessStatusCode)
{
var workItem = response.Content.ReadAsAsync<WorkItem>().Result;
Console.WriteLine("Bug Successfully Created: Bug #{0}", workItem.Id);
return workItem;
}
else
{
Console.WriteLine("Error creating bug: {0}", response.Content);
return null;
}
}
}
You could get started from the documentation below:
https://learn.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-5.1
Public Async Function GetRequestAsync(ByVal uri As String, Optional ByVal jsonMessageBody As String = "") As Task(Of String())
Dim client As HttpClient = New HttpClient()
client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))
client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Basic", _accessTokenHttpClient)
Dim statusCode As String = "NOTHING"
Dim responseBody As String = "NOTHING"
Try
If jsonMessageBody.Length > 0 Then
'#####################################################################
'### For all PATCH operations that have a URI and a JSON message ###
'#####################################################################
Dim patchValue = New StringContent(jsonMessageBody, Encoding.UTF8, "application/json-patch+json")
Dim method = New HttpMethod("PATCH")
Dim request = New HttpRequestMessage(method, uri) With {.Content = patchValue}
Dim response = client.SendAsync(request).Result
responseBody = response.Content.ReadAsStringAsync.Result()
Else
'#######################################################
'### For all other operations that have just a URI ###
'#######################################################
Using response As HttpResponseMessage = client.GetAsync(uri).Result
statusCode = response.StatusCode.ToString()
response.EnsureSuccessStatusCode()
responseBody = response.Content.ReadAsStringAsync().Result
End Using
End If
Catch
End Try
Dim answer As String() = {statusCode, responseBody}
Return answer
End Function
Hi Stack Overflow community!
I'm trying to mock a microservice in some java integration tests.
To do so, I'm using MockServer version 5.5.1.
To do the rest-requests I'm using OkHttp version 3.13.1
The code in java:
final SomeDTO requestObject = new SomeDTO(someParams);
final String jsonObject = objectMapper.writeValueAsString(requestObject);
final MediaType MEDIA_TYPE_JSON = MediaType.get("application/json; charset=utf-8");
final RequestBody requestBody = RequestBody.create(MEDIA_TYPE_JSON, jsonObject);
final Request request = new Request.Builder().url("serverUrl").post(requestBody).build();
final Response response = client.newCall(request).execute();
final String responseJson = response.body().string();
final ResultDTO result = objectMapper.readValue(responseJson, ResultDTO.class);
This works fine. However, when I attach MockServer with the matcher:
final MockServerClient client = new MockServerClient("127.0.0.1", 1080);
client.when(request().withMethod("POST") //
.withPath("serverUrl") //
.withBody(json(correctJsonString, MatchType.ONLY_MATCHING_FIELDS))) //
.respond(response().withStatusCode(200) //
.withHeaders(new Header("Content-Type", "application/json; charset=utf-8"),
new Header("Cache-Control", "public, max-age=86400"))
.withBody(responseJson));
I get a request didn't match expectation because: body didn't match, where the difference between the bodies are:
Request:
"body" : {
"type" : "STRING",
"string" : "{\"id\":33611,\"prop1\":28,\"prop2\":\"value2\",\"graph\":[...]}",
"contentType" : "text/plain; charset=utf-8"
}
Request should match:
"body" : {
"type" : "JSON",
"json" : "{\"prop2\":\"value2\",\"prop1\":28,\"graph\":[...]}"
}
So my questions:
Is it correct to assume that because of the type "JSON" <-> "STRING", the body doesn't match?
Is this a wrong interpretation of MockServer or does OkHttp generate the wrong request? (The request itself does work)
Any suggestions how to fix this?
Here is a JSON Demo:
#Test
public void testRemote3() {
String host = "localhost";
int port = 1080;
String url = String.format("http://%s:%d",host,port);
MockServerClient mockServerClient = new MockServerClient(host,port);
mockServerClient.when(
request()
.withMethod("POST")
.withPath("/order/completed/notify")
.withBody(new JsonBody("{\"username\":\"foo1\", \"age\": 13}", Charset.forName("UTF-8"),MatchType.STRICT))
).respond(
response().withStatusCode(200)
.withCookie("sessionId", "2By8LOhBmaW5nZXJwcmludCIlMDAzMW")
.withHeader("Location", "https://www.mock-server.com")
.withBody("{\"username\":\"wang\", \"status\": 1}")
);
mockServerClient.when(
request()
.withMethod("POST")
.withPath("/order/completed/notify")
.withBody(new JsonBody("{\"username\":\"zhao\", \"age\": 3}", Charset.forName("UTF-8"),MatchType.STRICT))
).respond(
response().withStatusCode(200)
.withCookie("sessionId", "2By8LOhBmaW5nZXJwcmludCIlMDAzMW")
.withHeader("Location", "https://www.mock-server.com")
.withBody("{\"username\":\"wang\", \"status\": true}")
);
log.info("----------------->calling ");
Map<String,Object> userInfo = new HashMap<>();
userInfo.put("age",13);
userInfo.put("username","foo1");
String result = OkHttpUtils.postJson(url+"/order/completed/notify",userInfo);
log.info(result);
Map<String,Object> fool = new HashMap<>();
fool.put("age",3);
fool.put("username","zhao");
result = OkHttpUtils.postJson(url+"/order/completed/notify",fool);
log.info(result);
}
So i am working this project on Xamarin forms, and get the error as in title on
var rootObject = deserial.Deserialize<RootObject>(gameJson);
I am supposed to return the list of games to my app.How can i remove the error?
public async Task<Game[]> GetGamesAsync(){
var client = new RestClient("http://mystore/");
var request = new RestRequest ("api/Games", Method.GET);
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
var apiKey = session ["ApiKey"];
var userId = session ["UserId"];
try
{
request.AddHeader ("authenticationkey",apiKey.ToString ());
request.AddHeader ("authenticationid",userId.ToString ());
}
catch{}
IRestResponse response = client.Execute (request);
statusCodeCheck (response);
var gameJson = response.Content;
if (response.StatusCode == HttpStatusCode.OK) {
RestSharp.Deserializers.JsonDeserializer deserial = new RestSharp.Deserializers.JsonDeserializer ();
var rootObject = deserial.Deserialize<RootObject>(gameJson);
return rootObject.games;
}
else if(response.StatusCode == HttpStatusCode.Forbidden){
return null;
}
}
Not sure you are looking for this but I also using Restsharp in portable library and I'm deserializing datacontracts with Json.NET's JsonConvert.DeserializeObject<T>
method. I have not encountered any problem with it yet.
Also another possible solution is that the returned data is wrapped and the main object is not the RootObject.
string URL="https://sampleservicebus.servicebus.windows.net/WinPhoneService/"
RestClient client = new RestClient(URL);
RestRequest request = new RestRequest("getkpimeasuredata", Method.POST);
KpiDomainData kpidata = new KpiDomainData();
kpidata.KPIId = 1006;
kpidata.ScorecardId = 3;
kpidata.EngineeringOrgId = 11;
kpidata.DataValuetypeId = 1;
kpidata.CumulativeMonth = 463;
kpidata.BusinessOrgId = 1;
string json = Newtonsoft.Json.JsonConvert.SerializeObject(kpidata);
json = "{\"kpidata\" : " + json + "}";
request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
ObservableCollection<KpiMeasureData> kpiDetailsList = await client.ExecuteTaskAsync<ObservableCollection<KpiMeasureData>>(request);
client.ExecuteAsync(request, response =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
}
});
When I debugged the wcf service code i came to know that the json data sent to getkpimeasuredata webmethod is null, I mean all the property values of the composite type were null even though I'm passing the data with values
And the Restcall works when I use Webclient instead of Restclient. But I need to use Restclient only. Please help.