How to add a the query options to my graphclient request - c#

I'm trying a to add query options to my graphclient. According to the documentation, this should be possible. However, I always get the message that the request property is no longer present in the Microsoft.Graph nuget. Which is strange. Downgrading to older versions does not help.
I'm trying to do something like this:
var options = new List<QueryOption>
{
new QueryOption("$select=internetMessageHeaders")
}
var mimeContent = await graphClient
.Users[TestProperties.UserEmail]
.Messages[specificMailResponse.Id]
.Request(options)
.GetAsync();
Can anyone tell me what I am doing wrong and why the request property no longer exists?
I'm using Microsoft.Graph 5.0.0-preview.10
At the end of the documentation my example is described https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/dev/docs/upgrade-to-v4.md

Related

Is there a way to start a Microsoft Teams Channel meeting using C#?

We are wanting to start a Teams Channel meeting using C#. The idea is that the channel meeting will be running, and who ever wants to join, can join. We need to automate this, thus doing it as a user each day is not an option.
Looking at the Graph API, I can't find an endpoint that can do this. Does anyone know how to do this in C#?
Yes, you can do it using C#, Graph SDK and using onlinemeetings API call.
You can use it using delegated permissions and make sure you have OnlineMeetings.ReadWrite permission set.
Here's the code sample:
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var onlineMeeting = new OnlineMeeting
{
StartDateTime = DateTimeOffset.Parse("2021-01-12T21:30:34.2444915+00:00"),
EndDateTime = DateTimeOffset.Parse("2021-01-02T22:00:34.2464912+00:00"),
Subject = "Teams meeting"
};
await graphClient.Me.OnlineMeetings
.Request()
.AddAsync(onlineMeeting);
enter code here
Check the SDK documentation for details on how to add the SDK to your project and create an authProvider instance.

C#: How to read Microsoft office emails. Different approaches

I need to read emails using C# (concrete task - count of received/sent emails by range).
Ideally, user enters credentials of his Microsoft Office/Exchange email on webpage and receive this info.
I see the following ways to implement it.
ExchangeService
using nuget package Microsoft.Exchange.WebServices we can get access to email profile, e.g.
ExchangeService _service;
_service = new ExchangeService(ExchangeVersion.Exchange2013_SP1)
{
Credentials = new WebCredentials("myemail#hotmail.com", "mypassword"),
};
_service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
_service.TraceEnabled = true;
_service.TraceFlags = TraceFlags.All;
var items = _service.FindItems(WellKnownFolderName.Inbox, searchFilter: new SearchFilter.IsGreaterThan(TaskSchema.DateTimeCreated, DateTime.Now.AddDays(-10)), new ItemView(int.MaxValue));
sometimes this approach works, but for some cases does not work (for example, if 2-way authentication is enabled)
using IAuthenticationProvider and Active Directory Tenant Id
there is a way to impement own IAuthenticationProvider with implementation AuthenticateRequestAsync like this
public async Task AuthenticateRequestAsync(HttpRequestMessage request)
{
var token = await GetTokenAsync();
request.Headers.Authorization = new AuthenticationHeaderValue(token.TokenType, token.AccessToken);
}
after this we can create GraphServiceClient like this:
GraphServiceClient graphServiceClient =
new GraphServiceClient(_authenticationProvider, _graphHttpProvider);
and can send email, for example:
await graphServiceClient.Users[fromAddress]
.SendMail(message, false)
.Request()
.PostAsync();
I suppose, similar way I can get access to folders also
For this approach, I assume, I need to get tenantId etc (I'm a little confused with it)
How to implement stable solution to read Microsoft Office/Exchange emails ?
I would avoid the first approach EWS is now legacy and in that example your using Basic Authentication which is depreciated and will be disabled in October this year (if it hasn't already been).
For 2 you need to create a Azure Application registration see https://learn.microsoft.com/en-us/graph/use-the-api which has some detailed documentation and walkthroughs on how to do that. There's also https://learn.microsoft.com/en-us/graph/tutorials/aspnet-core which is a pretty good example of building a webapp that takes you through all the steps.

MS Graph SDK: How to add URL segment to filter for specific member type?

I'd like to get group members from Graph. No problem, the API is there. I now want to filter for members that are groups themselves and there even is a sample for this on the docs page:
See the /microsoft.graph.group part of the URL? That's what I want, but via Graph SDK.
Switching the sample to C# to see the corresponding code there is no evidence of this microsoft.graph.group URL part anymore:
Am I blind? How to apply this filter via Graph SDK?
Filtering is not supported by SDK code generator. As an alternative you can add segment to request url manually.
var graphClient = new GraphServiceClient( authProvider );
var requestUrl = graphClient.Groups["{group-id}"]
.TransitiveMembers
.AppendSegmentToRequestUrl("microsoft.graph.group?$count=true");
var group = await new GroupTransitiveMembersCollectionWithReferencesRequest(requestUrl, graphClient, null)
.Header("ConsistencyLevel", "eventual")
.GetAsync();
Graph issue

how to solve "Microsoft.graph.serviceexception code generalexceptionmessage an error occurred sending the request" while fetching calendar events?

I have created an auth provider using user-password auth provider but and trying to retrieve calendar events in bot code which is in c#, having bot framework 4
IPublicClientApplication publicClientApplication =
PublicClientApplicationBuilder
.Create("jhnjchdjvd")
.WithTenantId("sdfdf")
.Build();
var s = new SecureString();
s.AppendChar('<');
s.AppendChar('T');
s.AppendChar('N');
s.AppendChar('>');
s.AppendChar('7');
UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopes);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
Microsoft.Graph.User me = await graphClient.Me.Request()
.WithUsernamePassword("kjkhv#indica.onmicrosoft.com",
s).GetAsync();
var events = await graphClient.Me.Events
.Request()
.Header("Prefer", "outlook.timezone=\"Pacific Standard Time\"")
.Select(e => new
{
e.Subject,
e.Body,
e.BodyPreview,
e.Organizer,
e.Attendees,
e.Start,
e.End,
e.Location
})
.GetAsync();
Above code throws exception which is
Microsoft.graph.serviceexception code generalexceptionmessage an error
occurred sending the request
How can I solve this error?
Make sure you use the latest NuGet Package and give a try. In order to get the latest one try the following:
"Install-Package Microsoft.Identity.Client -Pre".
This command
installs latest MSAL library.
Quickly i tested the sample. I know its not the BOT framework, but its MSAL & calling Graph, so the same logic applies and works on the principles. It worked for me.
Also i tested with BOT Framework and MSAL; here are the steps that i followed. You may want to check the same as well.
The same issue in my case was caused by revoking the Task function by .GetAwaiter().GetResult().
Solution: I replaced the .GetAwaiter().GetResult() with await approach.

Azure AD GraphServiceClient Extensions not working

I have the following query to retrieve a User using the GraphServiceClient with .net core 2.
user = await _graphClient.Users[principalName].Request()
.Expand("Extensions")
.GetAsync();
When I run this I get the following error
Microsoft.Graph.ServiceException: Code: generalException Message:
Unexpected exception returned from the service.
This only happens when I have added a OpenTypeExtension to the user using the following code!
extension = new OpenTypeExtension
{
ExtensionName = AzureADExtensions.UserConstants.ExtensionName,
AdditionalData = new Dictionary<string, object>
{
{"OtherEmail", externalUser.Email},
{"OtherRole" , externalUser.Roles.FirstOrDefault()}
}
};
await _graphClient.Users[user.Id].Extensions.Request()
.AddAsync(extension);
I am starting to get really getting fed up with Azure AD now.
I can't seem to add any meta data to my users. Only doing this because otherEmails does not work with the GraphServiceClient and trying to use any other sensible fields gives me this error:
Tenant does not have a SPO license when updating user
Any help would be appreciated.
So for anyone else that come across this, it seems to be an a bug in the service client.
The code below fails
user = await _graphClient
.Users[userId]
.Request()
.Expand("Extensions")
.GetAsync();
But this code works, just by requesting the extensions in a separate call!
user = await _graphClient
.Users[userId]
.Request()
.GetAsync();
var extensions = await _graphClient.Users[user.Id].Extensions.Request().GetAsync();
user.Extensions = extensions;
Hope that save's someone the time I lost on this!

Categories

Resources