Get role of current user in Sharepoint Online site using Microsoft Graph - .net-core

I am building a .net core web app in which i use AzureAD auth and Microsoft Graph to get data from a sharepoint online site.
I need to get the groups of the current user.
I tried to use graphClient.Me.MemberOf.Request().GetAsync();
I think i'm getting the role of the user in the Azure directory.
But i want the role of the current user for a specific sharepoint online site.
Is that possible to get this information and how ?
I don't find a working way to get this using Microsoft Graph.
EDIT:
As Microsoft Graph doesn't allow to get that data.
I tried to call the following Sharepoint Online API endpoint :
https://{name}.sharepoint.com/sites/{name}/_api/web/currentUser?$select=Groups/Title&$expand=Groups
Using this api endpoint i can see all the roles of the current user in my browser.
But i don't find how to call it from my .net core web app.
Tried the following :
var client = new HttpClient();
client.DefaultRequestHeaders.Add("Content-types", "application/json;odata=verbose");
var response = await client.GetAsync("https://{name}.sharepoint.com/sites/{name}/_api/web/currentUser?$select=Groups/Title&$expand=Groups");
if (response.IsSuccessStatusCode)
{
var json = await response.Content.ReadAsStringAsync();
}
But that give me a 403 response.
EDIT 2 :
I am currently trying to use CSOM to get this informations(TCUE.NetCore.SharepointOnline.CSOM.16.1.8029.1200.)
But i don't find a way to get TokenHelper.cs.
var token = TokenHelper.GetAppOnlyAccessToken(SharePointPrincipalId, webUri.Authority, null).AccessToken;
var ctx = TokenHelper.GetClientContextWithAccessToken(webUri.ToString(), token);
I tried to add "AppForSharePointOnlineWebToolkit" and it did not add the needed files in the project.
How can i get the TokenHelper.cs file ?
Thanks for any help.
Tristan

To execute CSOM code in .net core, do below settings.
We can install the package as below.
Install-Package TTCUE.NetCore.SharepointOnline.CSOM.16.1.8029.1200 -Version 16.1.8029.1200
More information is here: TTCUE.NetCore.SharepointOnline.CSOM.16.1.8029.1200
Or use the following solution from GitHub: NetCore.CSOM
Or follow the steps below.
1.Create a .NET Core console app.
2.Add the references: Microsoft.SharePoint.Client.Portable.dll, Microsoft.SharePoint.Client.Runtime.Portable.dll, and Microsoft.SharePoint.Client.Runtime.Windows.dll.
Note: If the project has references to Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll, please remove them.
These references can be accessed by installing CSOM library into another project, and then navigating to installed nuget packages in the file directory: c:\Users\user.nuget\packages\microsoft.sharepointonline.csom(version)\lib\netcore45
3.Add the code below to the .NET Core 2.0 console application:
Get current user role:
To get the current user role, you can use Web.GetUserEffectivePermissions method.
Ex:
ClientResult<BasePermissions> permission= web.GetUserEffectivePermissions(name);
context.ExecuteQuery();
var res = permission.Value;
Refer below link to get clientcontext using access token: https://www.sharepointpals.com/post/how-to-get-the-client-context-using-app-access-token-by-passing-client-id-and-client-secret-id-using-csom-in-sharepoint-office-365/

No. Microsoft Graph doesn't expose an endpoint that allows you to get the information of SharePoint Group and its members.
If you has this requirement, you could vote this idea on Microsoft Graph UserVoice.

Related

Send data from Share Extension to Xamatin.Forms app

I work on Share Extension. And it only has a sample project (following link) and a general extension documentation.
Basic project:
Extension documentation:
When I click share with my app on iphone (for example on photos), I want to send this file to my app and upload it remote server. But I couldn't find anyway to send object from share extension. I looked up and probably I need to use "NSUserDefaults" and I tried to use it that:
I did necessary settings (creating group id, app id etc) on my apple developer account.
I did necessary settings on my project Entitlements.plist
I try to send on ShareViewController - DidSelectPost method in the my project's share extension as below:
var default = new NSUserDefaults ("group.com.myapp.AppName", NSUserDefaultsType.SuiteName);
default.SetString ("Test content", "TestKey");
default.Synchronize ();
4)I try to receive string data on my main project's AppDelegate as below:
var default = new NSUserDefaults ("group.com.myapp.AppName", NSUserDefaultsType.SuiteName);
var key = default.StringForKey ("TestKey");
string value = key;
But I couldn't do it. And I saw someone did this with OpenUrl function. I tried this and this didn't work.
I started mobile programming with Xamarin forms and I don't know enough native iOS programming (I only learn with Xamarin). I think share extension has insufficient documentation.

Modelling an existing database in .NET Core 2.x

I have an existing application. I am trying to port some pieces over from .NET 4.x over to .NET Core. I have created a context in my .NET Core app. I have create a db context via scaffold-dbcontext. I can run a basic query (hooray). Life is good. Now, I want to add in some async queries. I get the following error:
System.InvalidOperationException: 'The provider for the source IQueryable doesn't implement IDbAsyncQueryProvider. Only providers that implement IDbAsyncQueryProvider can be used for Entity Framework asynchronous operations. For more details see http://go.microsoft.com/fwlink/?LinkId=287068.'
code:
var ctx = new GolfGameContext();
var userId = await (from u in ctx.AspNetUsers where u.Token == UserToken select u.Id).SingleAsync();
return userId;
This error seems strange. I have created some .NET Core 2.x apps from scratch and everything seems to work properly. I am able to do async queries with them just fine. When I look at the error link, I get taken to information about EF 6.x. I am guessing that there is something that the scaffold-dbcontext puts in the resulting models that cause this problem. I am also guessing that the code I have created in Core 2.x doesn't contain these same limitations. Am I on the right track? Do I need to change something in my context/models to get async to work properly? All thoughts are welcome.
TIA,
Wally

How to call a RESTful API with ASP.NET 5

Working with ASP.NET 5 on my Mac in Visual Studio Code. I have a RESTful API I need to call and not sure exactly how to do it. I've seen many examples using WebClient, HttpClient, WebRequest and HttpWebRequest.
I think my pain point is the dnxcore50 framework. Can someone please point me in the right direction with some code samples?
Here is an example about how to call a service. Please check the References and using carefully.
One important thing you have to do is install the Web API Client Libraries package: From the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command: Install-Package Microsoft.AspNet.WebApi.Client.
For the full source code, check this link.
I'm assuming it's the same way we used to do it prior to ASP .NET 5, so first you install the ASP .NET Web API Client Libraries NuGet package.
With that available, you reference System.Net.Http:
using System.Net.Http;
Then you use it as follows:
using (var httpClient = new HttpClient())
{
var response1 = await httpClient.GetAsync(url1);
var response2 = await httpClient.PostAsync(url2);
var response3 = await httpClient.SendAsync(url3);
}
That just gives you the response. Typically you'll want to look into the content, especially for GET requests. You can do this by:
var content = await response1.Content.ReadAsStringAsync();
That merely gives you the string in the content, so if it's JSON, you probably want to use something like JSON.NET (Newtonsoft.Json) to deserialize it into structured classes.
This is from memory so you might need a little tweak here and there.
To do this I'm using the NuGet feed https://api.nuget.org/v3/index.json
In my project.json I currently have these relevant dependencies and just use the "dnxcore50" framework:
"Microsoft.AspNet.WebApi.Client": "5.2.3",
"System.Net.Http": "4.0.0",
"System.Runtime.Serialization.Xml": "4.0.10"
Then I'm using HttpClient. Right now (beta7) it doesn't work on Linux or OSX because of https://github.com/dotnet/corefx/issues/2155.

Swagger w/ ASP.NET v5 Azure Api App

I'm attempting to set up a Api App (Azure) with Swagger + Swashbuckle as demonstrated by Scott Hanselman at the //Build conference here: http://channel9.msdn.com/Events/Build/2015/2-628.
I have installed (using NuGet) the packages Swagger.Api and Swashbuckle.Core. It hasn't added any controller or settings that I would expect in order to have a swagger page. When I navigate to {baseUrl}\swagger, I get a 404 error.
I would think that since it has a UI it would require a Web App in addition to the Api App, but I've rewatched the demo and Scott clearly says you can add Swagger + Swashbuckle to any Api App. In a 2nd app though I'd think there may be issues with Api discovery. Has anyone set this up yet successfully?
Time rolls on and now Swashbuckle works for vNext (beta8 for me, probably other versions too) - thank you to the team and contributors!
In project.json add the package:
"Swashbuckle": "6.0.0-*",
In startup.cs in ConfigureServices():
services.AddSwaggerGen();
services.ConfigureSwaggerDocument(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "My Super API",
Description = "A Super API using Swagger and Swashbuckle",
TermsOfService = ""
});
});
services.ConfigureSwaggerSchema(options =>{
options.DescribeAllEnumsAsStrings = true;
});
In startup.cs in Configure():
app.UseSwaggerGen();
app.UseSwaggerUi();
Now you can access your API doco - http://domain:port/swagger/ui/index.html
Access your Swagger definition - http://domain:port/swagger/v1/swagger.json
Then assuming you have at least one internet facing dev/uat/staging/prod environment, grab the definition URL then do File-> Import URI at http://editor.swagger.io/ - now you have code-gen for about 20 clients too :)
You can also setup your own code-gen server if you are so inclined too (https://github.com/swagger-api/swagger-codegen), however I leveraged the existing online generator. The online editor also has full model and relationship definitions too at least in my case where I fully defined my model using EF7 (I know, ick... but it's much better than <= EF6 and ServiceStack doesn't support CoreCLR, yet). Depending on the size of your project this could save you a few hours to a few weeks of work documenting, plus it is dynamically updating itself as you code more. And you can use it to test your endpoints too, but I still prefer PostMan.
Full sample project at https://github.com/mrsheepuk/ASPNETSelfCreatedTokenAuthExample/tree/beta8
Big ups to MrSheepUK
HTH
This answer is now outdated. See the other answer.
There is a nice blogpost describing the problem you have: https://alexanderzeitler.com/articles/Deploying-a-ASP-NET-MVC-6-API-as-Azure-API-App-in-Azure-App-Services/
This describes how you can add the Ahoy! package to an ASP.NET v6 Web Api project and adding this as an API app to Azure.
Here is another source: http://devmeetsbi.ghost.io/help-and-test-page-for-asp-net-web-api-asp-net-5-and-mvc-6/
You did all the right steps, but unfortunately for ASP.NET 5, Swashbuckle doesn't work yet.
You can get Ahoy! which is the next version of Swashbuckle that has ASP.NET v6 support here. That should make everything work.

Google Drive API - Example code is not working

I want to use Google API to transfer SharePoint Documents to Google Drive using dot net. For that to happen I want to use this link Google Quick Start.
I have followed every little piece of information. It states in beginning "Complete the steps described in the rest of this page, and in about five minutes you'll have a simple Drive app that uploads a file to Google Drive" but it is not true.
I am trying to run this sample example since yesterday but failed.
// Register the authenticator and create the service
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description, CLIENT_ID, CLIENT_SECRET);
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
So it seems that this code example is outdated and Google APIs have been upgraded.
Here comes the warning
[Obsolete("GoogleAuthenticationServer is not supported any more and it's going to be removed in 1.7.0-beta. Consider using the new Google.Apis.Auth NuGet package which supports .NET 4, .NET for Windows Store apps, Windows Phone 7.5 and 8 and Portable Class Libraries as well")]
Another code
var service = new DriveService(new BaseClientService.Initializer()
{
Authenticator = auth
});
And the error
Cannot implicitly convert type 'Google.Apis.Authentication.OAuth2.DotNetOpenAuth.NativeApplicationClient' to 'Google.Apis.Http.IConfigurableHttpClientInitializer'. An explicit conversion exists (are you missing a cast?)
Then I was looking for [latest release samples] there I found the source files.
I was not able able to run the sample also.
Here I was successfully authenticated but then had error for redirect Uri
My Client_Secrets.JSON looks like, as you can see I have set default redirect Uri to http://localhost/.
{"web":{"auth_uri":"https://accounts.google.com/o/oauth2/auth","client_secret":"secret","token_uri":"https://accounts.google.com/o/oauth2/token","client_email":email","redirect_uris":["http://localhost/"],"client_x509_cert_url":"aa#developer.gserviceaccount.com","client_id":"id","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","javascript_origins":["http://localhost:53404/"]}}
Now I can run this application but as mentioned getting error
Error: redirect_uri_mismatch
The redirect URI in the request: [[http://localhost:2430/authorize/]] did not match a registered redirect URI
I really don’t know from where this port number comes and from where this authorize comes. As you can see in my JSON, I have not set anything similar.
I am using VS 2010 SP1 Ultimate and Windows 7 home Basic.
I have tried to give complete information and my end goal is upload document in Google drive.
The tutorial you are following uses an older version of google.apis thats why you are seeing the not supported. Here are a couple of tutorials on how it works with the new version of the api.
http://daimto.com/google-oauth2-csharp/
http://daimto.com/google-drive-api-c/
Take a look in https://code.google.com/p/google-api-dotnet-client/source/browse/Tasks.ASP.NET.SimpleOAuth2/Default.aspx.cs?repo=samples. It's a Task API ASP.NET sample. As you can see you need to add several lines of code, but it works.
I downloaded the samples Eyal mentions and got that compiling before integrating with my own app. .Net needs to be 4 although it states it supports higher.
You have to set the redirect URI in the google developer console, not in your JSON. In your case, you would want to set it to http://localhost:2430/authorize/.

Resources