GithubHelp home page GithubHelp logo

microsoftgraph / aspnet-snippets-sample Goto Github PK

View Code? Open in Web Editor NEW
186.0 27.0 101.0 2.91 MB

A repository of code snippets that use Microsoft Graph to perform common tasks such as sending email, managing groups, and other activities from an ASP.NET Core MVC app. This sample uses the Microsoft Graph .NET Client Library to work with data, and the Microsoft Identity Web Library for authentication on the Microsoft identity platform v2.0 endpoint.

License: MIT License

C# 70.09% CSS 0.77% JavaScript 0.09% HTML 29.05%
devxsample

aspnet-snippets-sample's People

Contributors

baywet avatar christophwille avatar darrelmiller avatar jackson-woods avatar jamescro avatar jasonjoh avatar microsoft-github-policy-service[bot] avatar nokafor avatar o365devx avatar officegsx avatar peombwa avatar tfkram avatar v-dobr avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aspnet-snippets-sample's Issues

Request: Snippet for Group Scheme Extensions or ExtensionsProperties

Hello

I've found your snippets to be very helpful to move my project along. Right now I'm stuck on getting extensions attributes on a group. I realize you demonstrate openextensions, but I would prefer in this case to use schemeextensions or extensionproperties. The example below doesn't work when copying and pasting into graph explorer, I also couldn't get this to work via code. Received an access denied in both cases however I do have Directory.AccessAsUser.All.

(MicrosoftGraph-Scheme_Groups - Tried and receive access denied)
https://developer.microsoft.com/en-us/graph/docs/concepts/extensibility_schema_groups

Azure Graph, successfully created extensions, but I wasn't able to figure out how to use them with the graphserviceclient.
https://msdn.microsoft.com/en-us/library/azure/ad/graph/howto/azure-ad-graph-api-directory-schema-extensions?f=255&MSPPError=-2147217396

Example of an ExtensionProperty
`{

"odata.metadata": "https://graph.windows.net/mydomain/$metadata#directoryObjects/Microsoft.DirectoryServices.ExtensionProperty",

"value": [
    {
        "odata.type": "Microsoft.DirectoryServices.ExtensionProperty",
        "objectType": "ExtensionProperty",
        "objectId": "bd4cdaa3-3e9c-41a2-8308-8c10403c3989",
        "deletionTimestamp": null,
        "appDisplayName": "",
        "name": "extension_67183a58655d4977acd8a4815cbff2cd_SecondaryOwners",
        "dataType": "String",
        "isSyncedFromOnPremises": false,
        "targetObjects": [
            "Group"
        ]
    },`

How to set up open extension in application manifest under optionalclaims?

I added open extension to a user object. Then I added value for that open extension for user. Let’s say extension name is organisationId. How can I set up this extension in ad application manifest under optionalClaims to be returned to signed in user in claims?

In old ad graph api I created directory extension and then I applied name to optionalClaims like this extension_applicationId_organisationId, but how do I do it if I add open extension with new api? How to pass that open extension to claims to signed in user?

Calendar not working

I am having trouble getting the Calendar section of this demo to work.

All other sections, Mail, Users, Groups, Teams and Files all ask for User authentication when selected the for first time. Calendar does not, it reports this instead:

Error getting calendar view
Code: generalException
Message: An error occurred sending the request.

I have tried adding Calender.ReadWrite to the API permissions for both Delegated and Application permissions but it makes no difference.

Any help or pointers appreciated.

How to obtain a directory extension

Hello,
I'm trying to query a custom directory extension that was added to our user object. The extension is named extension_EXTENSION-ID_extensionName. I am able to use the Graph Explorer to obtain the directory extension: https://graph.microsoft.com/beta/users('{[email protected]}')?select=extension_EXTENSION-ID_extensionName

I realize the the Graph User object has a fixed model for which I can query and get Intellisense to return a list of properties for the user, however, my extension is not within this list. Is there a way to obtain this extension? And it is supported using the solution provided here?

Image src attribute in email body using microsoft graph

Is there sample code out there for getting an Office 365 email body with the embedded image using Microsoft Graph? So far I've only been able to get an image tag that the "src" attribute does not reflect anything that would display the image that looks something like this: <img src="cid:[email protected]"> and of course, that does not display any images.

Extended property operations Calendar

We have our current CRM, when we create a Calendar Event, we would like to add an "Extended Property" - single valued string (CRM Unique ID). This would allow us to retrieve only the Calendar Events in question with our CRM. Thank you for your help, Tim:

Creating class team

Hi;
I'm trying to add a new team as a class. But as i can see there is no sample for it.. When i googled i saw that need to get permission for scope eduroster.readwrite.all. But it's application permission... And all your samples works with delegated permissions.. Could you provide a sample to get graphclient for application permissions?

Get Attachment from Outlook using the HasAttachment Bool?

While attempting to get the attachment from Outlook, I have a problem using the message.hasattachement while checking to see which message has an attachment before getting the attachment; can you show example or further your example getting an attachment.
This works from the graph.microsoft.io
https://graph.microsoft.com/v1.0/me/MailFolders/Inbox/Messages?$select=webLink,subject,hasAttachments just can't get it into the Razor page --- ;(

added behavior notes:
a and b below work using the tool at graph.microsoft.io using a message with one attachment
a) //graph.microsoft.com/v1.0/me/mailFolders/inbox/messages/[message.id]/attachments?$select=name,size
b) //graph.microsoft.com/v1.0/me/mailFolders/inbox/messages/[message.id]/attachments/$count
the below seems to work and downloads to the page without the page having the capability to view so it's blank - or at least I didn't get an error.
c) //graph.microsoft.com/v1.0/me/mailFolders/inbox/messages/[message.id]/attachments

My problem exist while using the razor and "results", I'm trying to get that page to show "getmessage" the attachment (I've added gif for this) and then click the link (attachment name) which I have successfully got to the __ResultsPartial.cshtml page.
I had to use the below:
IMessageAttachmentsCollectionPage attachments = await graphClient.Me.Messages[message.Id].Attachments.Request().Select("Name,Size").GetAsync();

This is all a bit messy and any direction would be appreciated :)
Vr, Tim:
graph.microsoft.io

Where is the Resources resource?

I am trying to use the example for MS Graph Member of function. The example is the public class Groups Services. It has a using Resources statement but I have no Idea where the dll is to reference in the references section.

Please help. cannot find many examples and I need to figure out all the groups the current is a member of. The examples I do find are incomplete. (They leave information out :( )

500 (Internal Server)

Hi,

I am using telerik spreadsheet control in my project, and i have used owin startup class code for Microsoft authentication.

When i enter information in excel file and click on save i get attached error(see error.png)

If i comment " ConfigureAuth(app);" function in Startup.cs class file then its working fine.

Can you please provide solution on why telerik code conflicts with Microsoft owin code.

Looking forward to your quick reply.

Thank you.

How to create SharePoint documentSet using onedrive api?

OneDrive API's are used to interact with the SharePoint documentLibrary. In the sample i could see examples of creating files and folders within OneDrive, but i couldn't find examples for creating documentSets. Is this feasible, if so please update the examples?

App crashes on File menu with personal account

Can the sample application access files on personal account? I have posted a question on stack overflow regardin errors tryin to access files. Everything in app works well for personal login except app crashes on attempt to access any item on file menu? Should file menu be accessible from personal account? Do i need to set delegate permissions for this? I have set them after getting error and seeing the app asks for them in the code. I have been unable to use the file menu as app crashes when trying to load any of the menu choices under file menu. I would like to find out if this is user/dev error on my part when using sample as i followed the directions for using it explicitly and only deviated by adding extra permissions after it crashed on attempt to access file menu.

Thank you for taking an interest in Microsoft Graph development! Please feel free to ask a question here, but keep in mind the following:

  • This is not an official Microsoft support channel, and our ability to respond to questions here is limited. Questions about Graph, or questions about adding a new feature to the sample, will be answered on a best-effort basis.
  • Questions should be asked on Stack Overflow.
  • Issues with Microsoft Graph itself should be handled through support.

Missing files

I cloned this project locally. It has .net 5 dependencies, so I updated it to .net 7. I then updated all the nuget packages to their current versions. It will not build, I get 72 errors indicating missing classes. I wonder if they might have been renamed in a nuget package.
snippets build errors.txt

Unable to update Group description

I'm trying to update the description for a group that I have created through the API, but I'm getting an error message in return.

My code;

public static async Task<bool> UpdateGroup(GraphServiceClient graphClient, Group group)
   {
      try
      {
                await graphClient.Groups[group.Id].Request().UpdateAsync(new Group
                {
                    Description = group.Description
                });
                return true;
            }
            catch (Exception e)
            {
                throw;
            }
        }

The error;

Code: BadRequest
Message: Operation not supported.

I've checked the required permissions on Azure for "Microsoft Graph" and the option "Read and write all groups" is selected under both Application and Delegated permissions.

I can successfully create and delete groups so I'm assuming the permissions aren't the issue.
The code I'm using is from this repo so I'm not sure what to check to fix this.

Question: Turning off Implicit Flow

Wanting to make a new Web App using MSAL, the v2 Endpoint, and MS Graph I've learned that I want to avoid Implicit Flow when possible and instead opt for Authorization Code Flow for security.

This sample explicitly states:

Make sure the Allow Implicit Flow check box is selected

In order to use Hybrid Flow

Turning off Implicit Flow returns an error saying

Error.
An error occurred while processing your request.
unsupported_response_type

My question: Will there be an example showing how to do a similar sample without using Implicit Flow? More specifically an example using Authorization Code Flow?

Edit: Reworded question

Authentication Error - Value cannot be null. (Parameter 'value')

Describe the bug
Authentication Error - Value cannot be null. (Parameter 'value') seen on sign in after following steps in readme.md

image

To Reproduce
Steps to reproduce the behavior:

  1. Follow readme.md
  2. Navigate to https://localhost:5001
  3. Sign in with Azure AD account
  4. See error

Expected behavior

  1. Follow readme.md
  2. Navigate to https://localhost:5001
  3. Sign in with Azure AD account
  4. Access app as intended

Screenshots
If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

  • OS: Windows 10 19041.804
  • Browser: Edge
  • Version: 88.0.705.74

Dependency versions

  • Authentication library (MSAL, etc.) version: Version included with solution
  • Graph library (Graph SDK, REST library, etc.) version: Version included with solution

Unable to revise the security permissions via the Azure application registration

Right now, the readme file of this sample shows how to grant permissions for a specific user to use the Graph API. But if my application is designed so everyone in the O365 tenant could use that, then the current registration scheme is not scalable since I can't register a different application for each user. I need to use the Azure portal: https://portal.azure.com/#blade/Microsoft_AAD_IAM/ActiveDirectoryMenuBlade/RegisteredApps UI to create an application by saving the tenant global application ID and secret. Then I recognized that there are a bunch of delegated permissions granted on a per-user basis (14 of them through user consents) so I use the Azure UI instead of https://apps.dev.microsoft.com/ to grant a single App application for all users in the same tenant.

However, when I did that and trying to run the application to login, I got back a response error:
Sign In

Sorry, but we’re having trouble signing you in.
We received a bad request.

Additional technical information:
Correlation ID: f665b12b-999a-4110-ba1c-8b0c758df1d0
Timestamp: 2017-04-24 19:06:15Z
AADSTS70001: Application '5a8735c1-be64-496c-88ac-f0a1694021b4' is not supported for this API version.

I captured what the user consent permissions were granted for, and they are:
Read all users' basic profiles
View users' email address
View users' basic profile
Access user's data anytime
Sign in and read user profile
Read and write access to user profile
Sign users in
Send mail as a user
Have full access to user calendars
Read and write access to user mail
Have full access to user files
Access directory as the signed in user
Read and write all users' full profiles
Read and write all groups

Perhaps there is a way to provide a way to register the application via this Azure interface so I could get the permissions granted properly.

An exception is thrown when a user's manager is requested, and is null

When attempting to access the user's manager through the interface by clicking on the "Get my manager" link on the home page, an exception with the following message is thrown:

Resource 'manager' does not exist or one of its queried reference-property objects are not present.

The following is noted via a comment in the code in UsersController.cs/GetMyManager():

// Known issue: Throws exception if manager is null, with message "Resource 'manager' does not exist or one of its queried reference-property objects are not present."

This issue is created with the intent to both confirm from my own experience that it does exist (and indeed, only occurs if the user has no manager specified), and to formalize its existence through the Issues log.

ErrorAccessDenied when trying to get user photo

I tried using the get user photo in userServices but I get ErrorAccessDenied: Access Denied. Check credentials and try again. However all the other functions work such as GetUser and i was able to query all the information of a user other than the photo

Authorization_RequestDenied . Insufficient privileges to complete the operation

I have been added as a guest user in a tenant by cloud administrator.
i have been given directory roles of Application administrator , Application developer.
I am having scopes :
"Directory.AccessAsUser.All Directory.Read.All Directory.ReadWrite.All Group.Read.All Group.ReadWrite.All User.Invite.All User.Read User.ReadBasic.All User.ReadWrite User.ReadWrite.All"

I am using Graph client to update guest user mobile phone and department.

Issue i am getting is : Authorization_RequestDenied . Insufficient privileges to complete the operation

Questions i have:

  1. Can a guest user with application administrator role update a user profile ?
  2. I am doing it programaticaly .. so delegated permissions are sufficient ? or do i have to give application permissions as well for above scopes. if yes why ?
  3. solution for above error.

Thank you!

Get the User Group as part of the Authentication Process

How can we find out what group the user is member of during the Authentication Process - basically in the Startup_Auth.cs
I have a problem as how to make the graph call as admin during the authentication process.
Again, thank you for your direction, Tim:

Question: How to get the group picture along with group properties

I am able to retrieve all the required properties for all the group. To get the group image I have created another method. I am calling this method inside above all groups loop. Of course I am getting output and show the group name along with Image, but it is taking close to 20-25 secs since getGroupImage method is calling inside all groups loop.
My actual question is how to get the group image along with the group properties. If I see in the documentation there is no property mentioned about group image. How to get the group properties along with image in single call?

Sample is an Asp.net app but the app portal only supports javascript

I don't use .Net core, I don't use Javascript, the sample is ASP.NET 4.6 - ie real .NET for microsoft developers.
The instructions send you to the app portal which doesn't support microsoft products only IOS (not owned by microsoft), Android (ditto) and Javascript (wonderful scripting language also not microsoft).

This sample is thus useless for its intended audience.

Microsoft.Identity.Web.MicrosoftGraphExtensions AddMicrosoftGraph extension

Greetings!

I have a problem with AddMicrosoftGraph extension (from Microsoft.Identity.Web namespace, MicrosoftGraphExtensions class).

In tutorial you wrote about Microsoft.Identity.Web library with version 0.3-preview.
In my case I try to use it in 1.1 version, so I can't find this method.
Is this moved? And if yes where I can find it?

Thank you

Microsoft Graph is only for Azure AD?

I've read through the README.md and some of the controller classes. I've used the older Azure AD Graph API. Microsoft Graph looks like what I should use, if I want to use Azure AD. But I've also got to be able to use ADFS. So, I'd like to ask a clarifying question, am I correct in believing that Microsoft Graph is only for Azure AD?

Microsoft.Identity.Web v1.6.0 (IServiceCollection doesn't have AddSignIn)

After updating Identity.Web and Identity.Web.UI to any version after 0.1.5-preview,
In startup.cs, ConfigureServices function fails for the reason of (IServiceCollection doesn't have AddSignIn).

To Reproduce
Steps to reproduce the behavior:

  1. Update Microsoft.Identity.Web and Microsoft.Identity.Web.UI packages to any version above 0.1.5-preview
  2. Build Project
  3. See error

Expected behavior
Need implementation for especially adding the Microsoft.AspNetCore.Authentication.OpenIdConnect Events like OnAuthorizationCodeReceived, OnAuthenticationFailed,OnRemoteFailure

Dependency versions

  • Authentication library (MSAL, etc.) version: Same as last build
  • Graph library (Graph SDK, REST library, etc.) version: Microsoft.Graph, Version=3.6.0.0

Missing Areas?

This sample project has an anchor tag on the home page (<a class="btn btn-primary btn-large" asp-area="MicrosoftIdentity" asp-controller="Account" asp-action="SignIn">Click here to sign in</a>) which seems to point to an area named MicrosoftIdentity, but the project does not appear to contain any area definitions, and this link appears to point to nowhere.

Send Mail with Attachment - no error Sent Succeful but no attachment

Using the sample and working in the model MailService.cs,
I added HasAttachments = true,
I pass my Filename and FileData into the JSON like below:
while (rdr0.Read())
{
FileAttachment attachments = new FileAttachment
{
ODataType = "#microsoft.graph.fileAttachment",
Name = rdr0["FileName"].ToString(),
ContentBytes = rdr0["FileData"] as byte[]
};
}

   // Send the message.
    await graphClient.Me.SendMail(email, true).Request().PostAsync();

====
here is another attempt:
FileAttachment fileAttachment = new FileAttachment();

          {
            fileAttachment.ODataType = "#microsoft.graph.fileAttachment";
            fileAttachment.ContentBytes = rdr0["FileData"] as byte[];
            fileAttachment.Name = rdr0["FileName"].ToString();
        };

I get the message but don't get the attachment.
Any direction on sending the message with attachment?
Vr, Tim:
I must be missing something in the
Microsoft.Graph.IMessage.Attachments.CollectionPage
because I can not get anything converted or cast into it -- Thanks for the direction, Tim:

Issue with graph client accessing shared mailbox

I have a shared mailbox that I want to read the inbox messages. I modified the GetMyInboxMessages method and got an Access Denied error, even if I have full access.

Any idea how to get this to work for my shared mailbox (where the user id is a GUID in the example below)?

public async Task<List<ResultsItem>> GetMyInboxMessages(GraphServiceClient graphClient) 
{
    List<ResultsItem> items = new List<ResultsItem>();

    IMailFolderMessagesCollectionPage messages = await graphClient
        .Users["0f4331c1-57c1-48b1-8374-edd4f58b8c73"]
        .MailFolders
        .Inbox
        .Messages
        .Request()
        .GetAsync();

    if (messages?.Count > 0) {
        foreach (Message message in messages) {
            items.Add(new ResultsItem {
                Display = message.Subject,
                    Id = message.Id
            });
        }
    }
    return items;
}

ASP .Net Core samples?

Hi, I'm having trouble converting the example app to ASP .Net Core because some of the libraries are different or do not exist. Is there a plan to create another sample project that's suitable for ASP .Net Core? I've managed to use app.UseOpenIdConnectAuthentication to connect to my workplace's Azure AD, but not sure how to make the next step into calling the Graph API?

microsoft.graph client only pulls 10 emails

Maybe I'm just missing something on this but with the snippet /Mail/GetMyInboxMessages, it only brings back 10 records; if you can point to the answer here I would appreciate it.

Thank you for the snippets sample as it is very informative,
Vr, Tim:

MSAL.NET 3 - breaks these samples?

Not sure if this repo is still actively being worked on, but:

I just cloned this repo, and then corrected 8 or so build errors because of errors related to deprecated calls moving from MSAL.NET 2.0 to 3.0...

It builds fine, now, but the app immediately aborts after authentication with a error I am getting used to seeing:

Error.
An error occurred while processing your request.
See https://aka.ms/msal-net-3-breaking-changes

is anyone using MSAL.NET 3.0 successfully with these snippets?

Dave

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.