Updating Azure Application via Microsoft Graph SDK - c#

I am using the Microsoft Graph SDK (https://github.com/microsoftgraph/msgraph-sdk-dotnet) in my .NET Core 3.1 project logged in to my Service Principal. I can retrieve the Azure Application's Web Reply URLs:
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var rootItem = await graphClient.Applications.Request().GetAsync();
Microsoft.Graph.Application app = new Microsoft.Graph.Application();
foreach (var item in rootItem)
{
if (item.DisplayName.Equals("MyApp"))
{
app = item;
}
}
I am able to retrieve the actual Application object just fine. My question is, how do I update app.Web.RedirectUris through the SDK? I am able to do so via the Azure CLI with az ad app update --id <my_app_id> --reply-urls <url_1> <url_2>

You need to get an Microsoft.Graph.IApplicationRequestBuilder for the specific Application and then call UpdateAsync() method.
var rootItem = await client.Applications.Request().GetAsync();
Microsoft.Graph.Application app = new Microsoft.Graph.Application();
foreach (var item in rootItem)
{
if (item.DisplayName.Equals("MyApp"))
{
app = item;
app.Web.RedirectUris = new List<string> { "uri1", "uri2" };
await client.Applications[app.Id].Request().UpdateAsync(app);
}
}

Related

I need to retrieve the Application Insights's InstrumentationKey using C# code

I have created the application Insights using ARM template with C# code.
var creds = new AzureCredentialsFactory().FromServicePrincipal(client, key, tenant, AzureEnvironment.AzureGlobalCloud);
IAzure azure = Microsoft.Azure.Management.Fluent.Azure.Authenticate(creds).WithSubscription(subscription);
IDeployment deployement = azure.Deployments.Define("my-app")
.WithExistingResourceGroup("my-rg-grp")
.WithTemplate(template)
.WithParameters("{}")
.WithMode(DeploymentMode.Incremental)
.CreateAsync();
deployment doesn't have the InstrumentationKey in response.
How could I get the InstrumentationKey just after the Application Insights creation using ARM?
You can use ApplicationInsightsManagementClient class to get the ApplicationInsights resources and the relevant property. The class is defined at Microsoft.Azure.Management.ApplicationInsights v0.3.0-preview package
ApplicationInsightsManagementClient applicationInsightsManagementClient =
new ApplicationInsightsManagementClient(creds) { SubscriptionId = subscriptionId };
var appliationInsightComponents = await applicationInsightsManagementClient.Components.ListAsync();
var requiredApplicationInsightComponent = appliationInsightComponents.SingleOrDefault(a =>
a.ApplicationId.Equals("<<Name of resource>>", StringComparison.OrdinalIgnoreCase));
// to get the InstrumentationKey use
requiredApplicationInsightComponent.InstrumentationKey

how to create a web service for microsoft graph (C#)

I've recently started working as a junior c# developer. My boss asked me to build methods to CRUD teams in our AAD using the microsoft graph API. I've achieved this with a test application like that:
public async Task<string> createTeam()
{
// readying data from registry
var clientId = "********************"; //application (client) ID
var clientSecret = "********************";
var redirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient";
var authority = "https://login.microsoftonline.com/********************/v2.0";
var cca = ConfidentialClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.WithRedirectUri(redirectUri)
.WithClientSecret(clientSecret)
.Build();
List<string> scopes = new List<string>
{
"https://graph.microsoft.com/.default"
};
//
var authenticationProvider = new MsalAuthenticationProvider(cca, scopes.ToArray());
//
GraphServiceClient graphClient = new GraphServiceClient(authenticationProvider);
// Code to create a Team
var team = new Team
{
DisplayName = "0000My Sample Team",
Description = "My Sample Team’s Description",
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
}
};
var result = await graphClient.Teams.Request().AddAsync(team);
return result.DisplayName;
}
With that piece of code working, I've created an asp.net web Application (.net framework) and added the class to it. The plan was to deploy it to an IIS server and and publish the methods as web services.
[WebMethod]
public async Task<string> createTeamAsync()
{
//The class where my methods reside
TeamServices ts = new TeamServices();
var result = await ts.createTeam();
return "OK";
}
I registered the app and deployed but when I try to use it, it does not create any Team.
Do you know what I'm doing wrong of what I should learn next get the app working? Im just a few weeks in c# and I'm completely lost in all that .net echosystem
Thanks in advance

CSOM troubles with sharepoint online

I'm having some trouble with CSOM.
I'm trying to get the title of Sharepoint site, but unfortunately I'm getting this error => the remote server returned an error: (401) Unauthorized.
using (var context = GetClientContext("https://tenant.sharepoint.com/"))
{
context.Load(context.Web, p => p.Title);
await context.ExecuteQueryAsync();
Console.WriteLine($"Title: {context.Web.Title}");
}
public ClientContext GetClientContext(string targetUrl)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.ExecutingWebRequest +=
delegate (object oSender, WebRequestEventArgs webRequestEventArgs)
{
string token = GetToken();
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + token;
};
return clientContext }
public string GetToken()
{
IConfidentialClientApplication app;
var instance = "https://login.microsoftonline.com/{0}";
var tenant = "tenantId";
var authority = String.Format(CultureInfo.InvariantCulture, instance, tenant);
string[] scopes = new string[] { "https://tenant.sharepoint.com/.default" };
app = ConfidentialClientApplicationBuilder
.Create("clientId")
.WithClientSecret("secretId")
.WithAuthority(new Uri(authority))
.Build();
AuthenticationResult result = app.AcquireTokenForClient(scopes)
.ExecuteAsync().GetAwaiter().GetResult();
return result.AccessToken;
}
This is the permissions for the appRegistration
App Registration
But i can get it from a graph call
If want to use App Only permission in SharePoint Online CSOM, please register SharePoint Add-in instead of Azure AD's with this url:
https://tenant.sharepoint.com/_layouts/15/appregnew.aspx
Then set add-in permission using this xml in https:// TenantName-admin.sharepoint.com/_layouts/15/appinv.aspx:
<AppPermissionRequests AllowAppOnlyPolicy="true">
<AppPermissionRequest Scope="http://sharepoint/content/tenant" Right="FullControl" />
</AppPermissionRequests>
Then install SharePointPnPCoreOnline Package using Nuget and call like this:
using OfficeDevPnP.Core;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Client;
string siteUrl = "https://tenant.sharepoint.com/sites/demo";
using (var cc = new AuthenticationManager().GetAppOnlyAuthenticatedContext(siteUrl, "[Your Client ID]", "[Your Client Secret]"))
{
cc.Load(cc.Web, p => p.Title);
cc.ExecuteQuery();
Console.WriteLine(cc.Web.Title);
};
Here is a compeleted demo for your reference:
Connect To SharePoint Online Site With App Only Authentication

404 error while creating Online Meeting using microsoft graph api c# without login into AzureActiveDirectory

I am trying to create Online Meeting using microsoft graph api without login into AzureActiveDirectory with asp.net web application.For this my app has below permissions which are required as per documentation https://learn.microsoft.com/en-us/graph/api/application-post-onlinemeetings?view=graph-rest-1.0&tabs=csharp with client credential auth flow https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow without immediate interaction with a user.I am able to retrive access token successfully as per client-creds-grant-flow.
I tried Micosoft.Graph and Micosoft.Graph.Beta still getting 404 error.
Create online meeting code
var graphClient = GetAuthenticatedClientCredential();
var onlineMeeting = new OnlineMeeting
{
StartDateTime = DateTimeOffset.Parse("2020-10-01T10:30:34.2444915+00:00"),
EndDateTime = DateTimeOffset.Parse("2020-10-01T11:00:34.2464912+00:00"),
Subject = "Create Online Meeting-Without user login to Office 365"
};
return await graphClient.Me.OnlineMeetings
.Request()
.AddAsync(onlineMeeting);
Access Token code
public static async Task<string> GetUserAccessTokenAsyncByCc()
{
IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(appId)
.WithTenantId(appTenantId)
.WithClientSecret(appSecret)
.Build();
string[] scopes1 = new string[] { "https://graph.microsoft.com/.default" };
//string[] scopes1 = new string[] { "https://graph.microsoft.com/OnlineMeetings.ReadWrite.All" };
// string[] scopes1 = new string[] { "https://graph.microsoft.com/beta/OnlineMeetings.Read.All" };
//string[] scopes1 = new string[] { "https://graph.microsoft.com/beta/.default" };
var result = await cca.AcquireTokenForClient(scopes1).ExecuteAsync();
return result.AccessToken;
}
and Auth Provider code
public static GraphServiceClient GetAuthenticatedClientCredential()
{
DelegateAuthenticationProvider provider = new DelegateAuthenticationProvider(
async (requestMessage) =>
{
string accessToken = await GetUserAccessTokenAsyncByCc();
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
});
GraphServiceClient graphClient = new GraphServiceClient(provider);
return graphClient;
}
app permission image
below are the necessary app permission
You can only use delegated permissions to create an onlineMeeting, so you must log in as a user, and you cannot use the client credential flow. You need to use the auth code flow to obtain the token.

Updates a single work item Azure Devops using Asp.net

I am trying to update work item in Azure devops using this API : https://learn.microsoft.com/en-us/rest/api/azure/devops/wit/work%20items/update?view=azure-devops-rest-5.1#update-a-field .
But i can't find the way to do this.
You should use http client to call Rest API. Sample code as below:
private readonly WorkItemTrackingHttpClient _workItemTrackingHttpClient;
public RestApi(string baseUrl, string pat)
{
var vssConnection = new VssConnection(new Uri(baseUrl), new VssBasicCredential(string.Empty, pat));
_workItemTrackingHttpClient = vssConnection.GetClient<WorkItemTrackingHttpClient>();
var document = new JsonPatchDocument();
document.Add(new JsonPatchOperation()
{
Operation = Operation.Add,
Path = "/fields/Microsoft.VSTS.Scheduling.Effort",
Value = 1
});
var workItem = _workItemTrackingHttpClient.UpdateWorkItemAsync(document, 233843).Result;
}
Besides, you could also use client API, details you could take a look at our official doc here-- Fetch work items with queries programmatically in Azure DevOps Services

Categories