nLL

Mobile web, .Net, Android, gadgets and some random stuff

ThePlanet.com Orbit API C# Wrapper

Here is a small web application written in C# on .net 3.5. It gets given dedicated server's bandwidth details from https://api.theplanet.com in order to track your server's bandwidth usage. Orbit API supports server reboots too but  I didn't add that feature. If you want to customize this app after saving information below, you may need to open it up in Visual studio and re-discover web referances.

 

Classess

 

using System;
using System.Net;
using theplanet.api;
using System.Web; using System.Text.RegularExpressions;

/// /// Summary description for ThePlanetBandWidth /// public class BandwidthFinder { public BandwidthUsage GetBandwidthByDay(string userName, string passWord, int hardwareId) { HardwareBandwidthService hbw = new HardwareBandwidthService(); hbw.Credentials = new NetworkCredential(userName, passWord); GetBandwidthByDayRequest gbDay = new GetBandwidthByDayRequest(); gbDay.HardwareID = hardwareId; gbDay.HardwareIDSpecified = true; gbDay.DayDate = DateTime.Today; gbDay.DayDateSpecified = true; return hbw.GetBandwidthByDay(gbDay); } public BandwidthUsage GetBandwidthByMonth(string userName, string passWord, int hardwareId, DateTime mnth) { HardwareBandwidthService hbw = new HardwareBandwidthService(); hbw.Credentials = new NetworkCredential(userName, passWord); GetBandwidthByMonthRequest gbMonth = new GetBandwidthByMonthRequest(); gbMonth.HardwareID = hardwareId; gbMonth.HardwareIDSpecified = true; gbMonth.MonthDate = mnth; gbMonth.MonthDateSpecified = true; return hbw.GetBandwidthByMonth(gbMonth); } } public class HardwareFinder { public HardwareObject FindHardareByIp(string userName, string passWord, string serverIp) { HardwareHardwareService hrds = new HardwareHardwareService(); hrds.Credentials = new NetworkCredential(userName, passWord); return hrds.GetHardwareByIPAddress(serverIp); } } public class Utils { public static string ConvertByteToKB(long bytes) { const int scale = 1000; string[] orders = new string[] { "GB", "MB", "KB", "Bytes" }; long max = (long)Math.Pow(scale, orders.Length - 1); foreach (string order in orders) { if (bytes > max) return string.Format("{0:##.#}{1}", decimal.Divide(bytes, max), order); max /= scale; } return "0 Bytes"; } public static bool IsValidIP(string addr) { string pattern = @"^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$"; Regex check = new Regex(pattern); bool valid = false; if (addr == "") { valid = false; } else { valid = check.IsMatch(addr, 0); } return valid; } public static string GetIpFromDomain(string domainname) { return Dns.GetHostAddresses(domainname)[0].ToString(); } }

 

   Default.aspx code behind

 

using System;
using theplanet.api;


public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {


       results.Visible = false;


    }


    protected void Button1_Click(object sender, EventArgs e)
    {
        results.Visible = true;
        BandwidthFinder bwr = new BandwidthFinder();
        BandwidthUsage bwu = bwr.GetBandwidthByDay(un.Text, pw.Text, Convert.ToInt32(hwid.Text));
        string _totalusedtitle = "Last 24 hrs' BW: ";

        if (dates.SelectedValue == "1")
        {
            bwu = bwr.GetBandwidthByMonth(un.Text, pw.Text, Convert.ToInt32(hwid.Text),DateTime.Today);
            _totalusedtitle = "This month's BW: ";
        }
        if (dates.SelectedValue == "2")
        {
            bwu = bwr.GetBandwidthByMonth(un.Text, pw.Text, Convert.ToInt32(hwid.Text), DateTime.Today.AddMonths(-1));
            _totalusedtitle = "Last month's BW: ";
        }

        totalused.Text = Utils.ConvertByteToKB(bwu.ActualUsage);
        totalusedtitle.Text = _totalusedtitle;
        allowed.Text = Utils.ConvertByteToKB(bwu.AllowedUsage);
        bwImage.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(bwu.Image);
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        string _ip = "0";

        if (Utils.IsValidIP(ip.Text))
        {
            _ip = ip.Text;
        }
        else
        {
            _ip = Utils.GetIpFromDomain(ip.Text);
        }
        HardwareFinder hrf = new HardwareFinder();
        HardwareObject hrd = new HardwareObject();
        hrd = hrf.FindHardareByIp(un.Text, pw.Text, ip.Text);
        hwid.Text = hrd.HardwareID.ToString();
    }
}

 

Default.aspx html

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        body
        {
            font-size: 90%;
            font-family: Arial, Helvetica, sans-serif;
        }
        .logo
        {
            font-size: 160%;
            font-weight: 900;
            padding-bottom: 10px;
            vertical-align: middle;
        }
        .nav
        {
            background-color: #666666;
            font-size: medium;
            color: #ffffff;
            border: solid 1px #000000;
            padding: 5px;
            vertical-align: middle;
        }
        .result
        {
            text-align: center;
            padding-top: 10px;
        }
        .loading
        {
            vertical-align: middle;
            text-align: center;
            padding-top: 10px;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" AsyncPostBackErrorMessage="There was an error try again!"
        ScriptMode="Release">
    </asp:ScriptManager>
    <div>
        <div style="float: left;" class="logo">
            ThePlanet Orbit API C# Wrapper
        </div>
        <div style="float: right;">
            Hardware id by IP/Domain:
            <asp:TextBox ID="ip" runat="server"></asp:TextBox>
            &nbsp;<asp:Button ID="Button2" runat="server" Text="Find" OnClick="Button2_Click" />
        </div>
        <div style="clear: both;">
        </div>
        <div class="nav">
            Username:
            <asp:TextBox ID="un" runat="server"></asp:TextBox>
            &nbsp;Password:
            <asp:TextBox ID="pw" runat="server"></asp:TextBox>
            &nbsp;Hardware id:
            <asp:TextBox ID="hwid" runat="server"></asp:TextBox>
            &nbsp;<asp:DropDownList ID="dates" runat="server">
                <asp:ListItem Value="0">Last 24 hrs</asp:ListItem>
                <asp:ListItem Value="1">This month</asp:ListItem>
                <asp:ListItem Value="2">Last month</asp:ListItem>
            </asp:DropDownList>
            &nbsp;<asp:Button ID="Button1" runat="server" Text="Get stats" OnClick="Button1_Click" />
        </div>
    </div>
    <div  class="loading">
    <asp:UpdateProgress ID="udProgress" runat="server" DisplayAfter="50"
        Visible="true" DynamicLayout="true">
        <ProgressTemplate>
            <img border="0" src="loading.gif" alt="Loading.." />
        </ProgressTemplate>
    </asp:UpdateProgress>
    </div>
    <asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="Button1" />
        </Triggers>
        <ContentTemplate>
            <asp:Panel ID="results" runat="server" CssClass="result">
                <asp:Image ID="bwImage" runat="server" />
                <br />
                <br />
                <asp:Literal ID="totalusedtitle" runat="server"></asp:Literal>
                <b>
                    <asp:Literal ID="totalused" runat="server"></asp:Literal></b>
                <br />
                Allowed monhtly usage: <b>
                    <asp:Literal ID="allowed" runat="server"></asp:Literal></b>
            </asp:Panel>
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
    <script type="text/javascript">

        var c = new Sys.UI.Control($get("UpdatePanel1"));

        function beginRequestHandler(sender, args) {
            c.set_visible(false);
        }

        function endRequestHandler(sender, args) {
            c.set_visible(true);
        }

        function pageLoad() {
            Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandler);
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequestHandler);
        }
    
    </script>
</body>
</html>

 

Loading gif for Ajax loading progress

 

Web.config

 

<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
	<configSections>
		<sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
			<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
				<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
				<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
					<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
					<section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
					<section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
					<section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/></sectionGroup></sectionGroup></sectionGroup></configSections><system.web>
		<compilation debug="true">
			<assemblies>
				<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
				<add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
				<add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
				<add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation>
		<pages>
			<controls>
				<add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
				<add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></controls></pages>
		<httpHandlers>
			<remove verb="*" path="*.asmx"/>
			<add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add verb="GET,HEAD" path="ScriptResource.axd" validate="false" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></httpHandlers>
		<httpModules>
			<add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></httpModules></system.web>
	<appSettings>
		<add key="theplanet.api.HardwareBandwidthService" value="https://api.theplanet.com/SVC/HardwareBandwidthService.svc"/>
		<add key="theplanet.api.HardwareHardwareService" value="https://api.theplanet.com/SVC/HardwareHardwareService.svc"/>
	</appSettings>
	<system.codedom>
			<compilers>
				<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
					<providerOption name="CompilerVersion" value="v3.5"/>
					<providerOption name="WarnAsError" value="false"/></compiler>
				<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" warningLevel="4">
					<providerOption name="CompilerVersion" value="v3.5"/>
					<providerOption name="OptionInfer" value="true"/>
					<providerOption name="WarnAsError" value="false"/></compiler></compilers></system.codedom>
	<system.webServer>
			<validation validateIntegratedModeConfiguration="false"/>
		<modules>
			<remove name="ScriptModule"/>
			<add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></modules>
		<handlers>
			<remove name="WebServiceHandlerFactory-Integrated"/>
			<remove name="ScriptHandlerFactory"/>
			<remove name="ScriptHandlerFactoryAppServices"/>
			<remove name="ScriptResource"/>
			<add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
			<add name="ScriptResource" verb="GET,HEAD" path="ScriptResource.axd" preCondition="integratedMode" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/></handlers></system.webServer>
	<runtime>
		<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1" appliesTo="v2.0.50727">
			<dependentAssembly>
				<assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/></dependentAssembly>
			<dependentAssembly>
				<assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
				<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/></dependentAssembly></assemblyBinding></runtime></configuration>

 

Download source code ThePlanetOrbitAPI.zip (22.13 kb)

Add comment