Please ensure Javascript is enabled for purposes of website accessibility
Powered by Zoomin Software. For more details please contactZoomin

MES Web API V3

Application Server Usage Example

These scripting example code segments show how to use the MES Web API with Application Server applications.

The MES installation software contains a Power Shell script to register a client application with AVEVA Identity Manager (AIM). This script is in the \InstallFiles\CD-MES\AIMRegistration folder. The script must be run with administrator rights and will create an AIM registration for a named client ID with a specified client secret. This client ID and client secret is used in a client application to get an AIM token for use in calling the MES Web API.

By default, the Power Shell script is configured to allow tokens to exist for 24 hours. When this token is used with the MES Web API, the transaction is treated as a service-to-service transaction, meaning the associated user with the transaction will be the "Default Background User".

For more information about the MES Web API and AIM authentication tokens, see Authentication and Tokens.

Retrieving an AIM Token

Retrieving an AIM token example

dim url as string;

dim request as System.Net.WebRequest;

dim response as System.Net.HttpWebResponse;

dim streamReader as System.IO.StreamReader;

dim aimServer as string;

dim clientId as string;

dim clientSecret as string;

dim encoding as System.Text.Encoding;

dim postData as string;

dim dataBytes[1] as System.Byte;

dim Status;

dim stream as System.IO.Stream;

 

try

     'encrypted client credentials should be read instead of defining them in plain text

     aimServer = "MDDemo";

     clientId = "test1";

     clientSecret = "P@ssw0rd";

 

     'Create token endpoint url

     url = "https://" + aimServer + "/identitymanager/connect/token";

 

     request = System.Net.WebRequest.Create(url);

     request.ContentType = "application/x-www-form-urlencoded";

     request.Method = "POST";

 

     encoding = new System.Text.UTF8Encoding();

     postData = "grant_type=client_credentials&client_id=" + clientId + "&client_secret=" + clientSecret;

     dataBytes = encoding.GetBytes(postData);

     request.ContentLength = dataBytes.Length;

     stream = request.GetRequestStream();

     stream.Write(dataBytes, 0, dataBytes.Length);

     stream.Close();

     response = request.GetResponse();

     Status = response.StatusCode;

     'LogMessage("AIM API Status:" + Status);

 

     if Status == 200 then

          streamReader = new System.IO.StreamReader(response.GetResponseStream());

 

          dim json as System.String;

          dim accessTokenKey as System.String;

          dim accessToken as System.String;

          dim separator as System.String;

          dim list as System.Collections.ArrayList;

 

          json = streamReader.ReadLine();

          'LogMessage("JSON:" + json);

 

          'parse the json response

          list = new System.Collections.ArrayList();

          separator = ",";

          list.AddRange(json.Split(separator.ToCharArray(), 5));

 

          'Access token key should be the first one in the returned list.

          accessTokenKey = list[0];

          separator = ":";

          list = new System.Collections.ArrayList();

          list.AddRange(accessTokenKey.Split(separator.ToCharArray(), 5));

 

          'strip off unnecessary characters to get the access token

          accessToken = list[1];

          accessToken = accessToken.Substring(1, accessToken.Length - 2);

          'LogMessage("Access Token: " + accessToken);

          Me.Token = accessToken;

     endif;

 

catch

     Status = error.Message;

     LogError(error.Message);

endtry;

 

Using a Get to Retrieve a Job

Getting a Job example

dim apiKey as string;

dim Server as string;

dim url as string;

dim data as string;

dim request as System.Net.WebRequest;

dim content as System.IO.Stream;

dim byteArray[1] as System.Byte;

dim response as System.Net.HttpWebResponse;

dim streamReader as System.IO.StreamReader;

dim Status as string;

dim strResp as string;

dim startIndex as integer;

dim endIndex as integer;

dim item as string;

'Other variables not listed here are defined as properties on the object or graphic

try

'Use the client token from the other script

     apiKey = "Bearer " + Me.Token;

'Create url

     Server = "MDDemo";

     url = "https://" + Server + "/MESMW/api/v3/Jobs" + "?woId=" + Me.wo + "&operId=" + Me.operation + "&seqNo=" + Me.SeqNo;

'Create GET request for a job

     request = System.Net.WebRequest.Create(url);

     request.PreAuthenticate = true;

     request.Headers.Add("Authorization", apiKey);

     request.ContentType = "application/json";

     request.Method = "GET";

     'LogMessage("Send and get response for url" + url);

     response = request.GetResponse();

     Status = response.StatusCode;

     'LogMessage("Status:" + Status);

'Extract data from body

     streamReader = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);

     strResp = streamReader.ReadToEnd();

'Check length of response

     if strResp.Length > 0 then

          'LogMessage(strResp);

          'Example to find a specific return value

          startIndex = strResp.IndexOf("""item_id"":") + 11; 'Start position of the item_id which is 7 characters long plus 4 to skip separator characters

          endIndex = strResp.IndexOf("""item_desc"":") - 2; 'Position of next element minus 2 separator characters

          item = strResp.Substring(startIndex, endIndex - startIndex); 'The length of the value

          'LogMessage(item);

     else

          Status = "No data";

     endif;

catch

     Status = error.Message;

     LogError(error.Message);

endtry;

Using a Put to Start a Job

Starting a Job example

dim apiKey as string;

dim url as string;

dim Server as string;

dim data as string;

dim status as string;

dim startTime as System.DateTime;

dim request as System.Net.WebRequest;

dim content as System.IO.Stream;

dim byteArray[1] as System.Byte;

dim response as System.Net.HttpWebResponse;

dim streamReader as System.IO.StreamReader;

dim strResp as string;

dim startIndex as integer;

dim endIndex as integer;

dim state as integer;

try

'Use the client token from the other script.

     apiKey = "Bearer " + Me.Token;

     Server = "MDDemo";

     url = "https://" + Server + "/MESMW/api/v3/Jobs/Start";

'Set the data for the call

     state=3; 'Job State of 3 = Running

     data = System.String.Format("{{""run_ent_id"":""{0}"",""wo_id"":""{1}"",""oper_id"":""{2}"",""seq_no"":""{3}"",""state_cd"":""{4}""}}", Me.EntID, Me.wo, Me.operation, Me.SeqNo, state);

'Send Job Start Put

     request = System.Net.WebRequest.Create(url);

     request.PreAuthenticate = true;

     request.Headers.Add("Authorization", apiKey);

     request.ContentType = "application/json";

     request.Method = "PUT";

'Need to convert the string to stream

     byteArray = System.Text.Encoding.UTF8.GetBytes(data);

     content = request.GetRequestStream();

     content.Write(byteArray, 0, byteArray.Length);

'Send and get response

     response = request.GetResponse();

     Status = response.StatusCode;

     'LogMessage( "After get response");

'Extract data from body

     streamReader = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);

     strResp = streamReader.ReadToEnd();

'Check length of response

     if strResp.Length > 0 then

          'LogMessage(strResp);

'Example to find a specific return value

          startIndex = strResp.IndexOf("""act_start_time_utc"":") + 22; 'Start position of the act_start_time_utc which is 18 characters long plus 4 to skip separator characters

          endIndex = strResp.IndexOf("""act_finish_time_utc"":") - 2; 'Position of next element minus 2 separator characters

startTime = strResp.Substring(startIndex, endIndex - startIndex); 'The length of the element

          'LogMessage(startTime);

     endif;

catch

     Status = error.Message;

     LogError(error.Message);

endtry;

'Cleanup - very important

if content <> null then

     content.Close();

endif;

if response <> null then

     response.Close();

endif;

In This Topic
TitleResults for “How to create a CRG?”Also Available in