How to get authProvider for OneNote API - onenote-api

I'm using MS.Graph and trying to get a list of my OneNote Notebooks.
Here is the code I'm using.
IConfidentialClientApplication confidentialClientApplication = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantID)
.WithClientSecret(clientSecret)
.Build();
ClientCredentialProvider authProvider = new ClientCredentialProvider(confidentialClientApplication);
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var notebooks = await graphClient.Me.Onenote.Notebooks
.Request()
.GetAsync();
I can get the clientID, but where/how to I get the tenantID and clientSecret?

You might be able to get more info through this reference: https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS#client-credentials-provider

I used Microsoft.Graph.Auth (Pre-Release) from NuGet. That fixed the problem

Related

What is the right way to authenticate Azure Function against Azure DevOps REST API?

The goal is to develop an Azure function which should do some changes in Azure DevOps (like update work items, wiki pages etc), being triggered by Azure pipeline service hook.
Can I use function system identity in this case? And how can I give permissions for this identity to call DevOps REST APIs?
I'm not sure if this is the best way but you can create PAT token. Since you will use it for Azure Function I woudl recommend to use Azure KeyVault to store that token.
Here you have the example how you can use it to fetch projects from Azure DevOps:
public static async void GetProjects()
{
try
{
var personalaccesstoken = "PAT_FROM_WEBSITE";
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}", "", personalaccesstoken))));
using (HttpResponseMessage response = await client.GetAsync(
"https://dev.azure.com/{organization}/_apis/projects"))
{
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
Here you have documentation for updating work items. I tested that with Postman, but I was able to edit work item using PAT.

AmazonAutoScalingAsync client not seeing ASGs (Auto scaling Groups)

I've set up AmazonAutoScalingAsync client as well as many others but I'm unable to retrieve the existing ASGs.
BasicSessionCredentials sessionCredentials =
new BasicSessionCredentials(
credentials.getAccessKeyId(),
credentials.getSecretAccessKey(),
credentials.getSessionToken());
// Assume role
AWSSecurityTokenService sts_client_mfa =
AWSSecurityTokenServiceClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(sessionCredentials))
.build();
AssumeRoleRequest request =
new AssumeRoleRequest()
.withRoleSessionName("proserv-" + username)
.withRoleArn("myarn");
AssumeRoleResult response = sts_client_mfa.assumeRole(request);
Then I build the auto-scaling client as follows:
autoScalingClient =
AmazonAutoScalingAsyncClientBuilder.standard()
.withCredentials(
new AWSStaticCredentialsProvider(
new BasicSessionCredentials(
response.getCredentials().getAccessKeyId(),
response.getCredentials().getSecretAccessKey(),
response.getCredentials().getSessionToken())))
.withRegion(region)
.build();
These are the same steps I do from the AWS console but can't see the same results on the Java code.
getAutoScalingClient()
.describeAutoScalingGroupsAsync()
.get()
.getAutoScalingGroups()
.forEach(
group -> {
System.out.println(group);
});
getAutoScalingClient()
.describeAutoScalingInstancesAsync()
.get()
.getAutoScalingInstances()
.forEach(
entry -> {
System.out.println(entry);
});
Any thoughts?
Just figured it out. I was using the wrong region. After switching to the correct region it displayed as expected.

How do you get a list of all project iterations using the Azure DevOps Services .NET SDK?

I'd like to get a list of all the iterations for a given project in a Azure DevOps repository, using the .NET API.
Is there any example of how to do this? The current documentation (https://learn.microsoft.com/en-us/dotnet/api/microsoft.teamfoundation.work.webapi.workhttpclientbase.getteamiterationsasync?view=azure-devops-dotnet) is pretty thin.
Below is a working example of how to achieve this.
You need to reference Microsoft.TeamFoundation.Work.WebApi.
public async Task<List<TeamSettingsIteration>> GetProjectIterations(string serverUrl, string projectName)
{
var uri = new Uri(serverUrl);
var creds = new VssClientCredentials(new WindowsCredential(true), new VssFederatedCredential(true), CredentialPromptType.PromptIfNeeded);
var azureDevopsConnection = new VssConnection(uri, creds);
await azureDevopsConnection.ConnectAsync();
WorkHttpClient azureDevOpsWorkHttpClient = azureDevopsConnection.GetClient<WorkHttpClient>();
TeamContext teamContext = new TeamContext(projectName);
List<TeamSettingsIteration> results= await azureDevOpsWorkHttpClient.GetTeamIterationsAsync(teamContext);
return results;
}

How to make a GET Request using okhttp

I am new to Android Development and I would like to know how to perform a GET request using okhttp. I have referred http://square.github.io/okhttp/, but they only have examples of POST request. I have tried this -
okHttpClientLogin = new OkHttpClient();
requestBodyLogin = new FormBody.Builder()
.addEncoded("name", name_input) // params
.addEncoded("keys", keys_input) //params
.build();
requestLogin = new Request.Builder()
.addHeader("Authorization", token_type + " " +access_token)
.url(LOGIN_URL)
.get()
.build();
and got an Error :
{"status":{"status":206,"msg":"No record found"},"user":null}
I know why this error is coming, because the params have not been entered. I also tried passing requestBodyLogin inside .get() but it's not allowing.
Since OkHTTP 2.4, there's the function addQueryParameter. You can either use a HttpUrl, a String or a java.net.URL as url.
Basically, just create a new HttpUrl.Builder() and use the function addQueryParameter.
Example taken from the javadocs:
HttpUrl url = new HttpUrl.Builder()
.scheme("https")
.host("www.google.com")
.addPathSegment("search")
.addQueryParameter("q", "polar bears")
.build();
http://square.github.io/okhttp/3.x/okhttp/okhttp3/HttpUrl.html
http://square.github.io/okhttp/2.x/okhttp/com/squareup/okhttp/HttpUrl.Builder.html#addQueryParameter-java.lang.String-java.lang.String-

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