Microsoft Graph .Net API: Shared OneDrive folder - c#

I'm getting an invalid request error for the following (Message: One of the provided arguments is not acceptable):
DriveRecipient[] invitees = new DriveRecipient[1];
invitees[0] = new DriveRecipient()
{
Email = "testEmail#testdomain.com"
};
var test = await graphClient
.Me
.Drive
.Root
.ItemWithPath("/TestFolder")
.Invite(invitees, true, sendInvitation : true, message: "Test Message")
.Request()
.PostAsync();
I'm trying to share a folder (root/TestFolder) in OneDrive but am getting an invalid request error. Is it possible to share a folder this way? Or alternatively, how would I just create a shared folder, if this doesn't work?

You need to include the roles you want to apply ("read" and/or "write"):
var invitees = new List<DriveRecipient>();
invitees.Add(new DriveRecipient()
{
Email = "testEmail#testdomain.com"
});
var test = await client
.Me
.Drive
.Root
.ItemWithPath("/TestFolder")
.Invite(recipients: invitees,
requireSignIn: true,
sendInvitation: true,
message: "Test Invite",
roles: new List<string>() { "Read", "Write" })
.Request()
.PostAsync();

Related

MS Graph SDK retrive mailboxSettings return invalid user error

I tried to use MS Graph API to implement a backend API to access other users email setting (for getting out-of-office message). As it is backend API, client credential flow is used. I already granted the permissions "MailboxSettings.Read" and "MailboxSettings.ReadWrite" with application type.
I used my free Azure account for testing. Assume my login account is test#hotmail.com, then my Azure domain is testhotmail.onmicrosoft.com.
I created one more user client#testhotmail.onmicrosoft.com
I can get the result using Graph Explorer as below
https://graph.microsoft.com/v1.0/users/test#hotmail.com
https://graph.microsoft.com/v1.0/users/test#hotmail.com/mailboxSettings
https://graph.microsoft.com/v1.0/users/client#testhotmail.onmicrosoft.com
But it return error for below using Graph Explorer
{
"error": {
"code": "ErrorInvalidUser",
"message": "The requested user 'client#testhotmail.onmicrosoft.com' is invalid."
} }
https://graph.microsoft.com/v1.0/users/client#testhotmail.onmicrosoft.com/mailboxSettings
3a. If call by MS Graph SDK to get the user info for client#testhotmail.onmicrosoft.com as below, it is success
var scopes = new[] { "https://graph.microsoft.com/.default" };
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var user = await graphClient.Users["client#testhotmail.onmicrosoft.com"].Request().GetAsync();
3b. If call by MS Graph SDK to get the user info for test#hotmail.com, it returns error
Microsoft.Graph.ServiceException: 'Code: Request_ResourceNotFound
Message: Resource 'test#hotmail.com' does not exist or one of its
queried reference-property objects are not present.
var user = await graphClient.Users["test#hotmail.com"].Request().GetAsync();
If call by MS Graph SDK to get the mailbox setting as below, it returned error
Microsoft.Graph.ServiceException: 'Code: ErrorInvalidUser Message: The
requested user 'test#hotmail.com' is invalid.
var scopes = new[] { "https://graph.microsoft.com/.default" };
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var mail = await graphClient.Users["test#hotmail.com"].Request().Select("MailboxSettings").GetAsync();
Or returned error for below
Microsoft.Graph.ServiceException: 'Code: ResourceNotFound Message:
Resource could not be discovered.
var mail = await graphClient.Users["client#testhotmail.onmicrosoft.com"].Request().Select("MailboxSettings").GetAsync();
using Microsoft.Graph;
using Azure.Identity;
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "tenant_name.onmicrosoft.com";
var clientId = "aad_app_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var user = await graphClient.Users["xx#xx.onmicrosoft.com"]
.Request()
.Select("MailboxSettings")
.GetAsync();
var automaticRepliesSetting = user.MailboxSettings.AutomaticRepliesSetting;
Could you pls try this? By the way you may also try to add the 2 application permissions which mentioned in the document: MailboxSettings.Read, MailboxSettings.ReadWrite. And the most important is, your error message is invalid user, so I'm afraid you can use user_PrincipalName instead of myuser#hotmail.com. You can try to get the user_id in Azure AD potal or from the result for await graphClient.Users["myuser#hotmail.com"].Request().GetAsync();.
You are using hotmail.com , as per the doc you should also have either a personal Microsoft account with a mailbox on Outlook.com, or a Microsoft work or school account.
Hope this helps
Thanks

Copy a mail using Microsoft Graph C# SDK

I want to copy a mail from one folder to another.
Referring to the documentation, it should work like this:
var graphClient = new GraphServiceClient(authProvider);
var destinationId = "destinationId-value";
await graphClient.Me.Messages["{message-id}"]
.Copy(destinationId)
.Request()
.PostAsync();
However, when I try to use .Copy() like described I get the error, that I can't use it like a method. If I try to add the information as an [], like it's done for the users or messages property, I receive a different error.
I have tried it like this:
var graphClient = GetGraphClientInstance();
var destinationFolderId = "destinationFolderId-value";
await graphClient.Users["myUserName"].Messages[specificMail.Id]
.Copy(destinationFolderId )
.Request()
.PostAsync();
I'm using Microsoft.Graph version 5.0.0-preview-12.
Does anyone have an idea how to use the Copy property correctly?
Using Microsoft.Graph v5 your original code:
var graphClient = new GraphServiceClient(authProvider);
var destinationId = "destinationId-value";
await graphClient.Me.Messages["{message-id}"]
.Copy(destinationId)
.Request()
.PostAsync();
should be changed to:
var graphClient = new GraphServiceClient(authProvider);
var destinationId = "destinationId-value";
await graphClient.Users["myUserName"].Messages[specificMail.Id]
.MicrosoftGraphCopy
.PostAsync(new CopyPostRequestBody { DestinationId = destinationId });

Cannot update users with GraphClientService

While using newest version of Microsoft.Graph and Microsoft.Graph.Core libraries I am trying to execute following snippet to find user and then update him. User is found and retrieved but after executing Update method, program crashes. The application is .Net Framework 4.6.2. Not possible to upgrade due to other dependencies.
var builder = ConfidentialClientApplicationBuilder.CreateWithApplicationOptions(new ConfidentialClientApplicationOptions()
{
ClientId = "appId",
ClientSecret = "clientSecret",
TenantId = "tenantId"
});
var client = new GraphServiceClient(
new MicrosoftGraphAuthProvider(
builder.Build(),
new string[] {"https://graph.microsoft.com/.default" }));
var user = new Microsoft.Graph.User()
{
GivenName = "test",
Surname = "test",
Mail = "test#testmail.com"
};
var originalUser = await client.Users[upn]
.Request()
.Select("displayName")
.GetAsync();
await client.Users[originalUser.Id]
.Request()
.UpdateAsync(user);
Exception message
{"error":{"code":"Request_BadRequest","message":"Specified HTTP method is not allowed for the request target.","innerError":{"date":"2022-11-04T18:13:06","request-id":"","client-request-id":""}}}
First thoughts are to look at HTTP method used. But this is official distribution from Microsoft running against very slightly customized AzureAd tenant, so I would expect to work just like that. I am starting to be clueless. Gonna be helpful for ideas.
If you want to update user , you have to use
var result = await graphClient.Users[userId].Request().UpdateAsync(userUpdate);
doc - https://learn.microsoft.com/en-us/graph/sdks/create-requests?tabs=CS#updating-an-existing-entity-with-patch
Hope this helps ,
Thanks

Problem to send message to teams channel with Microsoft graph

I'm working to send a message to Teams by using Graph API.
my application is a daemon application that sends a message automatically in the background.
I have written code like an official reference link below:
https://learn.microsoft.com/en-gb/graph/sdks/choose-authentication-providers?tabs=CS#client-credentials-provider
in my case, I use the client-credentials-provider but, I still can't send a message, and always get the below error message.
surely I have already registered my application in Azure and set for the grant of scope
How can I fix this?
Following this api document, you need to give Application api permission Teamwork.Migrate.All, and try this code below:
using Azure.Identity;
using Microsoft.Graph;
public void sendMesgAsync()
{
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_app_client_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var chatMessage = new ChatMessage
{
Body = new ItemBody
{
Content = "Hello World"
}
};
await graphClient.Teams["{team-id}"].Channels["{channel-id}"].Messages
.Request()
.AddAsync(chatMessage);
}

C# Graph API TranslateExchangeIds().PostAsync() HTTP Method not allowed

I am using the C# package to Microsoft Graph API. I can read messages from the Graph API. Now I'd like to translate the message IDs like shown here:
https://learn.microsoft.com/de-de/graph/api/user-translateexchangeids?view=graph-rest-1.0&tabs=csharp
var translatedIds = client.Users[firstMailboxElement.SourcePostbox]
.TranslateExchangeIds(toBeTranslated, ExchangeIdFormat.RestImmutableEntryId, ExchangeIdFormat.RestId)
.Request()
.PostAsync()
.Result;
When I do so I get the following Exception:
System.AggregateException
One or more errors occurred.
(Code: Request_BadRequest Message: Specified HTTP method is not allowed for the request target.
Inner error: AdditionalData: date: 2021-12-15T06:52:45 [...])
Which does not seem to make sense, since I cant change the HTTP Method.
Any ideas how to fix this?
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_app_client_id";
var clientSecret = "client_secret";
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var inputIds = new List<String>()
{
"asdf"
};
var sourceIdType = ExchangeIdFormat.RestId;
var targetIdType = ExchangeIdFormat.RestImmutableEntryId;
var res = graphClient.Users["user_id"].TranslateExchangeIds(inputIds, targetIdType, sourceIdType).Request().PostAsync();
var a = res.Result;
I figured out, that the firstMailboxElement.SourcePostbox was null, when the exception occoured.
So the call went to client.Users[null], so the request URL was incomplete.

Categories