In this blog post, I will show you how to use the GraphClient in a VB.Net application. You will need to create an app registration for this project. I used the exact same app registration that I used in my previous VB.Net blog post here.

SDK Reference: https://docs.microsoft.com/en-us/graph/sdks/sdks-overview?view=graph-rest-1.0

I am using Visual Studio 2019 in this example. To begin, please start a VB.Net Console application and then install the following nuget packages:

Install nuget packages:

This will also install

  • Microsoft.Graph.Core
  • Microsoft.Json
  • System.Buffers
  • System.Diagnostics.DiagnosticSource
  • System.Numerics.Vectors
  • System.Runtime.CompilerServices.Unsafe
  • System.ValueTuple

I will be creating a custom Authentication Provider for this project. The reference for this:

Creating an Authentication Provider Reference: https://docs.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS

I am creating a custom authentication provider class called “InteractiveAuthentionProvider.vb”

There is a preview component you can install that has these classes built in so that you don’t have to implement your own class:  https://github.com/microsoftgraph/msgraph-sdk-dotnet-auth  That is currently in preview mode so I will blog about this later.

I have the custom InteractiveAuthenticationProvider class that will be passed to GraphClient.  In Module1, you will need to enter your client ID and tenant ID.  Refer to my previous blog post here about setting up the app registration.

Imports System.Net.Http
Imports Microsoft.Graph
Imports Microsoft.Identity.Client

''' <summary>
''' This is a custom class to implement the IAuthenticationProvider class.  You can implement the new preview Microsoft.Graph.Auth which has 
''' built in classes for the authentication providers:  https://github.com/microsoftgraph/msgraph-sdk-dotnet-auth
''' </summary>
Public Class InteractiveAuthenticationProvider
    Implements IAuthenticationProvider

    Private Property Pca As IPublicClientApplication
    Private Property Scopes As List(Of String)

    Private Sub New()
        'Intentionally left blank to prevent empty constructor
    End Sub

    ''' <summary>
    ''' The constructor for this custom implementation of the IAuthenticationProvider
    ''' </summary>
    ''' <param name="pca">The public client application -- in this example, I have pre-set this up prior to creating the auth provider</param>
    ''' <param name="scopes">The scopes for the request</param>
    Public Sub New(pca As IPublicClientApplication, scopes As List(Of String))
        Me.Pca = pca
        Me.Scopes = scopes
    End Sub

    ''' <summary>
    ''' This is the required implmentation of the AuthenticateRequestAsync Method for the IAuthenticationProvider interface
    ''' </summary>
    ''' <param name="request">The current graph request being made</param>
    ''' <returns></returns>
    Public Async Function AuthenticateRequestAsync(request As HttpRequestMessage) As Task Implements IAuthenticationProvider.AuthenticateRequestAsync
        Dim accounts As IEnumerable(Of IAccount)
        Dim result As AuthenticationResult = Nothing

        accounts = Await Pca.GetAccountsAsync()
        Dim interactionRequired As Boolean = False

        Try
            result = Await Pca.AcquireTokenSilent(Scopes, accounts.FirstOrDefault).ExecuteAsync()
        Catch ex1 As MsalUiRequiredException
            interactionRequired = True
        Catch ex2 As Exception
            Console.WriteLine($"Authentication error: {ex2.Message}")
        End Try

        If interactionRequired Then
            Try
                result = Await Pca.AcquireTokenInteractive(Scopes).ExecuteAsync()
            Catch ex As Exception
                Console.WriteLine($"Authentication error: {ex.Message}")
            End Try
        End If

        Console.WriteLine($"Access Token: {result.AccessToken}{Environment.NewLine}")
        Console.WriteLine($"Graph Request: {request.RequestUri}")
        'You must set the access token for the authorization of the current request
        request.Headers.Authorization = New Headers.AuthenticationHeaderValue("Bearer", result.AccessToken)
    End Function
End Class

 

Imports Microsoft.Graph
Imports Microsoft.Identity.Client
Imports Newtonsoft.Json

Module Module1

    Private Const client_id As String = "{client id -- also known as application id}" '<-- enter the client_id guid here
    Private Const tenant_id As String = "{tenant id or name}" '<-- enter either your tenant id here
    Private authority As String = $"https://login.microsoftonline.com/{tenant_id}"

    Private _scopes As New List(Of String)
    Private ReadOnly Property scopes As List(Of String)
        Get
            If _scopes.Count = 0 Then
                _scopes.Add("User.read") '<-- add each scope you want to send as a seperate .add
            End If
            Return _scopes
        End Get
    End Property

    ''' <summary>
    ''' underlaying variable for the readonly property PCA which returns an instance of the PublicClientApplication
    ''' </summary>
    Private _pca As IPublicClientApplication = Nothing
    Private ReadOnly Property PCA As IPublicClientApplication
        Get
            If _pca Is Nothing Then
                _pca = PublicClientApplicationBuilder.Create(client_id).WithAdfsAuthority(authority).Build()
            End If
            Return _pca
        End Get
    End Property

    ''' <summary>
    ''' The underlaying variable for the Authentication Provider readonly property
    ''' </summary>
    Private _authProvider As InteractiveAuthenticationProvider = Nothing
    Private ReadOnly Property AuthProvider As InteractiveAuthenticationProvider
        Get
            If _authProvider Is Nothing Then
                _authProvider = New InteractiveAuthenticationProvider(PCA, scopes)
            End If
            Return _authProvider
        End Get
    End Property

    ''' <summary>
    ''' The underlaying variable for the graphClient readonly property
    ''' </summary>
    Private _graphClient As GraphServiceClient = Nothing
    Private ReadOnly Property GraphClient As GraphServiceClient
        Get
            If _graphClient Is Nothing Then
                _graphClient = New GraphServiceClient(AuthProvider)
            End If
            Return _graphClient
        End Get
    End Property


    Sub Main()

        Get_Me()


        Console.ReadKey()

    End Sub

    Private Async Sub Get_Me()
        Dim user As User

        'Using the Select to get the employeeId as the v1 endpoint does not automatically return that
        user = Await GraphClient.Me().Request().Select("displayName,employeeid").GetAsync()
        Console.WriteLine($"User = {user.DisplayName}, employeeid = {user.EmployeeId}")


    End Sub

End Module

In summary, this example of using the GraphClient library in a VB.Net application demonstrates that, although different than the c# examples we have in our docs, there really isn’t much to using the different language.

0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments