Implementing SOAP in .NET

From SoftLayer Development Network Wiki

Jump to: navigation, search

Our .NET API example takes advantage of Visual Studio's Web Reference technology to read our API's WSDL files and turn them into objects you can use in your projects. Before you fire up your copy of Visual Studio note that this example is written in the Professional Edition of VS 2005. If you are running a different version, particularly one of the express editions, you may have some trouble getting proxies from your WSDLs, though we haven't noticed any problems in Visual Studio 2008 Express Edition. If your version of Visual Studio has trouble adding web references then download Microsoft's wsdl.exe helper tool. If you want to get right to work we've included C# and Visual Basic.NET implementations of this example in a VS 2005 solution for you to download.

The process we're going to show you is a way to grab a server list for an account, prompt for a specific server, then show that server's hourly bandwidth usage for the last 24 hours. The C# and VB.NET projects both produce output similar to this:

0) myhost.example.org
1) anotherhost.example.org
2) yetanotherhost.example.org

Enter the number of the server you would like to see bandwidth data for: 0


Last 24 hours of public traffic for server myhost.example.org:

Date/Time                Inbound (GB)            Outbound(GB) 
====================     ===================     ====================
 3/19/2008 @ 02:00 PM     2.53                    0.23
 3/19/2008 @ 01:00 PM     1.44                    0.13
 3/19/2008 @ 12:00 PM     0.81                    0.07
 3/19/2008 @ 11:00 AM     0.73                    0.08 
 3/19/2008 @ 10:00 AM     1.65                    0.11
 3/19/2008 @ 09:00 AM     1.06                    0.12
 3/19/2008 @ 08:00 AM     1.31                    0.14
 3/19/2008 @ 07:00 AM     1.68                    0.20
 3/19/2008 @ 06:00 AM     2.38                    0.29
 3/19/2008 @ 05:00 AM     2.84                    0.37
 3/19/2008 @ 04:00 AM     3.11                    0.40
 3/19/2008 @ 03:00 AM     3.32                    0.41
 3/19/2008 @ 02:00 AM     3.30                    0.38
 3/19/2008 @ 01:00 AM     3.14                    0.35
 3/19/2008 @ 12:00 AM     3.49                    0.38
 3/18/2008 @ 11:00 PM     4.46                    0.49
 3/18/2008 @ 09:00 PM     6.49                    0.72
 3/18/2008 @ 08:00 PM     7.08                    0.76
 3/18/2008 @ 07:00 PM     7.24                    0.76
 3/18/2008 @ 06:00 PM     7.69                    0.79
 3/18/2008 @ 05:00 PM     6.94                    0.71
 3/18/2008 @ 04:00 PM     7.12                    0.74
 3/18/2008 @ 03:00 PM     7.50                    0.74

Press <ENTER> to exit. 

Contents

Creating Your Project

Web Reference Details
Web Reference Details
C# Console Project
C# Console Project

From the VS main select File -> New -> Project. Start a new CS or VB console application, depending on which flavor of .NET is your cup of tea.

Creating A Web Reference To The SoftLayer API

Adding a Web Reference
Adding a Web Reference
Web Reference Details
Web Reference Details
The Solution Explorer
The Solution Explorer

Once your project initializes, you will need to add a reference to the API service WSDL. You can do that from the Project -> Add Web Reference menu. A neat little dialog will pop up. Use it to point to the SoftLayer API server.

First, we will reference the SoftLayer_Account class at: http://api.service.softlayer.com/soap/v3/SoftLayer_Account?wsdl. The wizard should fill in the “SoftLayer_AccountService” description. For this example, you’ll want to go into the “Web Reference Name” text box and change the label to SLDN_Acct. Now you are ready to hit the “Add Reference” button. Repeat the process for the SoftLayer_Hardware_Server class, http://api.service.softlayer.com/soap/v3/SoftLayer_Hardware_Server?wsdl, naming it SLDN_Serv.

Setting Up Authentication

We are now ready to begin. For those of you who are writing a C# example, you’ll want to bring up the Program.cs file in the editor pane. If you are writing a VB application, the file you’ll edit is the default Module1.vb file.

We start by declaring our services and authenticating with the SOAP server. Note that you will need to replace the user name and api key with your user name and api key.

C#

 
string user_name = "REPLACE WITH YOUR USER NAME";
string api_key = "REPLACE WITH YOUR API KEY";
 
SLDN_Serv.SoftLayer_Hardware_ServerService server = new SLDN_Serv.SoftLayer_Hardware_ServerService();
SLDN_Acct.SoftLayer_AccountService account = new SLDN_Acct.SoftLayer_AccountService();
 
acct_credentials.username = user_name;
acct_credentials.apiKey = api_key;
serv_credentials.username = user_name;
serv_credentials.apiKey = api_key;
 
account.authenticateValue = acct_credentials;
server.authenticateValue = serv_credentials;
 
SLDN_Acct.SoftLayer_Hardware[] hw = null;
 

VB.NET

 
Dim user_name As String = "REPLACE WITH YOUR USER NAME"
Dim api_key As String = "REPLACE WITH YOUR API KEY"
 
Dim server As SLDN_Serv.SoftLayer_Hardware_ServerService = New SLDN_Serv.SoftLayer_Hardware_ServerService()
Dim account As SLDN_Acct.SoftLayer_AccountService = New SLDN_Acct.SoftLayer_AccountService()
 
Dim acct_credentials As SLDN_Acct.authenticate = New SLDN_Acct.authenticate()
acct_credentials.username = user_name
acct_credentials.apiKey = api_key
serv_credentials.username = user_name
serv_credentials.apiKey = api_key
 
account.authenticateValue = acct_credentials
server.authenticateValue = serv_credentials
 
Dim hw() As SLDN_Acct.SoftLayer_Hardware = Nothing
 

Grabbing A Server List

Now that we have our SLDN services instantiated and authenticated, let’s use those objects to do something. We will start by pulling a list of servers for the user using the getHardware method in the SoftLayer_Account service.. Note that for the purpose of keeping this example simple and not having to deal with multiple pages of data, we simply cut the list of servers off at number ten.

C#

 
Try
{
  hw = account.getHardware();
}
catch (Exception e)
{
  Console.WriteLine("Exception encountered [" + e.Message + "]");
  hw = null;
}
 
if (hw == null)
{
  Console.WriteLine("No valid hardware objects found for account / credentials.");
  goto EXIT;
}
 
for (int i = 0; i < hw.Length; i++)
{
  string idx = i.ToString();
  Console.WriteLine(i.ToString() + ") " + hw[i].hostname + "." + hw[i].domain);
  if (i >= 9) break;
}
 

VB.NET

 
Try
  hw = account.getHardware()
Catch e As Exception
  Console.WriteLine("Exception encountered [" + e.Message + "]")
  hw = Nothing
End Try
 
If hw Is Nothing Then
  Console.WriteLine("No valid hardware objects found for account / credentials.")
  GoTo QUIT
End If
 
Dim i As Integer
 
For i = 0 To hw.Length()1
  Dim idx As String = i.ToString()
  Console.WriteLine(i.ToString() + ") " + hw(i).hostname + "." + hw(i).domain)
  If i >= 9 Then Exit For
Next
 

Selecting A Server And Getting Bandwidth Parameters

Now that we have displayed a list of hardware to the users and put the numeric index out to the left of each, let’s prompt the user to select one and do the most basic of validations.

C#

 
Console.Write("\nEnter the number of the server you would like to see bandwidth data for: ");
string choice = Console.ReadLine();
int selection = 0;
 
try
{
  selection = Convert.ToInt32(choice);
  if ((selection < 0) || (selection > hw.Length))
  {
    throw new Exception("Invalid selection!");
  }
}
catch
{
  Console.WriteLine("You have made an invalid selection.");
  goto EXIT;
}
 

VB.NET

 
Console.Write(vbCrLf + "Enter the number of the server you would like to see bandwidth data for: ")
Dim choice As String = Console.ReadLine()
Dim selection As Integer = 0
 
Try
  selection = Convert.ToInt32(choice)
  If selection < 0 Or selection > hw.Length Then
    Throw New Exception("Invalid selection!")
  End If
Catch e As Exception
  Console.WriteLine("You have made an invalid selection.")
  GoTo QUIT
End Try
 

Now that our user has selected a server, we want to display the bandwidth data for the last 24 hours for that box. We build our parameter by getting the current time and date, then subtracting 24 hours from it.

C#

 
TimeSpan one_day = new TimeSpan(24, 0, 0);
DateTime last_24_hours = DateTime.Now;
last_24_hours = last_24_hours.Subtract(one_day);
 

VB.NET

 
Dim one_day As TimeSpan = New TimeSpan(24, 0, 0)
Dim last_24_hours As DateTime = DateTime.Now
last_24_hours = last_24_hours.Subtract(one_day)
 

Now we will want to point our server object at the specific server the user selected from our list. The key is that you must create an instance of SoftLayer_Hardware_ServerInitParameters, set the id of that object to the id (index) of our selected server, then assign that SLDN_Serv.SoftLayer_Hardware_ServerInitParameters object to the SoftLayer_Hardware_ServerInitParametersValue for our service. If that sounds confusing read it again as it’s essential to understanding how the architecture works. Got it? Super. Now for the elegance. The beauty of this design is that you can reassign the hardware id of the server before each method call you make to the service, meaning you don’t have to instantiate all new objects to change the hardware device you are talking to. Brilliant!

C#

 
SLDN_Serv.SoftLayer_Hardware_ServerInitParameters box = new SLDN_Serv.SoftLayer_Hardware_ServerInitParameters();
box.id = (int)hw[selection].id;
server.SoftLayer_Hardware_ServerInitParametersValue = box;
 

VB.NET

 
Dim box As SLDN_Serv.SoftLayer_Hardware_ServerInitParameters = New SLDN_Serv.SoftLayer_Hardware_ServerInitParameters()
box.id = Convert.ToInt32(hw(selection).id)
server.SoftLayer_Hardware_ServerInitParametersValue = box
 

Retrieving Bandwidth Records

Now we are ready to ask the API for the bandwidth data for our specific server. A couple of notes here. First, a large number of API calls return containers which you have to instantiate. In this case, the return type is a SoftLayer_Container_Network_Bandwidth_Version1_Usage object. Secondly, in our experience some of the bandwidth-related calls are pretty database intensive and take some time to execute. This particular method, getBandwidthByHour seemed to take longer than most. Be patient, it works.

Again in the spirit of keeping this example simple, we are returning bandwidth utilization on the “public” server interface. However you could just as easily return the data for the private interface, or both for that matter.

C#

 
SLDN_Serv.SoftLayer_Container_Network_Bandwidth_Version1_Usage[] usage = null;
 
try
{
  usage = server.getBandwidthByHour("public", last_24_hours);
}
catch (Exception e)
{
  Console.WriteLine("Exception encountered: [" + e.Message + "]");
  goto EXIT;
}
 

VB.NET

 
Dim usage() As SLDN_Serv.SoftLayer_Container_Network_Bandwidth_Version1_Usage = Nothing
 
Try
  usage = server.getBandwidthByHour("public", last_24_hours)
Catch e As Exception
  Console.WriteLine("Exception encountered: [" + e.Message + "]")
  GoTo QUIT
End Try
 

Outputting the Result

Now the hard work is done--if you can call that hard work. We just need to do a little bit of formatting on our results and then display them to the user. This loop uses the recordedDate, incomingAmount, and outgoingAmount properties of our bandwidth usage container.

C#

 
Console.WriteLine("\n\nLast 24 hours of public traffic for server " + hw[selection].hostname + "." + hw[selection].domain + ":");
Console.WriteLine("\nDate/Time \t\t Inbound (GB) \t\t Outbound(GB)");
Console.WriteLine("==================== \t =================== \t ====================");
 
if (usage != null)
{
  for (int i = 0; i < usage.Length; i++)
  {
    string f_time = usage[i].recordedDate.ToShortTimeString();
 
    if (f_time.Length % 2 != 0) f_time = "0" + f_time;
 
    string f_date = usage[i].recordedDate.Date.ToShortDateString() + " @ " + f_time;
    decimal f_in = Decimal.Round((decimal)usage[i].incomingAmount, 2);
    decimal f_out = Decimal.Round((decimal)usage[i].outgoingAmount, 2);
 
    Console.WriteLine(" " + f_date + "\t  " + f_in + "\t\t\t  " + f_out);
  }
}
 

VB.NET

 
Console.WriteLine(vbCrLf + vbCrLf + "Last 24 hours of public traffic for server " + hw(selection).hostname + hw(selection).domain + ":")
Console.WriteLine(vbCrLf + "Date/Time " + vbTab + vbTab + " Inbound (GB) " + vbTab + vbTab + " Outbound(GB)")
Console.WriteLine("==================== " + vbTab + " =================== " + vbTab + " ====================")
 
If (Not usage Is Nothing) Then
  For i = 0 To usage.Length1
    Dim f_time As String = usage(i).recordedDate.ToShortTimeString()
 
    If f_time.Length Mod 2 <> 0 Then f_time = "0" + f_time
 
    Dim f_date As String = usage(i).recordedDate.Date.ToShortDateString() + " @ " + f_time
    Dim f_in As Decimal = Decimal.Round(Convert.ToDecimal(usage(i).incomingAmount), 2)
    Dim f_out As Decimal = Decimal.Round(Convert.ToDecimal(usage(i).outgoingAmount), 2)
 
    Console.Write(" " + f_date + vbTab + "  ")
    Console.Write(f_in)
    Console.Write(vbTab + vbTab + vbTab + "  ")
    Console.WriteLine(f_out)
  Next
End If
 

All that remains now is to make a graceful exit.

C#

 
EXIT:
  Console.Write("\nPress <ENTER> to exit.");
  Console.ReadLine();
 

VB.NET

 
QUIT:
  Console.Write(vbCrLf + "Press <ENTER> to exit.")
  Console.ReadLine()
 

The Complete Source

Now that we've seen how this works, here's the full script. These are provided as part of our completed project files. If you want to see the example in action then check out our project files. Otherwise if you want to use the code below then you need to add Web References to your project as described above.

C#

 
using System;
using System.Collections.Generic;
using System.Text;
/*
    +-------------------------------------------------------------------------------+
    |                                                                               |
    |   File:               BW_USAGE                                                |
    |                       =================================================       |
    |   Dev Platform:       WinXP SP2 2.3GHZ 2GB RAM                                |
    |   Dev Environment:    Visual Studio.NET 2005 Professional Edition (C#)        |
    |   Target:             Windows XP (x86)                                        |
    |   Purpose:            Demonstrate SoftLayer API calls from .NET               |
    |   Limitations:        Cuts the list to 10 servers no matter how many          |
    |                        the user might have access to.  Provided in source     | 
    |                        so no installer created.                               |
    |   URL:                The latest version of this script can be found at       |
    |                        http://sldn.softlayer.com/wiki/index.php/Implementing_SOAP_in_.NET |
    |   License:            This code is licensed under the Creative Commons 3.0    | 
    |                        Attribute United States License.                       |
    |                        http://creativecommons.org/licenses/by/3.0/us/         |
    |                       =================================================       |
    |   Dev Summary->                                                               |
    |   Revision:   Who:    When:       What:                                       |
    |   =========== ======= =========== =========================================   |
    |   01.00.00    WJF     03/06/08    Original Creation                           |
    +-------------------------------------------------------------------------------+
 
*/
namespace BW_USAGE_CS
{
    class Program
    {
        //READ ME
        //////////////////////////////////////////////////////////////////////////////////
        // In order to use this code you will need to create a new "console" project
        // from the VS start up wizard.  After the project initializes, you will be
        // required to add 2 web references.  You can do this from the project
        // explorer by right clicking "references" and choosing "add web reference"
        // from the resulting context menu.  There you will need to enter the URLs.
        // The first is 
        // http://api.service.softlayer.com/soap/v3/SoftLayer_Account?wsdl
        // while the second is 
        // http://api.service.softlayer.com/soap/v3/SoftLayer_Hardware_Server?wsdl
        // Please name them SLDN_Acct and SLDN_Serv respectively.  Once the web
        // references have been added and VS creates the appropriate wrappers you
        // simply need to replace the "user_name" and "api_key" with your SLDN username
        // and api key.  Please note that this procedure was documented using the
        // professional edition of MS Visual Studio 2005.  It is possible other versions,
        // particularly the free "express" editions, may require something more to
        // gain access to the SLAPI services via SOAP.
        //////////////////////////////////////////////////////////////////////////////////
        static void Main(string[] args)
        {
            //replace with your username and api key
            string user_name = "REPLACE WITH YOUR USER NAME";
            string api_key = "REPLACE WITH YOUR API KEY";
 
            //declare the services
            SLDN_Serv.SoftLayer_Hardware_ServerService server = new SLDN_Serv.SoftLayer_Hardware_ServerService();
            SLDN_Acct.SoftLayer_AccountService account = new SLDN_Acct.SoftLayer_AccountService();
 
            //create an authentification object for each
            SLDN_Acct.authenticate acct_credentials = new SLDN_Acct.authenticate();
            SLDN_Serv.authenticate serv_credentials = new SLDN_Serv.authenticate();
 
            //assign credentials
            acct_credentials.username = user_name;
            acct_credentials.apiKey = api_key;
            serv_credentials.username = user_name;
            serv_credentials.apiKey = api_key;
 
            account.authenticateValue = acct_credentials;
            server.authenticateValue = serv_credentials;
            SLDN_Acct.SoftLayer_Hardware[] hw = null;
 
            //attempt to pull a hardware list for this user
            try
            {
                hw = account.getHardware();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception encountered [" + e.Message + "]");
                hw = null;
            }
 
            //no hardware found?
            if (hw == null)
            {
                Console.WriteLine("No valid hardware objects found for account / credentials.");
                goto EXIT;
            }
 
            //display the first ten servers found for this user account
            for (int i = 0; i < hw.Length; i++)
            {
                string idx = i.ToString();
                Console.WriteLine(i.ToString() + ") " + hw[i].hostname + "." + hw[i].domain);
                if (i >= 9) break;
            }
 
            //ask for user to select a server
            Console.Write("\nEnter the number of the server you would like to see bandwidth data for: ");
            string choice = Console.ReadLine();
            int selection = 0;
 
            //validate selection
            try
            {
                selection = Convert.ToInt32(choice);
                if ((selection < 0) || (selection > hw.Length))
                {
                    throw new Exception("Invalid selection!");
                }
            }
            catch
            {
                Console.WriteLine("You have made an invalid selection.");
                goto EXIT;
            }
 
            //calculate a start time of 24 hours from now
            TimeSpan one_day = new TimeSpan(24, 0, 0);
            DateTime last_24_hours = DateTime.Now;
            last_24_hours = last_24_hours.Subtract(one_day);
 
            //create the server access by initializing the hardware id for this call to the one the user chose
            //note theoretically you can change the server before each call just by reinitializing the ServerInitParameters
            SLDN_Serv.SoftLayer_Hardware_ServerInitParameters box = new SLDN_Serv.SoftLayer_Hardware_ServerInitParameters();
            box.id = (int)hw[selection].id;
            server.SoftLayer_Hardware_ServerInitParametersValue = box;
 
 
            //now try and retrieve the last 24 hours of bandwidth data for this server.
            //note sometimes this call can be pokey returning depending on the current load of the bandwidth monitor.
            SLDN_Serv.SoftLayer_Container_Network_Bandwidth_Version1_Usage[] usage = null;
 
            try
            {
                usage = server.getBandwidthByHour("public", last_24_hours);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception encountered: [" + e.Message + "]");
                goto EXIT;
            }
 
            //display our results to the user
            Console.WriteLine("\n\nLast 24 hours of public traffic for server " + hw[selection].hostname + hw[selection].domain + ":");
            Console.WriteLine("\nDate/Time \t\t Inbound (GB) \t\t Outbound(GB)");
            Console.WriteLine("==================== \t =================== \t ====================");
 
            if (usage != null)
            {
                for (int i = 0; i < usage.Length; i++)
                {
                    string f_time = usage[i].recordedDate.ToShortTimeString();
                    if (f_time.Length % 2 != 0) f_time = "0" + f_time;
                    string f_date = usage[i].recordedDate.Date.ToShortDateString() + " @ " + f_time;
                    decimal f_in = Decimal.Round((decimal)usage[i].incomingAmount, 2);
                    decimal f_out = Decimal.Round((decimal)usage[i].outgoingAmount, 2);
                    Console.WriteLine(" " + f_date + "\t  " + f_in + "\t\t\t  " + f_out);
                }
            }
 
            //Yahoo kid you're all clear!
        EXIT:
            Console.Write("\nPress <ENTER> to exit.");
            Console.ReadLine();
        }
 
    }
}
 

VB.NET

 
Module Module1
 
    '+-------------------------------------------------------------------------------+
    '|                                                                               |
    '|  File:               BW_USAGE                                                 |
    '|                      =================================================        |
    '|  Dev Platform:       WinXP SP2 2.3GHZ 2GB RAM                                 |
    '|  Dev Environment:    Visual Studio.NET 2005 Professional Edition (VB.NET)     |
    '|  Target:             Windows XP (x86)                                         |
    '|  Purpose:            Demonstrate SoftLayer API calls from .NET                |
    '|  Limitations:        Cuts the list to 10 servers no matter how many           |
    '|                       the user might have access to.  Provided in source      | 
    '|                       so no installer created.                                |
    '|   URL:               The latest version of this script can be found at        |
    '|                       http://sldn.softlayer.com/wiki/index.php/Implementing_SOAP_in_.NET |
    '|   License:           This code is licensed under the Creative Commons 3.0     | 
    '|                       Attribute United States License.                        |
    '|                       http://creativecommons.org/licenses/by/3.0/us/          |
    '|                      =================================================        |
    '|  Dev Summary->                                                                |
    '|   Revision:   Who:    When:          What:                                    |
    '|   =========== ======= ===========    =========================================|
    '|   01.00.00    WJF     03/06/08       Original Creation                        |
    '+-------------------------------------------------------------------------------+
 
    Sub Main()
 
        'READ ME
        '///////////////////////////////////////////////////////////////////////////////
        '/ In order to use this code you will need to create a new "console" project
        '/ from the VS start up wizard.  After the project initializes, you will be
        '/ required to add 2 web references.  You can do this from the project
        '/ explorer by right clicking "references" and choosing "add web reference"
        '/ from the resulting context menu.  There you will need to enter the URLs.
        '/ The first is 
        '/ http://api.service.softlayer.com/soap/v3/SoftLayer_Account?wsdl
        '/ while the second is 
        '/ http://api.service.softlayer.com/soap/v3/SoftLayer_Hardware_Server?wsdl
        '/ Please name them SLDN_Acct and SLDN_Serv respectively.  Once the web
        '/ references have been added and VS creates the appropriate wrappers you
        '/ simply need to replace the "user_name" and "api_key" with your SLDN username
        '/ and api key.  Please note that this procedure was documented using the
        '/ professional edition of MS Visual Studio 2005.  It is possible other versions,
        '/ particularly the free "express" editions, may require something more to
        '/ gain access to the SLAPI services via SOAP.
        '////////////////////////////////////////////////////////////////////////////////
 
        'replace with your username and api key
        Dim user_name As String = "REPLACE WITH YOUR USER NAME"
        Dim api_key As String = "REPLACE WITH YOUR API KEY"
 
        'declare the services
        Dim server As SLDN_Serv.SoftLayer_Hardware_ServerService = New SLDN_Serv.SoftLayer_Hardware_ServerService()
        Dim account As SLDN_Acct.SoftLayer_AccountService = New SLDN_Acct.SoftLayer_AccountService()
 
        'create an authentification object for each
        Dim acct_credentials As SLDN_Acct.authenticate = New SLDN_Acct.authenticate()
        Dim serv_credentials As SLDN_Serv.authenticate = New SLDN_Serv.authenticate()
 
        'assign credentials
        acct_credentials.username = user_name
        acct_credentials.apiKey = api_key
        serv_credentials.username = user_name
        serv_credentials.apiKey = api_key
 
        account.authenticateValue = acct_credentials
        server.authenticateValue = serv_credentials
        Dim hw() As SLDN_Acct.SoftLayer_Hardware = Nothing
 
        'attempt to pull a hardware list for this user
        Try
            hw = account.getHardware()
        Catch e As Exception
            Console.WriteLine("Exception encountered [" + e.Message + "]")
            hw = Nothing
        End Try
 
        'no hardware found?
        If hw Is Nothing Then
            Console.WriteLine("No valid hardware objects found for account / credentials.")
            GoTo QUIT
        End If
 
        'display the first ten servers found for this user account
        Dim i As Integer
        For i = 0 To hw.Length() - 1
            Dim idx As String = i.ToString()
            Console.WriteLine(i.ToString() + ") " + hw(i).hostname + "." + hw(i).domain)
            If i >= 9 Then Exit For
        Next
 
        'ask for user to select a server
        Console.Write(vbCrLf + "Enter the number of the server you would like to see bandwidth data for: ")
        Dim choice As String = Console.ReadLine()
        Dim selection As Integer = 0
 
        'validate selection
        Try
            selection = Convert.ToInt32(choice)
            If selection < 0 Or selection > hw.Length Then
                Throw New Exception("Invalid selection!")
            End If
        Catch e As Exception
            Console.WriteLine("You have made an invalid selection.")
            GoTo QUIT
        End Try
 
        'calculate a start time of 24 hours from now
        Dim one_day As TimeSpan = New TimeSpan(24, 0, 0)
        Dim last_24_hours As DateTime = DateTime.Now
        last_24_hours = last_24_hours.Subtract(one_day)
 
        'create the server access by initializing the hardware id for this call to the one the user chose
        'Note theoretically you can change the server before each call just by reinitializing the ServerInitParameters
        Dim box As SLDN_Serv.SoftLayer_Hardware_ServerInitParameters = New SLDN_Serv.SoftLayer_Hardware_ServerInitParameters()
        box.id = Convert.ToInt32(hw(selection).id)
        server.SoftLayer_Hardware_ServerInitParametersValue = box
 
        Dim usage() As SLDN_Serv.SoftLayer_Container_Network_Bandwidth_Version1_Usage = Nothing
 
        'now try and retrieve the last 24 hours of bandwidth data for this server.
        'note sometimes this call can be pokey returning depending on the current load of the bandwidth monitor.
        Try
            usage = server.getBandwidthByHour("public", last_24_hours)
        Catch e As Exception
            Console.WriteLine("Exception encountered: [" + e.Message + "]")
            GoTo QUIT
        End Try
 
        'display our results to the user
        Console.WriteLine(vbCrLf + vbCrLf + "Last 24 hours of public traffic for server " + hw(selection).hostname + "." + hw(selection).domain + ":")
        Console.WriteLine(vbCrLf + "Date/Time " + vbTab + vbTab + " Inbound (GB) " + vbTab + vbTab + " Outbound(GB)")
        Console.WriteLine("==================== " + vbTab + " =================== " + vbTab + " ====================")
 
        If (Not usage Is Nothing) Then
            For i = 0 To usage.Length - 1
                Dim f_time As String = usage(i).recordedDate.ToShortTimeString()
                If f_time.Length Mod 2 <> 0 Then f_time = "0" + f_time
                Dim f_date As String = usage(i).recordedDate.Date.ToShortDateString() + " @ " + f_time
                Dim f_in As Decimal = Decimal.Round(Convert.ToDecimal(usage(i).incomingAmount), 2)
                Dim f_out As Decimal = Decimal.Round(Convert.ToDecimal(usage(i).outgoingAmount), 2)
                Console.Write(" " + f_date + vbTab + "  ")
                Console.Write(f_in)
                Console.Write(vbTab + vbTab + vbTab + "  ")
                Console.WriteLine(f_out)
            Next
        End If
 
        'Yahoo kid you're all clear!
QUIT:
        Console.Write(vbCrLf + "Press <ENTER> to exit.")
        Console.ReadLine()
 
    End Sub
 
End Module
 

See Also

Associated Methods

External Links

Personal tools