«^»
8.4. Getting a client to present a username and a password

We also have to alter the client so that it arranges for a username and a password to be present in the header of the SOAP message that it generates.

Currently, the proxy class (Service1) is derived from the class:

System.Web.Services.Protocols.SoapHttpClientProtocol
Service1 needs to be altered so that it is derived from the class:
Microsoft.Web.Services.WebServicesClientProtocol
The latter class is itself derived from:
System.Web.Services.Protocols.SoapHttpClientProtocol
and so Service1 can be used as before but it now has access to the other facilities that are in its new base class: these facilities are there to support WS-Security.

We can then add the username and the password to the header of the SOAP message by applying the appropriate method to the Service1 object:

0347: using Console        = System.Console;
0348: using Exception      = System.Exception;
0349: using PasswordOption = Microsoft.Web.Services.Security.PasswordOption;
0350: using Service1       = ConsoleUsername.Proxy.Service1;
0351: using UsernameToken  = Microsoft.Web.Services.Security.UsernameToken;
0352: namespace ConsoleUsername
0353: {
0354:     public class Class1
0355:     {
0356:         public static void Main()
0357:         {
0358:             Console.Write("Type in a Centigrade value: ");
0359:             string tCentigradeString = Console.ReadLine();
0360:             double tCentigrade = double.Parse(tCentigradeString);
0361:             Console.WriteLine("Centigrade value is: " + tCentigrade);
0362:             Console.Write("Type in a Username: ");
0363:             string tUsername = Console.ReadLine();
0364:             Console.WriteLine("Username is: " + tUsername);
0365:             Console.Write("Type in a Password: ");
0366:             string tPassword = Console.ReadLine();
0367:             Console.WriteLine("Password is: " + tPassword);
0368:             UsernameToken tUsernameToken = 
0369:                 new UsernameToken(tUsername, tPassword, PasswordOption.SendHashed);
0370:             Service1 tService1 = new Service1();
0371:             tService1.RequestSoapContext.Security.Tokens.Add(tUsernameToken);
0372:             try
0373:             {
0374:                 double tFahrenheit = tService1.ToFahrenheit(tCentigrade);
0375:                 Console.WriteLine("Fahrenheit value is: " + tFahrenheit);
0376:             }
0377:             catch(Exception pException)
0378:             {
0379:                 Console.WriteLine(pException.Message);
0380:             }
0381:         }
0382:     }
0383: }

Once again, the above code uses types from a subnamespace of the Microsoft.Web.Services namespace. As before, in order to get Visual Studio.NET to find these types, you will need to go to the Add Reference option of its Project menu, and then use this to add a reference to Microsoft.Web.Services.dll.