Enhanced Security Error while Visual Studio Team Services Rest API - rest

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());
}

Related

Rest API Post with parameters to get search result

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.

Pushing an update to VSTS via REST API

I am struggling with pushing an update to an existing file in a VSTS Git repository.
The documentation https://learn.microsoft.com/en-us/rest/api/vsts/git/pushes/create#update_a_file shows what to do.
When I use GET instead of POST, I get all existing pushes. So basically the request is working. This is my URL https://mine.visualstudio.com/_apis/git/repositories/ad3d7615-6e4a-4988-bd3f-ca80d7ec9791/pushes?api-version=4.1-preview.
I am testing the request from a console application. The body is created from a dynamic that is serialized later. The filecontent is a string var x=1;.
dynamic body = new
{
refUpdates = new[] { new { name = "refs/heads/master", oldObjectId = branchObjectId } },
commits = new[] {
new {
comment = "Updated Configuration" ,
changes = new[] {
new {
changeType = "edit",
item = new { path = "/files/filename.js"},
newContent = new { content = filecontent, contentType = "rawtext" }
}
}
}
}
};
The request looks like this:
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
byte[] login = Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "", personalaccesstoken));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(login));
var content = new StringContent(body, Encoding.UTF8, "application/json");
using (HttpResponseMessage response = client.PostAsync(url, content).Result)
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
responseBodyAction.Invoke(responseBody);
}
}
It is not successful, as the following Exception is thrown:
System.Net.Http.HttpRequestException: 'Response status code does not
indicate success: 404 (Not Found).
The body is a valid JSON.
Some API calls need the url .vsrm.visualstudio.com instead of .visualstudio.com. But not in this case.
I am out of ideas. Did anybody successfully push an update to VSTS and can show me how to do it?
As mentioned in a comment I was able to add instead of edit.
The solution is to first check in a file and then send an update/edit.
If there is no existing file, an edit will fail with the Exception.

Changing user folder collaborating type in box using Salesforce Toolbox

I'm trying to change Box folder collaboration type for user from salesforce Apex trigger. The first thoughts were to use box.Toolkit but it looks like this class does not have updateCollaboration or changeCollaboration method, only create. I guess my only option is to use Box's Rest API. Is there any way I can get service account token in Apex so I can use it in a callout?
I have created a special "Tokens" object in Salesforce with two fields: access token and refresh token. I then have a batch job that runs to update the access token every 55 minutes such that they never expired.
Here is a code snippet in APEX using the Tokens object.
#future(callout=true)
public static void updateTokens(){
//app info for authenticating
String clientID = 'MY_CLIENT_ID';
String clientSecret = 'MY_CLIENT_SECRET';
//look up value of existing refresh token
Token__c myToken = [SELECT Name, Value__c FROM Token__c WHERE Name='Refresh'];
Token__c myAccessToken = [SELECT Name, Value__c FROM Token__c WHERE Name='Access'];
String refreshToken = myToken.Value__c;
String accessToken = myAccessToken.Value__c;
//variables for storing data
String BoxJSON = '';
String debugTxt = '';
//callout to Box API to get new tokens
HttpRequest reqRefresh = new HttpRequest();
reqRefresh.setMethod('POST');
String endpointRefresh = 'https://www.box.com/api/oauth2/token';
reqRefresh.setEndpoint(endpointRefresh);
String requestBody = ('grant_type=refresh_token&refresh_token=' + refreshToken + '&client_id=' + clientID + '&client_secret=' + clientSecret);
reqRefresh.setBody(requestBody);
System.debug('Body of refresh request: ' + requestBody);
//Create Http, send request
Http httpRefresh = new Http();
Boolean successRefresh = false;
while (successRefresh == false){
try{
HTTPResponse resRefresh = httpRefresh.send(reqRefresh);
BoxJSON = resRefresh.getBody();
System.debug('Body of refresh response: ' + BoxJSON);
successRefresh = true;
}
catch (System.Exception e){
System.debug('Error refreshing: ' + string.valueof(e));
if (Test.isRunningTest()){
successRefresh = true;
}
}
}
Keep in mind that if you are using the Box for Salesforce integration your administrator can set the option for the permissions on the folders to sync with Salesforce permissions. This would reverse any changes you make to collaborations. Check out more about Box's Salesforce integration permissions here: https://support.box.com/hc/en-us/articles/202509066-Box-for-Salesforce-Administration#BfS_admin_perm

How can i post the feed to facebook page as admin using c# sdk?

I want to update the facebookpage using c# sdk. I have partially successful with this, the problem is whenever I post messages to the page, post is visible only for admin(i am the admin of the page)is logged In. I want the post or feed to be visible to every one who visit the page.
(even admin is logged out post's are not visible to admin also)
The following code i am trying to achieve
public ActionResult FacebookPagePost()
{
string app_id = "xxxx";
string app_secret = "xxx";
string scope = "publish_stream,manage_pages";
string page_Id = "xxX";
if (Request["code"] == null)
{
return Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
try
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
dynamic fbAccounts = client.Get("/me/accounts");
dynamic messagePost = new ExpandoObject();
messagePost.picture = "http://pic.com/pic.png";
messagePost.link = "http://www.examplearticle.com";
messagePost.name = "name goes here";
messagePost.description = "description goes here";
//Loop over the accounts looking for the ID that matches your destination ID (Fan Page ID)
foreach (dynamic account in fbAccounts.data) {
if (account.id == page_Id)
{
//When you find it, grab the associated access token and put it in the Dictionary to pass in the FB Post, then break out.
messagePost.access_token = account.access_token;
break;
}
}
client.Post("/" + page_Id + "/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
}
catch (Exception e)
{
}
}
}
1) Create a Facebook App at: developers.facebook.com and get yourself an APPID and APPSECRET. (there are a lot of tutorials online for doing this so I will skip repeating it)
2) Go to: http://developers.facebook.com/tools/explorer and choose your app from the dropdown and click "generate access token".
3) After that do the following steps here:
https://stackoverflow.com/questions/17197970/facebook-permanent-page-access-token to get yourself a permanent page token.
(I can not stress this enough, follow the steps carefully and thoroughly)*
*I have tool I built that does this for me, all I enter is the APPID, APPSECRET and ACCESSTOKEN which the tool then generates a permanent page token for me. Anyone is welcomed to use it and help make it better,
https://github.com/devfunkd/facebookpagetokengenerator
=========================================================================
Ok at this point you should have your APPID, APPSECRET and a PERMANENT PAGE TOKEN.
=========================================================================
In your Visual Studio solution:
4) Using Nuget:Install-Package Facebook
5) Implement the Facebook client:
public void PostMessage(string message)
{
try
{
var fb = new FacebookClient
{
AppId = ConfigurationManager.AppSettings.Get("FacebookAppID"),
AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"),
AccessToken = ConfigurationManager.AppSettings.Get("FacebookAccessToken")
};
dynamic result = fb.Post("me/feed", new
{
message = message
});
}
catch (Exception exception)
{
// Handle your exception
}
}
I hope this helps anyone who is struggling to figure this out.

DotNetOpenAuth Get Facebook Email Address

I have the following code where its grabbing First/Last name. I realize that email is an extended permission, but what would I need to modify to request extended permissions?
How do I get the email of an authenticated Facebook user through the DotNetOpenAuth?
fbClient = new FacebookClient
{
ClientIdentifier = ConfigurationManager.AppSettings["facebookAppID"],
ClientSecret = ConfigurationManager.AppSettings["facebookAppSecret"],
};
IAuthorizationState authorization = fbClient.ProcessUserAuthorization();
if (authorization == null)
{
// Kick off authorization request
fbClient.RequestUserAuthorization();
}
else
{
var request = WebRequest.Create("https://graph.facebook.com/me?access_token=" + Uri.EscapeDataString(authorization.AccessToken));
using (var response = request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var graph = FacebookGraph.Deserialize(responseStream);
// unique id for facebook based on their ID
FormsAuthentication.SetAuthCookie("fb-" + graph.Id, true);
return RedirectToAction("Index", "Admin");
}
}
}
return View("LogOn");
Add the following bits:
var scope = new List<string>();
scope.Add("email");
fbClient.RequestUserAuthorization(scope);
If you are using VS2012 built in oauth providers you just need to update your oauth package. See the last post on the following link: http://forums.asp.net/t/1847724.aspx/1. The only email I can't retrieve is MS Live. Currently I use facebook, google, and yahoo.