Loading...

REST API - Getting Started Using C#

To get started with REST API, a sample script written in C# is discussed: rest_api_csharp_sample.zip. The script demonstrates how to interact with the following APIs:

  • POST Login
  • GET Client Properties
  • POST Client Properties

Libraries

The script uses the following libraries:

  • System
  • System.Collections.Generic
  • System.Linq
  • System.Web
  • System.Diagnostics
  • System.Net
  • System.Xml
  • System.IO
  • System.Text

Parameters

This script takes the following parameters:

  • server: Name of the machine where the web server is installed.
  • username: Name of the CommCell Console user.
  • plainpassword: Password for the user.

Logging On

This part of the script logs on and obtains an authentication token. All API requests must contain an authentication token.

Script

POST: http://<web server host name>:81/SearchSvc/CVWebService.svc/Login
Parameters: None
Body: XML request with the user and a base64 encoded password
Response: XML with an attribute "token"

The variables are set and the GetSessionToken helper function is called. The helper function GetSessionToken does the following:

  • Encodes the password in base64.
  • Passes in the user credentials using the username and password attributes in the <DM2ContentIndexing_CheckCredentialReq> element.
  • Calls the helper function HttpWebResponse to send the request for a token.
  • Checks the response. If the request is successful, a token is returned.

    String service = "http://<server>:81/SearchSvc/CVWebService.svc/";
    public void CVRESTAPISample()
    {
    //1. Login
    string user = "username";
    string pwd = "plainpassword";
    string token = GetSessionToken(user, pwd);
    if (string.IsNullOrEmpty(token))
    {
    Debug.WriteLine("Login Failed");
    }
    else
    {
    Debug.WriteLine("Login Successful");
    }
    //Login successful.
    }
    private string GetSessionToken(string userName, string password)
    {
    string token = string.Empty;
    string loginService = service + "Login";
    byte[] pwd = System.Text.Encoding.UTF8.GetBytes(password);
    String encodedPassword = Convert.ToBase64String(pwd, 0, pwd.Length, Base64FormattingOptions.None);
    string loginReq = string.Format("<DM2ContentIndexing_CheckCredentialReq username=\"{0}\" password=\"{1}\" />", userName, encodedPassword);

    HttpWebResponse resp = SendRequest(loginService, "POST", null, loginReq);
    //Check response code and check if the response has an attribute "token" set
    if (resp.StatusCode == HttpStatusCode.OK)
    {
    XmlDocument xmlDoc = new XmlDocument();
    xmlDoc.Load(resp.GetResponseStream());
    token = xmlDoc.SelectSingleNode("/DM2ContentIndexing_CheckCredentialResp/@token").Value;
    }
    else
    {
    Debug.WriteLine(string.Format("Login Failed. Status Code: {0}, Status Description: {1}", resp.StatusCode, resp.StatusDescription));
    }
    return token;
    }

Getting the Client Properties

This part of the script returns the client properties for a client with a client ID equal to "2."

Note: If the client ID is not known, the GET Client API can be used to retrieve the clientId attribute.

Script

GET: http://<web server host name>:81/SearchSvc/CVWebService.svc/client/{clientId}
Parameters: None
Body: None
Headers: Authtoken (the token received from the login request)

The client ID is set to "2" and the SendRequest helper function is called. The helper function SendRequest sends the token with the request for the client properties. If the request is successful, the client name, host name, and client description are retrieved from the response:

 //2. Get client props. Client Id is hard coded to 2.
public void CVRESTAPIGetClientSample()
{
int iClient = 2;
string clientPropService = service + "client/" + iClient;
HttpWebResponse ClientResp = SendRequest(clientPropService, "GET", token, null);
if (ClientResp.StatusCode == HttpStatusCode.OK)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(ClientResp.GetResponseStream());
//Parse response to get client name, host name and client description
Debug.WriteLine(string.Format("Client properties response: ", xmlDoc.InnerXml));
string clientName = xmlDoc.SelectSingleNode("/App_GetClientPropertiesResponse/clientProperties/client/clientEntity/@clientName").Value;
string clientHostName = xmlDoc.SelectSingleNode("/App_GetClientPropertiesResponse/clientProperties/client/clientEntity/@hostName").Value;
string clientDescription = xmlDoc.SelectSingleNode("/App_GetClientPropertiesResponse/clientProperties/client/@clientDescription").Value;
}
else
{
Debug.WriteLine(string.Format("Get Client properties request Failed. Status Code: {0}, Status Description: {1}", ClientResp.StatusCode, ClientResp.StatusDescription));
}
}
private HttpWebResponse SendRequest(string serviceURL, string httpMethod, string token, string requestBody)
{
WebRequest req = WebRequest.Create(serviceURL);
req.Method = httpMethod;
req.ContentType = @"application/xml; charset=utf-8";
//build headers with the received token
if (!string.IsNullOrEmpty(token))
req.Headers.Add("Authtoken", token);
if (!string.IsNullOrEmpty(requestBody))
WriteRequest(req, requestBody);
return req.GetResponse() as HttpWebResponse;
}

private void WriteRequest(WebRequest req, string input)
{
req.ContentLength = Encoding.UTF8.GetByteCount(input);
using (Stream stream = req.GetRequestStream())
{
stream.Write(Encoding.UTF8.GetBytes(input), 0, Encoding.UTF8.GetByteCount(input));
}
}

Posting the Client Properties

This part of the script updates the job priority.

Note: The XML request is hard coded in the sample script, but it can be read from a file to set the appropriate properties.

POST: http://<web server host name>:81/SearchSvc/CVWebService.svc/client/{clientId}
Parameters: None
Body: XML request to set the properties including the client properties to change
Headers: Authtoken (the token received from the login request)

The new job priority is set. The request to update the job priority is sent using the helper function SendRequest:

//3. Set client props
public void CVRESTAPIUpdateClientSample()
{
//The following request XML is hard coded here but can be read from a file and appropriate properties set.
string newJobPriority = "7";
string updateClientProps = "<App_SetClientPropertiesRequest><clientProperties><clientProps JobPriority=\"<<jobPriority>>\"></clientProps></clientProperties></App_SetClientPropertiesRequest>";
updateClientProps = updateClientProps.Replace("<<jobPriority>>", newJobPriority);
HttpWebResponse clientUpdateResp = SendRequest(clientPropService, "POST", token, updateClientProps);
if (ClientResp.StatusCode == HttpStatusCode.OK)
{
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(clientUpdateResp.GetResponseStream());
Debug.WriteLine(string.Format("Client properties response: ", xmlDoc.InnerXml));
string errorCode = xmlDoc.SelectSingleNode("/App_SetClientPropertiesResponse/response/@errorCode").Value;
if (errorCode == "0")
{
Debug.WriteLine("Client properties set successfully");
}
else
{
Debug.WriteLine("Client properties could not be set. Error Code: " + errorCode);
}
}
else
{
Debug.WriteLine(string.Format("Set client properties request Failed. Status Code: {0}, Status Description: {1}", ClientResp.StatusCode, ClientResp.StatusDescription));
}
}

 

Last modified: 1/9/2018 9:09:52 PM