Rest API Post with parameters to get search result - rest

I am in Xamarin Forms and making rest calls to an API, I am new to this. I am wanting to send my search parameters which is:
{ "busObIds": [
"8102508"], "searchText": "John"}
(this the raw JSON format) to the API endpoint:
var client = new RestClient("http://localhost/NameAPI/api/V1/getquicksearchresults");
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer " + bearer);
I also have an Authorization Bearer i need to apply. I am stumbling through this and not sure how to do this correctly, as I was shown how to do in Postman but currently can not convert that into my project in Visual Studio Xamarin Forms. Help please if you can.
So am I doing this correct?
Do i need to serialize my JSON in model class?
Am i posting or getting? as it says POST but im not confident I am doing right.
Do i post my parameters in the AddHeader?
Anyway thank you in advance.
Update:
var _client = new RestClient("http://localhost/NameAPI/api/V1/getquicksearchresults");
var request = new RestRequest(Method.POST);
request.AddHeader("Accept", "application/json");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Authorization", "Bearer " + bearer);
request.AddParameter("busObIds", "8102508");
request.AddParameter("searchText", "John");
IRestResponse response = _client.Execute(request);
var jsonData = response.Content;
var jsonObj = JsonConvert.DeserializeObject<CiResponse>(jsonData);
this.CiList = new ObservableCollection<CiItem>();
if (null != jsonObj && jsonObj.Types != null && jsonObj.Types.Count > 0)
{
foreach (var item in jsonObj.Types)
this.CIList.Add(new CiItem
{
PublicId = item.PublicId,
SubTitle = item.SubTitle,
Text = item.Text,
Title = item.Title
});
}
When running i have no indication that its incorrect, but no output showing on screen.

Related

Update wiki page of tfs by calling rest-api

I want to update an already existing wiki page of tfs by using this document:
https://learn.microsoft.com/de-de/rest/api/azure/devops/wiki/pages/create%20or%20update?view=azure-devops-rest-4.1
Creating a new wiki-page (with content) is no problem. That is working fine.
But I want to edit an existing one. The tfs-documentation says that the only difference in API call is to use an "If-Match"-header (see section Request Header).
Here I have 3 situations:
Using no "If-Match"-Header or an empty: Get a "412 Precondition Failed" error.
Using a "If-Match"-Header with random value: Get a "400 Bad Request" error.
Using a "If-Match"-Header with exactly 40 characters (like the version-hash of the page-revision (e.g. '09f62be600a3b6d36d21b294dbb00921a5ba03ec')): Again "412 Precondition Failed" error.
I think the revision-hash (40 characters) should be a good way because the error message on non-40-chars returns the 400-error.
But it did not work? Has anyone an idea which id tfs is wanting? I used Postman and C# to update by API. Below you can see my example code:
var handler = new HttpClientHandler()
{
UseDefaultCredentials = true,
UseProxy = false,
};
var client = new HttpClient(handler);
client.BaseAddress = new Uri(".../pages/pagename" + "?api-version=4.1");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var putContent = new StringContent("{ \"content\": \"New content for page\" }", Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.TryAddWithoutValidation("If-Match", "09f62be600a3b6d36d21b294dbb00921a5ba03ec");
var responseTask = client.PutAsync(client.BaseAddress, putContent);
var result = responseTask.Result;
var content = result.Content.ReadAsStringAsync().Result;
var code = result.StatusCode;
var body = content;
According to the Create or Update Wiki API, if we want to edit the wiki page,If-Match header is required. The value of If-Matchth is the wiki page ETag.
ETags can also be used for optimistic concurrency control, as a way to help prevent simultaneous updates of a resource from overwriting each other
so we need to get the wiki Etag before update. Please have a try to change the code as following:
var baseUrl = "xxxxx";
var handler = new HttpClientHandler()
{
UseDefaultCredentials = true,
UseProxy = false,
};
var client = new HttpClient(handler)
{
BaseAddress = new Uri(baseUrl)
};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "YourToken");
var getResult = client.GetAsync(baseUrl).Result;
var etag = getResult.Headers.GetValues("ETag");
var putContent = new StringContent("{ \"content\": \"New content for page\" }", Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.TryAddWithoutValidation("If-Match", etag);
var responseTask = client.PutAsync(client.BaseAddress, putContent);
var result = responseTask.Result;
var content = result.Content.ReadAsStringAsync().Result;
Test Result:

Enhanced Security Error while Visual Studio Team Services Rest API

I'm currently trying to use the Rest APIs exposed by Visual Studio Team Services (was Visual Studio Online) to obtain work item information. I seem to be able to connect however when I look at the response to my query its a html page with a Enhanced Security Error message. I believe that this is due to the Enhanced Security option in IE but I'm calling this from my client machine and I can only see options on how to turn this off on a server.
this is the call i'm making
using (var client = new HttpClient())
{
var token = "xxxxxxxxxxxx";
var apiVersion = "1.0";
var account = "xxxxxxxx";
var query = "Select [System.Id] From WorkItems Where[System.WorkItemType] = 'WorkItem' order by [System.CreatedDate] desc";
var url = "https://" + account + ".visualstudio.com/Core/_apis/wit/";
// Execute a query that returns work item IDs matching the specified criteria
using (var request = new HttpRequestMessage(HttpMethod.Post, url + "wiql"))
{
request.Headers.Add("Authorization", "Bearer " + token);
request.Headers.Add("Accept", "application/json;api-version=" + apiVersion);
Dictionary<string, string> body = new Dictionary<string, string>
{
{
"query", query
}
};
request.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
using (var response = await client.SendAsync(request))
{
var content = await response.Content.ReadAsStringAsync();
var workItems = JObject.Parse(content)["workItems"] as JArray;
string[] ids = workItems.Select<JToken, string>(w => (w["id"] + "")).Take(10).ToArray<string>();
string idsString = String.Join(",", ids);
// Get details for the last 10
using (var detailsRequest = new HttpRequestMessage(HttpMethod.Get, url + "workitems?ids=" + idsString + "&fields=System.Id,System.Title"))
{
detailsRequest.Headers.Add("Authorization", "Bearer " + token);
detailsRequest.Headers.Add("Accept", "application/json;api-version=" + apiVersion);
using (var detailsResponse = await client.SendAsync(detailsRequest))
{
var detailsContent = await detailsResponse.Content.ReadAsStringAsync();
var detailsWorkItems = JObject.Parse(detailsContent)["value"] as JArray;
foreach (dynamic workItem in detailsWorkItems)
{
Console.WriteLine("Work item: {0} ({1})",
workItem.fields["System.Id"],
workItem.fields["System.Title"]
);
}
}
}
}
}
}
any help with this would be appreciated,
thanks
Chris
You can add related sites to trusted sites (for example: https://app.vssps.visualstudio.com, https://login.live.com etc…).
Internet option=>Security
Select Trusted sites
Click sites
Type website address and click add
The simple way to know which URLs need to be added, you could send a simple Get Rest request (e.g. get work item REST API), it will pop up a window that contains site URL (will pop up many times for different URL), add these URL to trusted sites list.
Update:
Based on the response result, it isn’t related to enhanced security, the result means it isn’t authenticated. So the token is invalid, it is access token of OAuth, you need to get access token after register your app to VSTS.
More information, you can refer to this article.
There is a OAuth sample that you can refer. After you get access token, add it to request header and retrieve data from VSTS.
If you want to access VSTS through personal access token, the code like this: (check this article)
try
{
var username = "username";
var password = "password";
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}", username, password))));
using (HttpResponseMessage response = client.GetAsync(
"https://{account}.visualstudio.com/DefaultCollection/_apis/build/builds").Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}

making a REST calls from unity3d - Need to pass JSON object using HTTPWebRequest

How to make a REST call in unity3d? especially POST method. I have tried with GET request. Pls see the below get request. so i need to write POST request in Unity3d. The post rquest should be in JSON format. I tried with below code. It's hit the my service but the receiving JSON object is null. Hope your support.
var httpWebReq = WebRequest.Create("http://localhost:6091/UserService.svc/RegisterUser/") as HttpWebRequest;
httpWebReq.ContentType = "text/json;charset=utf-8";
httpWebReq.Method= "POST";
using(var streamWriter = new StreamWriter(httpWebReq.GetRequestStream()))
{
string user = "{UserID:0," +
"Email:'ruwan#gmail.com'," +
"Password:'ruwan123'," +
"NickName:'ruwa'," +
"Age:35" +
"}";
byte[] formData = UTF8Encoding.UTF8.GetBytes(user);
httpWebReq.ContentLength = formData.Length;
streamWriter.Write(formData);
}
var httpResponse = (HttpWebResponse)httpWebReq.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
//Now you have your response.
//or false depending on information in the response
Debug.Log(responseText);
}
use WWW for GET,
use WWW with WWWForm for POST.
Finally i got the solution thanks to all for help.
Actually the easiest way to make rest call for WCF is we have to add the Newtonsoft.Json. Finally my code is-
GET --
WebClient myWebClient = new WebClient();
myWebClient.Encoding = Encoding.UTF8;
myWebClient.Headers.Add("Content-Type", "text/json");
var json = JsonConvert.DeserializeObject<Room[] >(new WebClient().DownloadString("Your URL"));
List<yourclass> test1= new List<yourclass>();
foreach (var test in json)
{
test1.Add(new yourclass()
{
yourclass.property1 = test.property1
});
}
Debug.Log(test1);
POST---
WebClient myWebClient = new WebClient();
var Test = JsonConvert.SerializeObject(new
{
YourProperty= 0
}, new JsonSerializerSettings() { Formatting = Newtonsoft.Json.Formatting.None });
myWebClient.Encoding = Encoding.UTF8;
myWebClient.Headers.Add("Content-Type", "text/json");
string responsebody = myWebClient.UploadString("Your URL", "POST", Test );
//if(responsebody == true)
Debug.Log(responsebody);

How to retrieve image files from Sharepoint Image Library (List) through REST API using C# in Windows Store App

I am building a Windows Store App where I have to upload and download images from a SharePoint 2013 site. I tried the REST API but all I am getting is XML data containing the properties of the file but I am not able to get the actual file. Can someone please help me with this?
Following is the code that I am trying with:
HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = false;
handler.Credentials = new NetworkCredential(userName, password, domain);
HttpClient client = new HttpClient(handler);
client.DefaultRequestHeaders.Add("Accept", "application/atom+xml");
client.DefaultRequestHeaders.Add("ContentType", "application/atom+xml;type=entry");
var response = await client.GetAsync("server/site/_api/web/ListName/Items(1)/File");
Byte[] bArray = await response.Content.ReadAsByteArrayAsync();
The following example demonstrates how to retrieve a specific file content from library:
url: http://site url/_api/web/lists/getbytitle('<list title>')/items(<item id>)/File/$value
method: GET
headers:
Authorization: "Bearer " + accessToken
Example
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var response = client.GetAsync("https://tenant.sharepoint.com/_api/web/lists/getbytitle('Documents')/items(1)/File/$value", HttpCompletionOption.ResponseHeadersRead).Result;
var fileContent = response.Content.ReadAsByteArrayAsync().Result;
References
Working with folders and files with REST

Azure REST WebClient PUT Blob

I'm trying to simply upload a new blob to an Azure Storage countainer using WebClient like this :
var sas = "[a new generated sas with Read, Write, List & Delete permissions]";
var sData = "This is a test!";
var sEndPoint = "http://myaccount.blob.core.windows.net/mycontainer/MyTest.txt" + sas;
var clt = new WebClient();
var res = await clt.UploadStringTaskAsync(sEndPoint, "PUT", sData);
This is giving me a "(400) Bad Request." error. Am I doing anything wrong here?
Thanks
(By the way, I need to use REST instead of Client API since I'm in a Silverlight project)
You would need to define a request header (x-ms-blob-type) for blob type and set it's value to BlockBlob. Also for Put requests you would need to define the Content-Length request header as well. I wrote a blog post on Shared Access Signatures and performing some blob operations using that (with both REST API and Storage Client library) which you can read here: http://gauravmantri.com/2013/02/13/revisiting-windows-azure-shared-access-signature/.
and here's the code from that post on uploading blob. It uses HttpWebRequest/HttpWebResponse instead of WebClient:
static void UploadBlobWithRestAPISasPermissionOnBlobContainer(string blobContainerSasUri)
{
string blobName = "sample.txt";
string sampleContent = "This is sample text.";
int contentLength = Encoding.UTF8.GetByteCount(sampleContent);
string queryString = (new Uri(blobContainerSasUri)).Query;
string blobContainerUri = blobContainerSasUri.Substring(0, blobContainerSasUri.Length - queryString.Length);
string requestUri = string.Format(CultureInfo.InvariantCulture, "{0}/{1}{2}", blobContainerUri, blobName, queryString);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUri);
request.Method = "PUT";
request.Headers.Add("x-ms-blob-type", "BlockBlob");
request.ContentLength = contentLength;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(Encoding.UTF8.GetBytes(sampleContent), 0, contentLength);
}
using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse())
{
}
}
When testing against the blob emulator this is the code I need to get it working:
var connection = ConfigurationManager.AppSettings["AzureStorageConnectionString"];
var storageAccount = CloudStorageAccount.Parse(connection);
var client = new WebClient();
client.Headers.Add("x-ms-blob-type", "BlockBlob");
client.Headers.Add("x-ms-version", "2012-02-12");
client.UploadData(string.Format(#"{0}/$root/{1}{2}", storageAccount.BlobEndpoint, myFileName, sharedAccessSignature), "PUT", _content);