14.2. Using My in Code

Using the My objects in your application code is straightforward in most Windows and web-based projects. Because the underlying real namespace is implicitly referenced and any necessary objects are created for you automatically, all you need to do is reference the object property or method you wish to use. As an example, consider the following code snippet that evaluates the user identity and role attached to the thread running an application:

Private Sub OK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
   Handles OK.Click
    If My.User.IsAuthenticated Then
        If My.User.IsInRole("Administrators") Then
            My.Application.Log.WriteEntry("User " & My.User.Name & _
                " logged in as Administrator", TraceEventType.Information)
        Else
            My.Application.Log.WriteEntry("User " & My.User.Name & _
                " does not have correct privileges.", TraceEventType.Error)
        End If
    End If
    ...
End Sub

The code is fairly straightforward, with the various My object properties and methods defined with readable terms such as IsAuthenticated and WriteEntry. However, before the introduction of My to the developer's toolbox, it was no trivial task to write the code to attach to the current principal, extract the authentication state, determine what roles it belongs to, and then write to an application log.

Every My object provides vital shortcuts to solve scenarios commonly faced by both Windows and web developers, as this example shows. Microsoft did a great job in creating this namespace ...

Get Professional Visual Studio® 2008 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.