C# Client Application

The following code sample presents ready-to-use client application written in C#.

 

Comments

Class Request implements sending a request packet to the Panel-managed server via HTTP and receiving the response packet. It has the following members:

public string Hostname

Holds the host name (IP address) of the Panel-managed server to which the request packet is sent. Is "localhost" by default.

public string Login

Holds the Panel administrator's login. Is "admin" by default.

public string Password

Holds the Panel administrator's password. Is "setup" by default.

public string Protocol

Holds the version of API RPC protocol used for interaction with the Panel.

public ValidationEventHandler XmlSchemaValidation

A handler used to receive schema validation errors.

public string AgentEntryPoint

Holds the URL of the Panel Agent that will handle the request packet on the server side.

public string InputValidationSchema

Holds the URL of the validation schema that will be applied to the request packet before it is sent to the server side.

public string OutputValidationSchema

Holds the URL of the validation schema that will be applied to the response packet after it is received on the client side.

public XmlDocument Send (XmlDocument)

Gets the request packet (in the form of the XmlDocument object) to its input parameter. Sends a request and gets the response in the form of the XmlDocument object.

public XmlDocument Send (Stream)

Gets the request packet (a stream) to its input parameter. Validates the request packet using the agent_input.xsd validation schema. Invokes the Send(XmlDocument) member function.

public XmlDocument Send (string)

Gets the URI of the request packet (XML file) to its input parameter. Validates the request packet using the agent_input.xsd validation schema. Invokes the Send(XmlDocument) member function.

private HttpWebRequest SendRequest (string)

Forms an HTTP request: puts the HTTP header and serialized XML packet to the object of type HttpWebRequest. Returns this object.

private XmlDocument ParseAndValidate (TextReader, string)

Gets the URI of the agent_input.xsd schema and a string reader (with the URI of the XML packet to validate) to its input parameters. Validates the packet and returns it structured as a tree (an XmlDocument object).

private XmlDocument GetResponse (HttpWebRequest)

Gets the HTTP request packet (HttpWebRequest object) to its input parameter. Sends the packet via HTTP, receives the response packet from the server, validates it using the agent_output.xsd schema, and returns the response XML packet structured as a tree (an XmlDocument object).

 

Class Program implements the 'client' console application.

static void Main (string[])

An entry point to the PanelApiRpcClient application. Obtains an array of arguments (strings) to its input parameter. The arguments are:

[0] - the host name (IP address) of the Panel-managed server,

[1] - the Panel administrators' login,

[2] - the Panel administrator's password,

[3] - the API RPC protocol used,

[4] - a path of the XML file with an XML request packet.

The function forms a request packet of type Request (see above), validates it, sends a request to the Panel, and prints out the resulting XML packet.

private static bool RemoteCertificateValidation (object, X509Certificate, X509Chain, SslPolicyErrors)

The function verifies the remote SSL certificate to authenticate the server. If the server is not authenticated, returns false.

private static void XmlSchemaValidation (object, ValidationEventArgs)

Validation error event handler.

static void PrintResult(XmlDocument)

The function outputs the response packet (an XmlDocument object) to the console.

 

The client application can be started from command line as follows:

PanelApiRpcClient 192.0.2.168 admin_login admin_passwd 1.6.2.0 "c:\requests\AddNewDomain.xml"

 

The request packet is passed in the AddNewDomain.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<packet version="1.6.2.0">
<domain>
    <add>
      <gen_setup>
        <name>example.com</name>
        <ip_address>192.0.2.48</ip_address>
      </gen_setup>
      <hosting>
        <vrt_hst>
          <property>
            <name>ftp_login</name>
            <value>fpt16se4fdf0</value>
          </property>
          <property>
            <name>ftp_password</name>
            <value>qweqwe</value>
          </property>
          <ip_address>192.0.2.48</ip_address>
        </vrt_hst>
      </hosting>
    </add>
  </domain>
</packet> 

The response packet received from the server can look as follows:

<?xml version="1.0"?>
<packet version="1.6.2.0">
  <domain>
    <add>
      <result>
        <status>ok</status>
        <id>6</id>
        <guid>5c0e3881-22a2-4401-bcc0-881d691bfdef</guid>
      </result>
    </add>
  </domain>
</packet>

 

This packet returns the result of the add operation and ID and GUID of the domain just created.

 

Code sample

 

using System;
using System.Net;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
 
namespace PanelApiRpcClient
{
      public class Request
      {
            // Public interface
            //
            public string Hostname	= "localhost";	 // Panel Hostname
            public string Login	= "admin_login";	       // Administrator's Login
            public string Password	= "admin_passwd";		 // Administrator's Password
            public string Protocol	= "1.6.2.0";	 // API RPC Version Protocol. 
                            
                                                       
            // Handler for receiving information about document type definition (DTD),
            // XML-Data Reduced (XDR) schema, and XML Schema definition language (XSD) 
            // schema validation errors. 
            public ValidationEventHandler XmlSchemaValidation = null;
            
            public Request()
            {
            }
            
            public string AgentEntryPoint        { get { return "https://" + Hostname + ":8443/enterprise/control/agent.php"; } }
            
            public string InputValidationSchema  { get { return "https://" + Hostname + ":8443/schemas/rpc/" + Protocol + "/agent_input.xsd"; } }
            public string OutputValidationSchema { get { return "https://" + Hostname + ":8443/schemas/rpc/" + Protocol + "/agent_output.xsd"; } }
            
            public XmlDocument Send(XmlDocument packet)
            {
                  HttpWebRequest request = SendRequest(packet.OuterXml);
                  XmlDocument result = GetResponse(request);
                  return result;
            }
            public XmlDocument Send(Stream packet)
            {
                  using (TextReader reader = new StreamReader(packet))
                  {
                        return Send(ParseAndValidate(reader, InputValidationSchema));
                  }
            }
            public XmlDocument Send(string packetUri)
            {
                  using (TextReader reader = new StreamReader(packetUri))
                  {
                        return Send(ParseAndValidate(reader, InputValidationSchema));
                  }
            }
		
            // Private interface
            //
            
            // Sending a request message
            //
            private HttpWebRequest SendRequest(string message)
            {
                  HttpWebRequest request = (HttpWebRequest)WebRequest.Create(AgentEntryPoint);
			
                  request.Method = "POST";
                  request.Headers.Add("HTTP_AUTH_LOGIN", Login);
                  request.Headers.Add("HTTP_AUTH_PASSWD", Password);
                  request.ContentType = "text/xml";
                  request.ContentLength = message.Length;
			
                  ASCIIEncoding encoding = new ASCIIEncoding();
                  byte[] buffer = encoding.GetBytes(message);
			
                  using (Stream stream = request.GetRequestStream())
                  {
                        stream.Write(buffer, 0, message.Length);
                  }
			
                  return request;
            }
		
            // Parsing and validating packet
            //
            private XmlDocument ParseAndValidate(TextReader xml, string schemaUri)
            {
                  XmlSchemaSet schemas = new XmlSchemaSet();
                  schemas.Add(null, schemaUri);
			
                  XmlReaderSettings settings = new XmlReaderSettings();
                  if (XmlSchemaValidation != null)
                        settings.ValidationEventHandler += new ValidationEventHandler(XmlSchemaValidation);
                  settings.ValidationType = ValidationType.Schema;
                  settings.ValidationFlags |= XmlSchemaValidationFlags.ProcessSchemaLocation;
                  settings.Schemas = schemas;
			
                  XmlDocument document = new XmlDocument();
			
                  using (XmlReader reader = XmlTextReader.Create(xml, settings))
                  {
                        document.Load(reader);
                  }
			
                  return document;
            }
            private XmlDocument GetResponse(HttpWebRequest request)
            {
                  using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                  using (Stream stream = response.GetResponseStream())
                  using (TextReader reader = new StreamReader(stream))
                  {
                        return ParseAndValidate(reader, OutputValidationSchema);
                  }
            }
      }
                        
      class Program
      {
            static void Main(string[] args)
            {
                  if (args.Length < 5)
                  {
                        Console.WriteLine("Usage: PanelApiRpcClient <Hostname> <Login> <Password> <Protocol> <Request>");
                        Console.WriteLine("  ");
                        Console.WriteLine("  Hostname  - Panel host name");
                        Console.WriteLine("  Login     - Administrator's login");
                        Console.WriteLine("  Password  - Administrator's password");
                        Console.WriteLine("  Protocol  - API RPC protocol version");
                        Console.WriteLine("  Request   - Request file path (*.xml)");
                        return;
                  }

                  // Verifies the remote Secure Sockets Layer (SSL) certificate 
                  // used for authentication.
                  ServicePointManager.ServerCertificateValidationCallback =
				new RemoteCertificateValidationCallback(RemoteCertificateValidation);

                  Request request = new Request();
                  request.XmlSchemaValidation = XmlSchemaValidation;

                  request.Hostname	= args[0]; // "10.49.8.120";
                  request.Login	= args[1]; // "admin";
                  request.Password	= args[2]; // "setup";
                  request.Protocol	= args[3]; // "1.6.2.0";

                  string packet	= args[4]; // "request.xml";

                  try
                  {
                        XmlDocument result = request.Send(packet);

                        PrintResult(result);
                  }
                  catch (Exception e)
                  {
                        Console.WriteLine("Request error: {0}", e.Message);
                  }
            }
		
            // The following method is invoked by the RemoteCertificateValidationDelegate.
            private static bool RemoteCertificateValidation(object sender,
                  X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                  if (sslPolicyErrors != SslPolicyErrors.RemoteCertificateNotAvailable)
				return true;
		
                  Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
		
                  // Do not allow this client to communicate with unauthenticated servers.
                  return false;
            }
            // 
            private static void XmlSchemaValidation(object sender, ValidationEventArgs e)
            {
                  Console.WriteLine("Validation error: {0}", e.Message);
            }
		
            static void PrintResult(XmlDocument document)
            {
                  XmlTextWriter writer = new XmlTextWriter(Console.Out);
                  writer.Formatting = Formatting.Indented;
		
                  document.WriteTo(writer);
		
                  writer.Flush();
                  Console.WriteLine();
            }
      }
}