< C# Authentication Program Example | Main | XML Web Services and the Network >


Chapter 10 Part 18:

HTTP with .NET



What do we have in this chapter 10 Part 18?

  1. VB .NET Authentication Program Example

  2. Application Models

  3. Code Access Security



VB .NET Authentication Program Example


Create a new class library project and you might want to use AuthenticateVB as the solution and project names.


VB .NET Authentication Program Example - creating a new class library project in VS 2008 IDE


Rename the source file to AuthenticateClassSample to reflect the application that will be developed.


VB .NET Authentication Program Example - renaming the source file will automatically rename the class


Add the following codes.


Imports System

Imports System.Net

Imports System.Text

Imports System.IO

Imports System.Collections


Public Class AuthenticateClassSample

    ' Displays simple usage information for running the sample.       

    Shared Sub usage()

        Console.WriteLine("usage: Executable_file_name [-r URI] [-u user-name] [-p password] [-d domain]")

        Console.WriteLine("Available options:")

        Console.WriteLine("     -r  URI         URI resource to retrieve")

        Console.WriteLine("     -u  user-name   Username to use for authentication")

        Console.WriteLine("     -p  password    Password to use for authentication")

        Console.WriteLine("     -d  domain      Domain to use for authentication")

        Console.WriteLine("     -m              Displays authentication modules")


    End Sub


    ' Retrieves the specified URI with the given credential information. The retrieved resource

    ' is simply printed to the Console.

    Shared Sub RetrieveUri(ByVal uriName As String, ByVal creds As NetworkCredential)

        Dim httpRequest As HttpWebRequest = Nothing

        Dim httpResponse As HttpWebResponse = Nothing



            httpRequest = CType(WebRequest.Create(uriName), HttpWebRequest)


            Console.WriteLine("Creating web request...")

            httpRequest.Credentials = creds

            httpResponse = CType(httpRequest.GetResponse(), HttpWebResponse)


            Dim httpReader As StreamReader = New StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8)

            Dim httpContent As String = httpReader.ReadToEnd()




        Catch wex As WebException

            Console.WriteLine("Exception occurred: {0}", wex.Message)


            httpResponse = CType(wex.Response, HttpWebResponse)


            If (Not IsNothing(httpResponse)) Then


            End If

        End Try

    End Sub


    ' Enumerates and prints the available authentication modules.

    Shared Sub DisplayAuthenticationModules()

        Dim registeredModules As IEnumerator = AuthenticationManager.RegisteredModules

        Console.WriteLine("Authentication Modules:")

        While (registeredModules.MoveNext())

            Dim currentAuthenticationModule As IAuthenticationModule = CType(registeredModules.Current, IAuthenticationModule)


            Console.WriteLine("   Module : {0}", registeredModules.Current)

            Console.WriteLine("    Supports Pre-Authentication : {0}", currentAuthenticationModule.CanPreAuthenticate)

        End While

    End Sub


    ' This routine parses the command line, creates the user credential object if

    ' credentials are supplied and issues the request.

    Shared Sub Main()

        Dim userCredentials As NetworkCredential = Nothing

        Dim uriResource As String = "https://www.cert.org"

        Dim userName As String = "anonymous"

        Dim passWord As String = "test@yahoo.com"

        Dim domain As String = Nothing


        ' Parse the command line

        Dim args As String() = Environment.GetCommandLineArgs()

        Dim i As Integer




        For i = 1 To args.GetUpperBound(0)


                Dim CurArg() As Char = args(i).ToCharArray(0, args(i).Length)

                If (CurArg(0) = "-") Or (CurArg(0) = "/") Then

                    Select Case Char.ToLower(CurArg(1), System.Globalization.CultureInfo.CurrentCulture)

                        Case "d"

                            ' Domain to use for authentication

                            i = i + 1

                            domain = args(i)

                        Case "m"

                            ' Display registered authentication modules


                        Case "p"

                            ' Password to use for authentication

                            i = i + 1

                            passWord = args(i)

                        Case "r"

                            ' URI resource to download (get)

                            i = i + 1

                            uriResource = args(i)

                        Case "u"

                            ' Username to use for authentication

                            i = i + 1

                            userName = args(i)

                        Case "x"

                            ' Web proxy to use for all requests

                            i = i + 1

                            WebRequest.DefaultWebProxy = New WebProxy(args(i))

                        Case Else


                            Exit Sub

                    End Select

                End If

            Catch e As Exception


                Exit Sub

            End Try


        ' Make the request

        Console.WriteLine("Make the request...")


            If ((Not userName Is Nothing) Or (Not passWord Is Nothing) Or (Not domain Is Nothing)) Then

                userCredentials = New NetworkCredential(userName, passWord, domain)

            End If

            RetrieveUri(uriResource, userCredentials)

        Catch ex As Exception

            Console.WriteLine("Exception occurred: {0}", ex.Message)


        End Try

    End Sub

End Class




To test this project we need to change the DLL to application (EXE) type project. Select the project folder > Right click mouse > Select Properties context menu. Change the Application type: to Console Application and the Startup object: to Sub Main.


VB .NET Authentication Program Example - invoking the project's property page


VB .NET Authentication Program Example - Changing the Application type: to Console Application and the Startup object: to Main() subroutine


Build the project.


VB .NET Authentication Program Example - building the project


Run the project.


VB .NET Authentication Program Example - running the project  


The following are the sample outputs. You should try running this program against the HTTPS (web) server with username and password.


VB .NET Authentication Program Example - a sample output without argument values



VB .NET Authentication Program Example - a sample output with argument values


Application Models


The .NET Framework Web classes can be accessed from a variety of application types, including console applications, ASP.NET, XML-based Web Services, Windows Forms, and Windows Services. However, it is important to realize that these application models can run under different environments. For example, a Windows Service or ASP.Net application can run under a different user account or impersonate different users, meaning it might not have the ability to change proxy settings or access to certain resources such as certificates.

The threading models also can vary from one application to another. For example, the ASP.NET environment uses a thread pool to satisfy incoming HTTP requests. This thread pool is also used by the HttpWebRequest class. This means that, if you are building a middle-tier application, you should be aware that both the Web server (ASP.NET) and any back-end Web requests issued will share the same limited set of threads and you should adjust the limits accordingly. This is a significant contrast to using HttpWebRequest from within a console-based application where all work is started from a “main” execution thread.


Code Access Security


As seen with other .NET network classes, use of the Web classes is restricted depending on where the executable is running from. Table 10-6 lists resources the Web classes can access from the various application zones. For example, an application accessed from an intranet share can only connect back to the same machine on which it is running (the localhost). Notice that version 1.1 of the .NET Framework allows applications run from the Internet zone to access the localhost, whereas this was not allowed in version 1.


Table 10-6: Code Access Permissions for Web Classes


.NET Framework Version



Local Machine













< C# Authentication Program Example | Main | XML Web Services and the Network >