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 Plesk server via HTTP and receiving the response packet. It has the following members:

public string Hostname

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

public string Login

Holds Plesk Administrator login. Is "admin" by default.

public string Password

Holds Plesk Administrator password. Is "setup" by default.

public string Protocol

Holds the version of API RPC protocol used for interaction with Plesk. Allowed values: 1.3.5.1 | 1.4.0.0 | 1.4.1.0 | 1.4.1.1 | 1.4.1.2 | 1.4.2.0 | 1.5.0.0 | 1.5.1.0 | 1.5.2.0 | 1.5.2.1. Default value: "1.4.2.0".

public ValidationEventHandler XmlSchemaValidation

A handler used to receive schema validation errors.

public string AgentEntryPoint

Holds the URL of Plesk 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 PleskApiRpcClient application. Obtains an array of arguments (strings) to its input parameter. The arguments are:

[0] - the host name (IP address) of the Plesk serverl,

[1] - Plesk Administrator login,

[2] - Plesk Administrator 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 Plesk, 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:

PleskApiRpcClient 192.0.2.168 admin_login admin_passwd 1.4.2.0 "c:\requests\AddNewClient.xml"

 

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

<?xml version="1.0" encoding="UTF-8"?>
<packet version="1.4.2.0">
<client>
<add>
      <gen_info>
            <cname>LogicSoft Ltd.</cname>
            <pname>Stephen Lowell</pname>
            <login>stevelow</login>
            <passwd>steve78</passwd>
            <status>0</status>
            <phone>416 907 9944</phone>
            <fax>928 752 3905</fax>
            <email>host@logicsoft.net</email>
            <address>105 Brisbane Road, Unit 2</address>
            <city>Toronto</city>
            <state/>
            <pcode/>
            <country>CA</country>
      </gen_info>
      <limits>
            <disk_space>100000</disk_space>
            <max_dom>50</max_dom>
            <max_subdom>250</max_subdom>
            <max_webapps>30</max_webapps>
            <max_traffic>50000</max_traffic>
            <max_db>200</max_db>
            <mysql_dbase_space>50000</mysql_dbase_space>
            <max_shared_ssl_links>50</max_shared_ssl_links>
            <expiration>1134616208</expiration>
      </limits>
      <permissions> 
            <create_domains>true</create_domains>
            <manage_phosting>true</manage_phosting>
            <manage_quota>false</manage_quota>
            <manage_subdomains>true</manage_subdomains>
            <change_limits>true</change_limits>
            <manage_dns>true</manage_dns>
            <manage_log>true</manage_log>
            <manage_anonftp>true</manage_anonftp>
            <manage_webapps>true</manage_webapps>
            <manage_sh_access>true</manage_sh_access>
            <manage_maillists>true</manage_maillists>
            <make_dumps>true</make_dumps>
            <remote_access_interface>true</remote_access_interface>
            <cp_access>true</cp_access>
            <manage_domain_aliases>true </manage_domain_aliases>
      </permissions>
</add>
</client>
</packet>

 

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

<?xml version="1.0"?>
<packet version="1.4.2.0">
<client>
<add>
      <result>
            <status>ok</status>
            <id>2</id>
      </result>
</add>
</client>
</packet>

 

This packet returns the result of the add operation and the unique identifier of the client account just created and registered in Plesk database.

 

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 PleskApiRpcClient
{
      public class Request
      {
            // Public interface
            //
            public string Hostname	= "localhost";	 // Control Panel Hostname
            public string Login	= "admin_login";	       // Administrator Login
            public string Password	= "admin_passwd";		 // Administrator Password
            public string Protocol	= "1.4.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: PleskApiRpcClient <Hostname> <Login> <Password> <Protocol> <Request>");
                        Console.WriteLine("  ");
                        Console.WriteLine("  Hostname  - Control Panel hostname");
                        Console.WriteLine("  Login     - Administrator login");
                        Console.WriteLine("  Password  - Administrator 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.4.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();
            }
      }
}