C-API
CAPIs provide users to enhance test scripts. NetStorm allows users to use their own inbuilt APIs written in C, also called as NetStorm functions or more formally NSFunctions. These APIs can further be divided into categories depending on their usage and functionalities.
While adding a C API, a user can search the API name in the dropdown list by typing instead of manually searching for the same.
C-APIs list
1 | ns_save_string() | To save a null-terminated string to an ns variable. |
2 | ns_eval_string() | To evaluate the string representation of the ns variable. |
3 | ns_log_msg() | Helps to log messages from the script, with format specifier to test run directory. |
4 | ns_log_string() | To log a simple string from the script to test the run directory. |
5 | ns_get_ua_string() | Returns the user agent string |
6 | ns_set_ua_string() | Used to set the user agent string. |
7 | ns_get_pg_think_time() | Returns the page think time in milliseconds. |
8 | ns_page_think_time() | Sets the page think time for ctype scripts. Accepts value in double. |
9 | ns_encode_url() | Escapes URL strings (Converts all letters considered illegal in their %XX values). |
10 | ns_decode_url() | It un-escapes all URL encoding to a string representation. |
11 | ns_paramarr_len() | Returns the length of the search parameter array |
12 | ns_paramarr_idx() | Returns value of search parameter array at a particular index. |
13 | ns_paramarr_random() | Returns a random value from the search parameter array. |
14 | ns_get_int_val() | Returns the integer value of a ns variable |
15 | ns_set_int_val() | Sets a ns variable to an integer value. |
16 | ns_encode_save_string() | Encodes a string and saves it to a ns variable. |
17 | ns_encode_eval_string() | This further encodes the evaluated string. |
18 | ns_url_get_http_status_code() | Returns the HTTP status code. Ex 200, or 404 |
19 | ns_url_get_body_msg() | Returns the whole body part of the URL. |
20 | ns_url_get_body_size() | Returns the size of body in bytes. |
21 | ns_url_get_resp_msg() | Returns the response message of the URL |
22 | ns_get_redirect_url() | Returns the url to which the main URL is redirected. |
23 | ns_is_rampdown_user() | Returns 0 if user is ramped down and 1 if user is not ramped down. |
24 | ns_save_data_var() | Saves netstorm variable value to a data file. |
25 | ns_save_data_ex() | Saves data as per the given format in the data file |
26 | ns_save_data_eval() | Saves data as per the given eval string in the data file. |
27 | ns_set_cookies_disallowed() | Sets disallowed cookies flag |
28 | ns_get_cookies_disallowed() | Gets disallowed cookies flag |
29 | ns_get_auto_cookie_mode() | Returns the mode value. It can be 0,1,2,3,4 |
30 | ns_add_cookie_val_ex() | Sets the value of the cookie. |
31 | ns_get_cookie_val_ex() | Returns pointer to a cookie value populated in a static buffer or NULL if cookie name is not found |
32 | ns_get_cookie_idx() | Gets cookies Idx from its name. |
33 | ns_get_cookie_val() | Returns Pointer to cookie value populated in a static buffer or NULL if cookie name is not found. |
34 | ns_set_cookie_val() | Set the cookie value using hash code. |
35 | ns_advance_param() | Advances to the next available value in the file parameter. |
36 | ns_get_max_ka() | Returns the maximum num_ka used by the netstorm at the time of calling this API. |
37 | ns_get_min_ka() | Returns the minimum num_ka used by the netstorm at the time of calling this API. |
38 | ns_get_num_ka_pct() | Return the keep alive percentage used by the netstorm at the time of calling this API |
39 | ns_set_ip_address() | Sets the local IP address. |
40 | ns_get_user_ip() | Returns the user IP. |
41 | ns_get_area_ip() | Takes area ID and returns IP in integer format. |
42 | ns_get_area_ip_char() | Same as above but outputs in AAA.BBB.CCC.DDD format |
43 | ns_get_session_status() | Returns the status of the session in string format |
44 | ns_get_sessid() | Returns the session id of each session if multiple sessions are being used while running test. |
45 | ns_get_test_id() | Returns the test run no of current test. |
46 | ns_get_guid() | Returns the global unique ID. |
47 | ns_get_nvmid() | Returns the Netstorm Virtual ID |
48 | ns_param_sprintf() | Writes formatted string to a netstorm variable. |
49 | ns_set_embd_objects | Sets embedded url or objects for a main URL. Takes first argument as number of embedded URL’s and second one is list of embedded URL’s to set in page. |
50 | do_shmget() | Creates a shared memory and returns the start address that can be type casted to other type. |
51 | ns_get_status_name | Takes status as argument and returns URL,Page and Transaction status string. |
52 | ns_encode_decode_url_free() | Used to de-allocation in the same unit that did the allocation. |
53 | ns_add_user_data_point() | Used to set graph data value of user monitor. |
54 | ns_check_response_size() | Used to compare the response size with user defined value1 and value2. |
Return values are:- | ||
0-On success if the response size is as per mode. | ||
1-If response/reply size is small | ||
2-If response/reply size is big | ||
-1 On error. | ||
55 | ns_get_num_nvm() | Returns the no of process in netstorm execution(NVM-Netstorm Virtual Machine ) |
56 | ns_url_get_resp_size() | Returns the size of the response (bytes of body received or bytes of chunks). |
Returns -1 on error. | ||
57 | ns_get_session_status_name() | Takes status as string and returns in char string like MiscErr. |
58 | ns_get_userid() | Returns the id of the user executing the script. |
59 | ns_ip_to_char() | Takes int as argument and returns IP in dotted decimal notation. |
60 | ns_set_pg_think_time() | Sets the page think time for legacy type scripts. |
Note: In script, if any C-API is present outside the flow, which is present inside RunLogic, then that C-API will not be executed.
Using C-APIs in Scripts
The user needs to follow the below-mentioned steps for using C-APIs in a sample application:
- Right-click on the Flow file
- Go to Insert Menu
- Click on CAPI
Or
- Go to File menu
- Click on Insert
- Click on CAPI
Following dialog box is displayed:
String Functions
String functions are used to set the value of variables and to evaluate strings with embedded parameters. The following String functions are available:
ns_eval_string
Description
This API is used to evaluate the string representation of the NS variable.
Fields
It has the following fields:
- Evaluation String: This string contains a NS variable which is selected from the list of parameters. All occurrences of NS variable are replaced in the input string with the NS variable’s current value.
- Parameter: A list of all parameters is stored in script.capture file. The selected parameter is appended to the evaluation string.
- Return Variable: This is an optional field. This is used in case a user wants to save the return value of the API in an already defined variable of c file.
Example
char value[64]; char *ptr; ptr = ns_eval_string(“Test run is {run_count}”); printf (“%s\n”, ptr);
If the current value of run_count NS variable is 20, then printf function print – Test run is 20.
In this case, Test run is {run_count} is an evaluation string with run_count is NS variable and ptr is return variable.
![]() | Parameter list is empty and disabled in case of no parameter defined in script.capture file. String pointer returned by ns_eval_string is a static buffer pointer. ns_eval_string keeps using the same buffer for all ns_eval_string() calls. So, the next call to ns_eval_string would overwrite the last contents returned by ns_eval_string. If the contents are required to be used downstream, they should be saved in some local buffer. To save the contents, use strncpy (ptr, value, 64); value would now hold the required string. |
Validations
Search Parameter with ns_eval_string cases result for NetOcean
ORD | USE in eval string | LB, RB occurrence in Request | Result |
1 | SearchParam | 1 | first occurrence value is returned. |
1 | SearchParam_2 | 1 | same string { SearchParam_2} filled |
1 | SearchParam | Not Found | empty string returned with 0 length |
ALL | SearchParam_2 | 4 | 2nd occurrence value is returned |
ALL | SearchParam_6 | 4 | same string {SearchParam_6} |
Search Parameter with ns_eval_string cases result for NetStorm
Search Parameters Usage
nsl_search_var(RespOrderNumber, PAGE=*, LB="<RESP_ORDER_NUMBER>", RB="</RESP_ORDER_NUMBER>", RETAINPREVALUE="YES"); nsl_search_var(NotFound, PAGE=*, LB="<title>", RB="</title>", RETAINPREVALUE="YES"); nsl_search_var(ProdIdSearch, PAGE=*, LB="<PRODUCT_ID>", RB="</PRODUCT_ID>", ORD=ALL, RETAINPREVALUE="YES");
Test Cases
printf("Case 1 : Output :%s\n",ns_eval_string("{RespOrderNumber}")); printf("Case 2 : Output :%s\n",ns_eval_string("{RespOrderNumber_2}")); printf("Case 3 : Output :%s\n",ns_eval_string("{NotFound}")); printf("Case 4 : Output :%s\n",ns_eval_string("{ProdIdSearch_2}")); printf("Case 5 : Output :%s\n",ns_eval_string("{ProdIdSearch_6}"));
Result in Progress Report
Case 1 : Output :2005610012 Case 2 : Output :{RespOrderNumber_2} Case 3 : Output : Case 4 : Output :91709210891 Case 5 : Output : Invalid index of the variable. Index = 6, Count = 4
ns_save_string
Description
This API is used to save a null-terminated string to a NS variable (or parameter). This is the only way to assign a value to a NS variable (if an assignment is allowed for its type).
Fields
It has the following fields:
- Variable Value: This is the value that is assigned to the Variable Name.
- Variable Name: This is the name of the NS variable. Variable name must be declared in the capture file and it should be of the type that supports setting the value.
- Return Variable: ns_save_string assigns the null terminated variable value to NS Variable variable_name. For function to succeed, it returns 0 on success and -1 on failure. This return value can be assigned to a return variable defined in a script.c file if required.
Example
ns_save_string(“Load”, “action-type”); #This sets the value of NS variable action-type to Load. ns_save_string(“null”, “action-type”); #This sets the value of NS variable action-type to null.
![]() | Parameter list is empty and disabled in case of no parameter defined in script.capture file (same as in the above case). |
Validations
The variable value cannot be empty since the argument an API cannot be null.
ns_save_searched_string API
Description
This API is used to save a searched string to a NS variable.
Fields
It has the following fields:
- Input Type: This field specifies the input type. If the input type is a buffer, then NS_ARG_IS_BUF is used for this field. If the input type is a parameter, then NS_ARG_IS_PARAM is used for this field.
- Input: This field is used for input. If the input type is NS_ARG_IS_BUF, then the input must be a buffer and if the input type is a parameter then input is any parameter, such as search parameter, declare parameter, file parameter, and so on.
- Output Type: This field is used to specify the output type. It can be NS_ARG_IS_BUF if the output is stored in a buffer or NS_ARG_IS_PARAM if the output is stored in a parameter.
- Output: This field is used for output. If the output type is NS_ARG_IS_BUF, then the output must be a buffer and if the output type is a parameter, then output is any parameter, such as search parameter, declare parameter, file parameter, and so on.
- LB: This field is used to provide the left bound of the string.
- RB: This field is used to provide the right bound of the string.
- ORD: This field is used to provide ORD value it can be, NS_ORD_ALL, NS_ORD_ANY, or any positive integer.
- Start Offset: This field can be NS_FROM_START or any positive integer value.
- Save Length: This field is used to specify the length of the string that which user want to save in output. It can be any positive integer value or NS_SAVE_COMPLETE.
![]() | In case of ORD= NS_ORD_ALL, the user can save the output in declare array type parameter only. |
Example
ns_save_searched_string(NS_ARG_IS_BUF, msg_buf, NS_ARG_IS_PARAM, "UPC", "<abc>", "</abc>", NS_ORD_ANY,NS_FROM_START, NS_SAVE_COMPLETE) ns_save_searched_string(NS_ARG_IS_BUF, msg_buf, NS_ARG_IS_PARAM, "UPC", "<abc>", "</abc>", NS_ORD_ALL, 2, 10) Here UPC is nsl_decl_array type variable. ns_save_searched_string(NS_ARG_IS_PARAM, UPC, NS_ARG_IS_PARAM, "UPC1", "<abc>", "</abc>", NS_ORD_ANY,NS_FROM_START, NS_SAVE_COMPLETE)
ns_chk_strcpy
Description
This API is used to copy string from source buffer to destination buffer. If source length is more that destination buffer length, then string is truncated. Following is the syntax of this API:
int ns_chk_strcpy(char *dest, char *src, int dest_len)
Fields
It has following fields:
- dest: Destination buffer. It is always a C variable.
- src: Source buffer. It can be constant or C variable.
- dest_len: Destination buffer length including one byte for NULL termination.
Return Values
- 0: If string is copied without truncation
- 1: If string is copied with truncation as destination buffer is shorter than source buffer
Example char src[128 + 1] = "This is a test string"; int ret; // Case 1 - String will be copied without truncation #define DEST1_BUF_LEN 32 char dest1[DEST1_BUF_LEN + 1]; ret = ns_chk_strcpy(dest1, src, (DEST1_BUF_LEN + 1)); printf("ret = %d, dest = %s\n", ret, dest1); // Case 2 - String will be copied with truncation #define DEST2_BUF_LEN 20 char dest2[DEST2_BUF_LEN + 1]; ret = ns_chk_strcpy(dest2, src, (DEST2_BUF_LEN + 1)); printf("ret = %d, dest = %s\n", ret, dest2);
Validation
- The destination field contains only C-API.
- The Source field contains only C-API in case of the checkbox is selected otherwise it is treated as constant.
- Length field if used for Destination buffer length including one byte for NULL termination.
- The return variable field contains the API return value.
ns_save_data_eval
Description: This API is used to write var data in a file either in append or truncate mode.
Syntax: int ns_save_data_eval (char file_name, int mode, char eval_string);
Where var can be either C Buffer or NS Variable.
There are two modes for the same.
- NS_TRUNC_FILE – It is used to truncate a given file if exists.
- NS_APPEND_FILE – It is used to append in a given file if exists.
Example
ns_save_string(“this is cavisson”, “data”); //Where data is NS Variable.
ns_save_data_eval(“/tmp/testData.txt”, NS_TRUNC_FILE, “{data}”); //Here storing data’s value in file “/tmp/testData.txt” in truncate mode.
Note:
1- Maximum data value can be 5KB, value will be truncated in case of more than 5KB.
2- The return type is 0 in case of success.
Log Message Functions
Log Message Functions help to create a log of the message from scripts. The following NS functions are available in this category:
ns_log_msg
Description
This API is used to create a log of user-specified messages.
Fields
- Level: It is the log level to which the logged message belongs. Possible values of Level are NS_LOG_STD, NS_LOG_EXTENDED, and NS_LOG_DEBUG.
- String Variable: This is the string variable already defined in c file.
- String: This is the string message with the format placeholder of the above string variable defined in c file.
- Return Variable: This API returns an integer value which should be stored in a return variable of int
Example
char *x = "Hello"; int retValue; retValue = ns_log_msg(level, "%s World", x); Output of above == > Hello World
![]() | Select the Check if C Variable checkbox before using value of variable x. |
Logs
Test Scripts may log user messages using ns_log_msg () NS Function. Logged messages have a log level associated with it. Log level specifies the verbosity of the message. Messages with higher log levels represent a higher level of verbosity. At run time, the log messages are enabled by checking the appropriate selection on the Log Tab of the Run Time Settings screen.
All possible values for log level are:
- NS_LOG_STD: Mostly the error messages which typically should always be on.
- NS_LOG_EXTENDED: Verbose messages which typically should be on for small test runs.
- NS_LOG_DEBUG: Debug message which typically should be on for debugging purposes.
Format and the argument(s) following it are same as the format and the arguments taken by printf. By default, Standard logs are logged to standard out. All other logs messages are disabled. When the logging to file option is enabled, messages are logged to TRxxx/logs. xxx is the Test run number. Also, these messages can be viewed only after the completion of the test run.
ns_log_string
Description
This API is used to create a log of strings.
Fields
- Level: level is the log level to which the logged message belongs. Possible values of Level are NS_LOG_STD, NS_LOG_EXTENDED, and NS_LOG_DEBUG.
- String Variable: This is the string message to be logged or maybe a string variable already defined in string.c file.
- Return Variable: This API returns an integer value which should be stored in a return variable of int type.
Keywords APIs
following are the Keywords APIs:
ns_get_num_nvm
Description
This API is used to get num_process in the NetStorm execution NetStorm Virtual Machine (NVM).
Syntax
int ns_get_num_nvm()
Return Value
Returns the num processes.
Example
int num = 0; num = ns_get_num_nvm(); printf(“nvm = %d”,num); Optional variable return value contains the variable name which have the value returned by this API.
ns_get_num_ka_pct
Description
This API is used to get the keep alive percentage used by the NetStorm at the time of calling this API.
Syntax
int ns_get_num_ka_pct()
Returns Value
Returns the keep alive percentage used by the netstorm at the time of calling this API.
Example
int Kapct ; Kapct = ns_get_num_ka_pct(); Printf(“%d”,Kapct);
ns_get_min_ka
Description
This API is used to get the minimum keep alive time used by the NetStorm at the time of calling this API.
Syntax
int ns_get_min_ka()
Returns Value
Return the minimum keep alive time used by the netstorm at the time of calling this API.
Example
int minKa = 0; minKa = ns_get_min_ka(); printf(“%d”,minKa);
ns_get_max_ka
Description
This API is used to get the maximum keep alive time used by the NetStorm at the time of calling this API.
Syntax
int ns_get_max_ka()
Returns Value
Returns the maximum keep alive time used by the NetStorm at the time of calling this API.
Example
int maxKa =0; maxKa = ns_get_max_ka(); printf(“%d”,maxKa);
Information Functions
ns_get_session_status
Description
This API is used to get the session status code.
Syntax
int get_session_status();
Return Value
Returns page session code.
Example
int SessCode; SessCode = ns_get_session_status(); Printf(“current session status code is: %d”, SessCode);
ns_get_auto_cookie_mode
Description
This API returns mode value which may have following possible values:
- Disable auto cookie, i.e. do not use Auto cookie (Default)
- Use auto cookie with name, path and domain
- Use auto cookie with name only
- Use auto cookie with name and path only
- Use auto cookie with name and domain only
Syntax
ns_auto_cookie_mode();
Return Value
Returns integer value.
Example
int mode ; mode = ns_get_auto_cookie_mode(); printf(“%d”,mode);
ns_get_ua_string
Description
This API is used to get the user agent value.
Syntax
char * ns_get_ua_string ();
Example
char *uaStr = ns_get_ua_string (); printf(“%s”,uaStr);
ns_get_cookies_disallowed
Description
This API is used to get disallowed cookie flag which shows whether or not cookies are allowed. It sets the cookie allowed or not flag. Val = 1 means cookies are disallowed.
Syntax
ns_get_cookies_disallowed();
Return Value
This API returns Boolean value.
Example
Flag = ns_get_cookies_disallowed();
ns_get_user_ip
Description
This API is used to get the user IP.
Syntax
char *ns_get_user_ip();
Return Value
Returns the user ip.
Example
Char* uip = ns_get_user_ip(); Printf(“%s”, uip);
ns_get_nvmid
Description
This API is used to get the NVM ID.
Syntax
int ns_get_nvmid();
Return Value
This API returns the NVM-Id.
Example
int nvmId = ns_get_nvmid(); printf(“%d”, nvmId);
ns_get_userid
Description
This API is used to get the user id.
Syntax
unsigned long ns_get_userid();
Return Value
This API returns the user id.
Example
Unsigned long userid = ns_get_userid(); Printf(“%l”,userid);
ns_get_sessid
Description
This API is used to get the current session id.
Syntax
unsigned long ns_get_sessid();
Return Value
Returns the session-id.
Example
Unsigned long sessid = ns_get_sessid(); Printf(“%l”,sessid);
ns_get_testid
Description
This API is used to get the test run number.
Syntax
ns_get_testid();
Return Value
This API returns integer value.
Example
int testid = ns_get_testid(); printf(“%d”,testid);
ns_get_guid
Description
This API is used to get the global unique-id.
Syntax
char * ns_get_guid();
Return Value
This API returns the global unique-id.
Example
char* guid = ns_get_guid(); printf(“%s”,guid);
ns_is_rampdown_user
Description
This API is used to check the vuser is in rampdown phase or not.
Syntax
int ns_is_rampdown_user(void);
Return Value
This API returns integer value.
Example
int isRampDown = ns_is_rampdown_user(); Printf(“%d”,isRampDown);
ns_get_redirect_url
Description
This API is used to stores redirected-to location.
Syntax
char *ns_get_redirect_url()
ns_get_pg_think_time
Description
This API is used to get the page think time.
Syntax
int ns_get_pg_think_time()
Return Value
This function returns integer value.
Example
int time = ns_get_pg_think_time(); printf(“%d”,time);
ns_get_int_val
Description
This API is used to get the integer value of the NS variable (or parameter) var_name.
Syntax
int ns_get_int_val (char * var_name);
Return Value
Returns 0 on success and –1 on failure. Function fails, if the variable is invalid or variable length is greater than and equal to 4096.
Example
int val = 0; val = ns_get_int_val(param); Printf(“integer value of the parameter %s is %d”,param,val);
ns_set_int_val
Description
This API is used to set the value to a NS variable (or parameter).
Syntax
int ns_set_int_val (char * var_name, int value);
Return Value
Returns 0 on success, -1 if not allowed, -2 if size is more than max size.
Example
int value = 0; Value = ns_set_int_val(param,12); Printf(“%d”,Value);
ns_get_cookie_idx
Description
Get the hash code of the cookie.
Syntax
int ns_get_cookie_idx (char *cname, char *sname)
Cname – Cookie Name
Sname – Session Name
Return Value
This API returns the integer identity of the cookie.
Example
int idx = ns_get_cookie_idx(cname, sname); printf(“%d”,idx);
ns_get_cookie_val
Description
This API is used to get the cookie value by hash code.
Syntax
ns_get_cookie_val();
Return Value
This API returns string value.
Example
s_val_cookie = ns_get_cookie_val(); printf(“%s”,s_val_cookie);
ns_get_cookie_val_ex
Description
This API is used to get cookie value populated in a static buffer.
Syntax
char *ns_get_cookie_val_ex(char *cookie_name, char *domain, char *path)
Where
cookie_name – Cookie Name
domain – Get Cookie of this domain. NULL if domain is not to be checked
path – Get Cookie of this path. NULL if path is not to be checked
Return Value
This API returns Pointer to cookie value populated in a static buffer or NULL if cookie name is not found.
Example
char* val = ns_get_cookie_val_ex(cname, domain,path); printf(“%s”,val); char *sessionIdValue = ns_get_cookie_val_ex ("sessionid", NULL, NULL); ns_log_msg(NS_LOG_DEBUG, "Cookie sessionid value = %s", sessionIdValue);
In case where Domain Name and Path Name are NULL, select For all Domain and For all Path check box.
ns_set_cookie_val
Description
This API is used to set the cookie value using hash code.
Syntax
int ns_set_cookie_val (int cookie_idx, char *cookie_val)
Return Value
This API sets the value of the cookie.
Example
cookieIdx = ns_get_cookie_idx(); int val = ns_set_cookie_val(cookieIdx, cookie_val); printf(“%d”,val);
ns_set_cookie_val_ex
Description
This API is used to set the value of the cookie.
Syntax
int ns_set_cookie_ex (char *cookie_name, char *domain, char *path, char *cookie_val)
Where,
cookie_name – Cookie Name
domain – Get Cookie of this domain. NULL if domain is not to be check
path – Get Cookie of this path. NULL if path is not to be check
cookie_val – Value of the cookie.
Return Value
Pointer to 0 is successful or -1 if cookie name is not found.
Example
int setCookieVal = ns_set_cookie_val_ex(cname,domain,path,cookie_val); printf(“%d”,setCookieVal); char cookie_buf[4096]; char *ENDECAVal = ns_get_cookie_val_ex ("ENDECA", NULL, NULL); sprintf(cookie_buf, "%s&Nn=48", ENDECAVal); ns_set_cookie_val_ex("ENDECA", NULL, NULL, cookie_buf);
In case where Domain Name and Path Name are NULL, select For all Domain and For all Path check box.
ns_set_ip_address
Description
This API is used to set the local IP address.
Syntax
int ns_set_ip_address (char* ip_char);
Return Value
This API returns 0 or -1 in case if success or failure respectively.
Example
int setip = ns_set_ip_address(ip_char); printf(“%d”,setip);
ns_set_ua_string
Description
This API is used to set the user agent value.
Syntax
void ns_set_ua_string (char *ua_static_ptr);
Return Value
None
Example
Char* ua_static_ptr; ua_static_ptr = …; ns_set_ua_string(ua_static_ptr);
ns_set_cookies_disallowed
Description
This API sets the cookie allowed or not flag. Val = 1 means cookies are disallowed.
Syntax
void ns_set_cookies_disallowed (int val)
Return Value
None
Example
int val = 1; ns_set_cookies_disallowed(val);
do_shmget
Description
This API is used to create the shared memory.
Syntax
void * do_shmget(int size, char *msg);
Return Value
This API returns the shared memory start address which can be type casted to any other type.
ns_get_area_ip_char
Description
This API takes integer area_id ID argument and returns IP in AAA.BBBB.CCCC.DDDD notation.
Syntax
char *ns_get_area_ip_char(unsigned int area_id)
Return Value
This API returns IP as string.
Example
char* ipAdd = ns_get_area_ip_char(areaid); printf(“%d”,ipAdd);
ns_get_area_ip
Description
This API takes integer area_id ID argument and returns IP in integer format.
Syntax
unsigned int ns_get_area_ip(unsigned int area_id)
Return Value
This API returns IP address as string.
Example
unsigned int ipAdd = ns_get_area_ip(unsigned int area_id) printf(“ipAdd”);
ns_web_add_auto_header
Description: This API is used to add a HTTP header in all subsequent requests.
Syntax: int ns_web_add_auto_header(char header, char content, int flag);
There are three modes/flags for the same.
0 – To send only in Main URLs
1 – To send only in embedded URLs
2 – To send in both Main and Embedded.
Example: ns_web_add_auto_header(“Customer-Id”, “abc1234”, 0);
URL pre/post Helper Functions
Below are the URL pre/post helper functions:
ns_url_get_body_size
Description
This API is used to get the size of the body.
Syntax
int ns_url_get_body_size();
Return Value
This API returns size of the body or -1 on error.
Example
int body_size = 0; body_size = ns_url_get_body_size(); printf(“%d”, body_size);
ns_url_get_resp_size
Description
This API is used to get the size of the response [bytes of body received or bytes of chunks].
Syntax
int ns_url_get_resp_size()
Return Value
This API returns the size of the response or -1 on error.
Example
int resp_size = 0; resp_size = ns_url_get_resp_size(); printf(“%d”, resp_size);
ns_url_get_http_status_code
We cannot use (“ns_url_get_http_status_code“) this ns api directly because of its functionality. We need to create a function to define this api and after that need to call that function using “URLCALLBACK” in ns_web_url .
We are having two options to call the function.
1.PREURLCALLBACK: To call the function before the execution of any page.
2.POSTURLCALLBACK:To call the function after the execution of any page.
Example #include <stdio.h> #include <stdlib.h> #include <string.h> #include "ns_string.h" void func() { int status_code; status_code = ns_url_get_http_status_code(); printf("The Status Code is %d",status_code); } void ASD_CUST_V2_VerificationSearchACT() { ns_start_transaction("ASD_CUST_V2_VerificatioSearchKCACN"); ns_web_url("ASD_CUST_V2_VerificationSearchAliasCallType", "URL=https://ms-qa-2.tst.cavisson.com:443/dep/api/v2/customer/verificationSearch?alias={pAlias}&callType={pcallType}", "METHOD=POST", "HEADER=content-type:application/json", "HEADER=Authorization:DEP1-HMAC-SHA256 QCoE:M0WHOPN+ixOgGdtTsX3ZQ3R3B4ljNhA+mHSoDcQP0JQ=", "HEADER=X-DEP-REQUEST-ID:1111122222", "POSTURLCALLBACK=func", "HEADER=X-DEP-Date:{XDEPDate}", "HEADER=x-dep-from-system-code:MBL", "HEADER=x-dep-from-app:API", BODY_BEGIN, "{"value": "NizVBf8813" }", BODY_END ); ns_end_transaction("ASD_CUST_V2_VerificatioSearchKCACN", NS_AUTO_STATUS); ns_page_think_time(0); In this we have declared a function (func) and we are calling this using POSTURLCALLBACK. We have executed one test TR10890. Below is the TestrunOutput where we can see the status code.
ns_url_get_body_msg
Description
This API is used to get the message inside the body of the URL response.
Syntax
char *ns_url_get_body_msg(int *size)
Return Value
This API returns the body string.
Example
char* body_msg; int size = …; body_msg = ns_url_get_body_msg(size); printf(“%s”,body_msg);
ns_url_get_resp_msg
Description
This API is used to get the response of the URL.
Syntax
char *ns_url_get_resp_msg(int *size);
Return Value
Returns the response string or NULL on error.
Example
char* body_msg; int size = …; body_msg = ns_url_get_body_msg(size); printf(“%s”,body_msg);
Encoding and Decoding the Value of a Variable
Below are the APIs for encoding and decoding the value of a variable:
ns_encode_url
Description
This API is used to escape URL strings (converts all letters consider illegal in URLs to their %XX versions).
Syntax
char *ns_encode_url(const char *string, int inlength);
Return Value
This function returns a new allocated string or NULL if an error occurred.
Example
char* encodedUrl ; char* urlStr = ….; int len = ….; encodedUrl = ns_encode_url(urlStr, len); printf(“%s”,encodedUrl);
ns_decode_url
Description
This API is used to un-escape URL encoding in strings (converts all %XX codes to their 8bit versions).
Syntax
char *ns_decode_url(const char *string, int length);
Return Value
This function returns a new allocated string or NULL if an error occurs.
Example
char* decodedUrl ; char* str = ..; int len = …; decodedUrl = ns_decode_url(str, len); printf(“%s”,decodedUrl);
ns_encode_decode_url_free
Description
This API is used for de-allocation in the same translation unit that did the allocation.
Syntax
void ns_encode_decode_url_free(char *ptr);
Return Value
None
ns_encode_html
Description
This API is used to convert given text into html format.
Syntax
char *ns_encode_html(input_string, input_string_length, output_buffer)
- input_string : Indicates input string
- input_string_length: Indicates length of input string (if known), If length is not known, provide 0.
- output_buffer: Indicates output buffer (Note: output buffer size should be sufficient large), if user is not sure for output buffer size, then pass NULL.
Return Value
This function returns a new allocated string if output_buffer is declared or NULL if an error occurred.
Example
char* encodedHtml ; char* inputStr = ….; int len = ….; char output_buff[sufficient size] ; encodedHtml = ns_encode_html(inputStr, len, output_buff); possible values: len = len (if known) or 0 output_buff = output_buffer(if declare) or NULL printf(“%s”, encodedHtml); Ex: Plain text data: <03/01/1987> After conversion into Html encoded data: <03/01/1987>
ns_decode_html
Description
This API is used to convert given encoded html string into plain text.
Syntax
char *ns_encode_html(input_string, input_string_length, output_buffer)
- input_string : Indicates input string
- input_string_length: Length of input string (if known), If length is not known then provide 0.
- output_buffer: Indicates output buffer (Note: output buffer size should be sufficient large), if user is not sure for output buffer size, then pass NULL.
Return Value
This function returns a new allocated string if output_buffer is declared or NULL if an error occurred.
Example
char* decodedHtml ; char* inputStr = ….; int len = ….; char output_buff[sufficient size] ; decodedHtml = ns_encode_html(inputStr, len, output_buff); possible values: len = len (if known) or 0 output_buff = output_buffer(if declare) or NULL printf(“%s”, decodedHtml); Ex: html-encoded data: <03/01/1987> After conversion: <03/01/1987>
ns_encode_base64
Description
This API is used to convert given text into base64 format.
Syntax
char *ns_encode_base64(input_string, input_string_length, output_buffer)
- Here input_string : Indicates input string
- input_string_length: Length of input string (if known), If length is not known then provide 0.
- output_buffer: Indicates output buffer (Note: output buffer size should be sufficient large), if user is not sure for output buffer size, then pass NULL.
Return Value
This function returns a new allocated string if output_buffer is declared or NULL if an error occurred.
Example
char* encodedBase64 ; char* inputStr = ….; int len = ….; char output_buff[sufficient size] ; encodedHtml = ns_encode_base64(inputStr, len, output_buff); possible values: len = len (if known) or 0 output_buff = output_buffer(if declare) or NULL printf(“%s”, encodedBase64); Ex: Plain text data : <03/01/1987> After conversion: ICAmbHQ7MDMvMDEvMTk4NyZndDsgIA==
ns_decode_base64
Description
This API is used to convert given encoded base64 string into plain text.
Syntax
char *ns_decode_base64(input_string, input_string_length, output_buffer)
- Here input_string: Indicates input string
- input_string_length: Length of input string (if known), If length is not known then provide 0.
- output_buffer: Indicates output buffer (Note: output buffer size should be sufficient large), if user is not sure for output buffer size then pass NULL.
Return Value
This function returns a new allocated string if output_buffer is declared or NULL if an error occurred.
Example
char* decodedBase64 ; char* inputStr = ….; int len = ….; char output_buff[sufficient size] ; decodedHtml = ns_decoded_base64(inputStr, len, output_buff); possible values: len = len (if known) or 0 output_buff = output_buffer(if declare) or NULL printf(“%s”, decodedBase64); Ex: Plain base64 encoded data: CAmbHQ7MDMvMDEvMTk4NyZndDsgIA== After conversion: <03/01/1987>
ns_encode_eval_string
Description
This API is used to encode the present available value of the variable.
Syntax
char *ns_encode_eval_string(char *string);
Return Value
This API returns the encoded value of the variable.
Example
char* decodedUrl ; char* str = …; decodedUrl = ns_decode_url(str); printf(“%s”,decodedUrl);
ns_encode_specific_eval_string
Description
This API is used to encode the specific characters of the variable. In case, no specific characters are given, it calls “ns_encode_eval_string” which encode all the special characters.
Syntax
char *ns_encode_specific_eval_string (char *string, int encode_flag_specific , char* specific_chars, char* EncodeSpaceBy);
Return Value
This API returns the encoded value of the specific characters of the variable and rest characters are returned as they were.
Example
ns_save_string("#gh''st.+john 's+bay&cmcatId=cat1004020008&deptId=dept20000019'&categoryId=cat1004020008&id=cat1004020008&subcatId=''****", "s2"); printf("Value of s2 = %s\n", ns_encode_specific_eval_string("{s2}",1 , "* " , "+"));
Output:
Value of s2 = #gh''st.+john++++'s+bay&cmcatId=cat1004020008&deptId=dept20000019'&categoryId=cat1004020008&id=cat1004020008&subcatId=''%2A%2A%2A%2A
ns_encode_save_string
Description
This API is used to encode param_value and then save this encoded value to NS variable param_name.
Syntax
int ns_encode_save_string(const char* param_value, const char* param_name);
Return Value
This API returns 0 in case of success and -1 in case of failure.
Example
int encode_save; encode_save = ns_encode_save_string(null, param); printf(“%d”, encode_save);
ns_add_user_data_point
Description
This API is used to set graph data value of user monitor.
Syntax
int ns_add_user_data_point(int rptGroupID, int rptGraphID, double value);
Where
- int rptGroupID, group id: Group ID which we have taken in scenario with USER_MONITOR GDF
- int rptGraphID, graph id is also from GDF
- Value is what we have to add for user monitor
Return Value
Returns 0 in case of success and -1 in case of failure.
Example
int val; int rptGroupID; int rptGraphID; double value; val = ns_add_user_data_point( rptGroupID, rptGraphID, value); Printf(“%d”,val);
ns_set_pg_think_time
Description
This API is used to set the page think time.
Syntax
int ns_set_pg_think_time(int pg_think)
Example
int pg_think = 20; int time = ns_set_pg_think_time(pg_think); printf(“%d”,time);
ns_add_cookie_val_ex
Description
This API is used to add the cookie value.
Syntax
int ns_add_cookie_ex (char *cookie_name, char *domain, char *path, char *cookie_val)
Where
- Cookie_name: Cookie Name
- Domain: Get Cookie of this domain. NULL if domain is not to be checked
- Path: Get Cookie of this path. NULL if path is not to be checked
- cookie_val: Value of the cookie
Return Value
Pointer to 0 is successful or -1 if cookie name is not found.
Note: In case where Domain Name and Path Name are NULL, select the For all Domain and For all Path check box.
ns_advance_param
Description
This API advances to the next available value in the parameter data file. Next value is based on the MODE of the parameter.
Syntax
int ns_advance_param(const char *param_name);
param_name: Name of the parameter in double quotes or a C variable containing the name of the parameter. Name should be without curly brackets.
Return Value
This function returns 0 on success and -1 on failure. Parameter name is not a file parameter.
Example
ns_advance_param(“Param1”);
where Param1 is a parameter.
ns_paramarr_idx
Description
This API returns a string containing the value of the parameter at the specified position in a parameter array. If the parameter does not exist, then return value is the concatenation of “{“, paramArrayName, “_”, index and “}”
Syntax
char * ns_paramarr_idx(const char * paramArrayName, unsigned int index);
Arguments: Parameter array and index value.
Return Value
On success: Return a string buffer containing the value. On failure: Return NULL.
Example
“{myParam_4}”
ns_paramarr_len
Description
This API gets the number of elements in parameter array.
Syntax
int ns_paramarr_len(const char * paramArrayName);
Return Value
On success: Returns the number of elements in parameter array. On failure: return -1
ns_paramarr_random
Description
This API returns a string containing the value of the parameter in a parameter array. The value is returned from the parameter at a position chosen randomly by NetStorm.
If the parameter does not exist, then return value is the concatenation of “{“, paramArrayName, “_”, index and “}”
Example “{myParam_4}”
Syntax
char * ns_paramarr_random(const char * paramArrayName);
Arguments: Param array
Return Value
On success: Return a string buffer containing the value. On failure: Return NULL.
ns_check_reply_size
Description
This API is used to compare the response size with value1 and value2.
Arguments:
- mode: This indicates the mode value. Currently NotBetweenMinMax mode is supported only.
- value1: This indicates the user defined value1 that is used to compare with response size.
- value2: This indicates the user defined value2 that is used to compare with response size.
Returns value:
- 0 : on success if the response size is as per mode.
- 1 : if response/reply size is small.
- 2 : if response/reply size is big.
- -1 : on error
Example
int replySize = ns_check_reply_size(mode,value1,value2);
ns_get_session_status_name
Description
This API is used to get session status string name.
Syntax
ns_get_session_status_name(int status);
Return Value
This API returns char string that gives the session status, in case of failure returns Invalid error.
ns_get_status_name
Description
This API takes status as argument and returns Return URL, Page and Tx status as a string.
Syntax
ns_get_status_name(int status);
Return Value
This API returns char string.
ns_set_embd_objects
Description
This API is used to set embedded objects. It takes first argument as number of embedded URLs & second one is list of embedded URLs to set in a page.
Syntax
ns_set_embd_objects();
Example
ns_set_embd_objects(numeurls,eurls);
ns_aes_decrypt
Description: This API is used to decrypt any input, which supports AES decryption algorithm.
Syntax: ns_aes_decrypt();
ns_aes_encrypt
Description: This API is used to decrypt any input, which supports AES encryption algorithm.
Syntax: ns_aes_encrypt();
Transaction APIs
Below are the transaction APIs:
ns_start_transaction
Description
This API acts as a marker to define the start of a transaction. Transaction timing measurement would start at the start of accessing the next page.
Syntax
int ns_start_transaction(char* tx_name);
Argument
tx_name is any string and specifies the name of the transaction being started.
Return Value
This API returns 0 on success and -1 on failure.
ns_end_transaction
Description
This API acts as a marker to define the end of a transaction.
Syntax
int ns_end_transaction_ex(char* tx_name, int status);
Argument
tx_name is any string and specifies the name of the transaction being ended. A transaction by the specified transaction name should have been successfully started earlier, for this function to succeed. Status is the transaction status. Possible values of status can be 0-15. 0 specifies success and -1 specifies failure. Status codes 1-15 are other user defined transaction failures status codes.
Return Value
This API returns 0 on success and –1 on failure.
ns_end_transaction_as
Description
This API acts as a marker to define the end of a specified transaction name. [end_name].
Syntax
int ns_end_transaction_as(char* tx_name, int status, char *end_name)
Argument
tx_name is any string and specifies the name of the transaction being ended. A transaction by the specified transaction name should have been successfully started earlier, for this function to succeed. Status is the transaction status. Possible values of status can be 0-15. 0 specifies success and -1 specifies failure. Status codes 1-15 are other user defined transaction failures status codes.
end_name: Transaction name.
Return Value
This API returns 0 on success and -1 on failure.
SOAP WebServiceSecurity API
Below are the SOAP WebServiceSecurity APIs:
Purpose
SOAP WS Security API is used to add the Web Service (WS) security header in SOAP XML. WS security header contains security certificate, signedInfo token which have digest value of soap body part or full body and signature of signedInfo token.
We have implemented three APIs in NS for supporting soap WS security
- ns_soap_ws_security
- ns_enable_soap_ws_security
- ns_disable_soap_ws_security
ns_soap_ws_security
This API is used for adding soap security information in NS. It is used by NS while sending the soap request.
It takes 9 arguments:
- Keyfile
- Certificate file
- Algorithm
- token
- digest id
- certificate id
- sign id
- key info id
- sec token id
ns_enable_soap_ws_security / ns_disable_soap_ws_security
If soap WS security is already applied using “ns_soap_ws_security” API, the status is enabled. Thus, the WS security is applied on each outgoing SOAP request. To disable this WS security after particular request, use “ns_disable_soap_ws_security”. It is disabled for the rest of the session until it is enabled using “ns_enable_soap_ws_security”
Example
ns_soap_ws_security(....); ns_web_url (page1, ….); ns_disable_soap_ws_security(); ns_web_url (page2, ….); ns_enable_soap_ws_security(); ns_web_url (page3, ….);
In the above configuration, the SOAP WS security header is added on page1 soap xml. Then, the SOAP WS security header gets disabled, so it is not added on page2 soap xml. Further, we enable the SOAP WS security header so the header is added on page3 soap xml.
Syntax
int ns_soap_ws_security(char *keyFile, char *certFile, int algorithm, char *token, char *digest_id, char *cert_id, char *sign_id, char *key_info_id, char* sec_token_id );
Where,
keyFile – is used to provide absolute path for key file
certFile – is used to provide absolute path for certificate file
algorithm – is used for specifying algorithm. Currently SHA1 is supported.
Default values for the following are:-
- algorithm – DIGEST_SHA1
- token – “body”
- digest_id – “id-1”
- cert_id – “X509-CertificateId-1”
- sign_id – “SIG-SignatureId-1”
- key_info_id – “KI-KeyInfoId-1”
- sec_token_id – “STR-SecurityTokenId-1”
List attributes (mandatory & optional)
All arguments are mandatory to be provided. Key File, Certificate File and Algorithm cannot be set NULL. Rest 6 arguments can be set to NULL and the API then uses default values for these fields.
Example
ns_soap_ws_security("/home/netstorm/work/scripts/HTTP2/HTTP2/test/privKey.pem", "/home/netstorm/work/scripts/HTTP2/HTTP2/test/publicCert.pem", 1, NULL, NULL, NULL, NULL, NULL, NULL); ns_enable_soap_ws_security(); ns_disable_soap_ws_security();
NS Database APIs
ns_db_odbc_init()
Description | This API initializes the ODBC library. Internally it allocates environment handle, sets ODBC version to 3, and allocates a connection handle |
Inputs | None |
Returns | 0 on Success, -1 on error |
ns_db_connect()
Description | This API makes a connection to the destination database using the connection string passed as argument | |
Inputs | char *conn_str | This is the connection string that is used to connect the Database Source using ODBC |
Returns | 0 on Success, -1 on error | |
Example | if (ns_db_connect(“DSN=PostgreSQL; Username=netstorm; Database=test”) == -1) { handle_error(); } |
ns_db_alloc_stmt_handle()
Description | This API allocates a handle for executing an SQL statement. This API must be called before making a call to ns_db_execute() | |
Arguments | The API fills the address statement handle in this argument | |
Returns | 0 on Success, -1 on error | |
Example | void *stmt = NULL; if (ns_db_alloc_stmt_handle(&stmt) == -1) { handle_error(); } |
ns_db_execute_direct()
Description | This API is used to execute an SQL statement. Please note that ns_db_odbc_init(), ns_db_connect() and ns_db_alloc_stmt_handle() API’s must be called in this sequence before calling this API | |
Arguments | void *in_stmt | Statement handle returned by ns_db_alloc_stmt_handle() |
| char *qstr | SQL statement to be executed |
Returns | 0 on Success, -1 on error | |
Example | if(ns_db_execute_direct(stmt, “update products set quantity = 4 where name = bedsheet’;”) == -1) { handle_error(); } |
ns_db_get_value()
Description | This API is used to retrieve the output of the last SQL command executed using nd_db_execute() API. | |
Arguments | void *in_stmt | Statement handle returned by ns_db_alloc_stmt_handle() |
| char *retbuf | The output of the query is saved in this buffer. The user can supply the memory for this buffer. In that case, the 3rd argument should be the size of buffer. In case the 3rd argument is zero, a static buffer is populated by the API, which should be copied by the user of this API |
| int retbuflen | Length of the buffer if the memory is allocated by the caller. If 0, the return string will be written to a static buffer, which the caller must copy |
Returns | 0 on Success, -1 on error | |
Example | char buf[2048]; … … if(ns_db_get_value(stmt, buf, 2048) == -1) { handle_error(); } printf(“Query result: %s\n”, buf); |
ns_db_free_stmt()
Description | This API is used to free the statement handle allocated using ns_db_alloc_stmt_handle() API. | |
Arguments | void *stmt | Statement handle returned by ns_db_alloc_stmt_handle() |
Returns | 0 on Success, -1 on error | |
Example | if(ns_db_free_stmt(stmt) == -1) { handle_error(); } |
ns_db_odbc_close()
Description | This API is used to free the environment handle and database connection handle, which are allocated internally at the time of ns_db_odbc_init() API |
Arguments | None |
Returns | 0 on Success, -1 on error |
Example | if(ns_db_odbc_close() == -1) { handle_error(); } |
ns_db_prepare()
Description | This API is used to prepare a SQL statement. Please note that ns_db_odbc_init(), ns_db_connect() and ns_db_alloc_stmt_handle() API’s must be called in this sequence before calling this API. | |
Arguments | void *stmt | Statement handle returned by ns_db_alloc_stmt_handle() |
| char *qstr | This will prepare an SQL string for execution |
Returns | 0 on Success, -1 on error | |
Example | ns_db_prepare(stmt, *qstr); if(ns_db_prepare(stmt, “update products set quantity = 4 where name = ?;”) == -1) { handle_error(); } |
ns_db_bindparameter()
Description | This API is binds a buffer to a parameter marker in an SQL statement. Please note that ns_db_odbc_init(), ns_db_connect(), ns_db_alloc_stmt_handle() and ns_db_prepare() API’s must be called in this sequence before calling this API. | |
Arguments | ns_db_bindparameter(stmt, p_no, io_type, v_type, p_type, col_size, d_digit, p_value_ptr, buf_len, strlen_indptr) | |
void *in_stmt | [Input] Statement handle | |
unsigned short p_no | [Input] Parameter number, ordered sequentially in increasing parameter order, starting at 1 | |
signed short int io_type | [Input] The type of the parameter | |
signed short int v_type | [Input] The C data type of the parameter | |
signed short int p_type | [Input] The SQL data type of the parameter | |
unsigned long col_size | [Input] The size of the column or expression of the corresponding parameter marker | |
signed short int d_digit | [Input] The decimal digits of the column or expression of the corresponding parameter marker | |
void *p_value_ptr | [Deferred Input] A pointer to a buffer for the parameter’s data | |
long buf_len | [Input/Output] Length of the p_value_ptr buffer in bytes. | |
long *strlen_indptr | [Deferred Input] A pointer to a buffer for the parameter’s length | |
Returns | 0 on Success, -1 on error | |
Example | If(ns_db_bindprepare(in_stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, 10, 0, department, 0, &plength) == -1) { handle_error(); } |
ns_db_execute()
Description | This API is used to execute the SQL statement which has been prepared by ns_db_prepare() and ns_db_bindparameter(). Through this api, the SQL statement will be compiled only once and can be executed repeatedly hence minimizing the execution time required by the same-looking queries. Please note that ns_db_odbc_init(), ns_db_connect(), ns_db_alloc_stmt_handle(), ns_db_prepare() and ns_db_bindparameter() API’s must be called in this sequence before calling this API | |
Arguments | void *in_stmt | Statement handle returned by ns_db_alloc_stmt_handle() |
Returns | 0 on Success, -1 on error | |
Example | ns_db_execute_ex(stmt); if(ns_db_execute_ex(stmt == -1) { handle_error(); } |
Sample Flow Files
db_select_flow.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ns_string.h"
extern int db_log_result(char *, char *);
void db_select_flow()
{
char buf[2048];
void *stmt = NULL;
char tablename[30], qstr[256];
sprintf(tablename, "products_%04d%06d", ns_get_nvmid(), ns_get_userid());
// Initialize db environement and variables
if(ns_db_odbc_init() == -1)
{
ns_db_odbc_close();
return;
}
ns_start_transaction("Connect_db_for_select");
// Connect to database with DSN PostgresSQL, username netstorm and password test123
if(ns_db_connect("DSN=PostgreSQL; Username=netstorm; Datbase=test") == -1)
{
ns_set_tx_status("Connect_db_for_select", 70);
ns_db_odbc_close();
return;
}
ns_end_transaction("Connect_db_for_select", NS_AUTO_STATUS);
// Allocate statement handle.
if(ns_db_alloc_stmt_handle(&stmt) == -1)
{
ns_db_odbc_close();
return;
}
ns_start_transaction("Run_select");
sprintf(qstr, "select * from %s;", tablename);
// Executing select query
if(ns_db_execute(stmt, qstr) == -1)
{
ns_set_tx_status("Run_select", NS_TX_ERROR);
fprintf(stderr, "Error in executing query: [%s]\n", qstr);
}
ns_end_transaction("Run_select", NS_AUTO_STATUS);
ns_page_think_time(1);
if(ns_db_get_value(stmt, buf, 2048) == -1)
fprintf(stderr, "Error in executing query: [%s]\n", qstr);
printf("\n======\nBuffer = %s\n======\n", buf);
db_log_result("select", buf);
ns_db_free_stmt(stmt);
ns_db_odbc_close();
}
db_create_flow.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ns_string.h"
void db_create_flow()
{
void *stmt = NULL;
char tablename[30], qstr[256];
sprintf(tablename, "products_%04d%06d", ns_get_nvmid(), ns_get_userid());
// Initialize db environement and variables
if(ns_db_odbc_init() == -1)
{
ns_db_odbc_close();
return;
}
ns_start_transaction("Connect_db_for_create");
// Connect to database with DSN PostgresSQL, username netstorm and Database test
if(ns_db_connect("DSN=PostgreSQL; Username=netstorm; Database=test") == -1)
{
ns_set_tx_status("Connect_db_for_create", 70);
ns_db_odbc_close();
return;
}
ns_end_transaction("Connect_db_for_create", NS_AUTO_STATUS);
// Allocate statement handle.
if(ns_db_alloc_stmt_handle(&stmt) == -1)
{
ns_db_odbc_close();
return;
}
ns_start_transaction("Run_create");
// Executing drop table command
sprintf(qstr, "drop table %s;", tablename);
if(ns_db_execute(stmt, qstr) == -1){
ns_set_tx_status("Run_create", NS_TX_ERROR);
fprintf(stderr, "Error in executing query: [%s]\n", qstr);
}
// Executing create table command
sprintf(qstr, "create table %s (name varchar(20), category varchar(20), quantity int, unitprice int);", tablename);
if(ns_db_execute(stmt, qstr) == -1){
ns_set_tx_status("Run_create", NS_TX_ERROR);
fprintf(stderr, "Error in executing query: [%s]\n", qstr);
}
ns_end_transaction("Run_create", NS_AUTO_STATUS);
ns_page_think_time(1);
ns_db_free_stmt(stmt);
ns_db_odbc_close();
}
db_update_flow.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ns_string.h"
void db_update_flow()
{
void *stmt = NULL;
char tablename[30], qstr[256];
sprintf(tablename, "products_%04d%06d", ns_get_nvmid(), ns_get_userid());
// Initialize db environement and variables
if(ns_db_odbc_init() == -1)
{
ns_db_odbc_close();
return;
}
ns_start_transaction("Connect_db_for_update");
// Connect to database with DSN PostgresSQL, username netstorm and password test123
if(ns_db_connect("DSN=PostgreSQL; Username=netstorm; Datbase=test") == -1)
{
ns_set_tx_status("Connect_db_for_update", 70);
ns_db_odbc_close();
return;
}
ns_end_transaction("Connect_db_for_update", NS_AUTO_STATUS);
// Allocate statement handle.
if(ns_db_alloc_stmt_handle(&stmt) == -1)
{
ns_db_odbc_close();
return;
}
ns_start_transaction("Run_update");
// Executing select query
sprintf(qstr, "update %s set quantity = 4 where name = 'bedsheet';", tablename);
if(ns_db_execute(stmt, qstr) == -1){
ns_set_tx_status("Run_update", NS_TX_ERROR);
fprintf(stderr, "Error in executing query: [%s]\n", qstr);
}
ns_end_transaction("Run_update", NS_AUTO_STATUS);
ns_page_think_time(1);
ns_db_free_stmt(stmt);
ns_db_odbc_close();
db_insert_flow.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ns_string.h"
void db_insert_flow()
{
void *stmt = NULL;
char tablename[30], qstr[256];
sprintf(tablename, "products_%04d%06d", ns_get_nvmid(), ns_get_userid());
// Initialize db environement and variables
if(ns_db_odbc_init() == -1)
{
ns_db_odbc_close();
return;
}
ns_start_transaction("Connect_db_for_insert");
// Connect to database with DSN PostgresSQL, username netstorm and password test123
if(ns_db_connect("DSN=PostgreSQL; Username=netstorm; Datbase=test") == -1)
{
ns_set_tx_status("Connect_db_for_insert", 70);
ns_db_odbc_close();
return;
}
ns_end_transaction("Connect_db_for_insert", NS_AUTO_STATUS);
// Allocate statement handle.
if(ns_db_alloc_stmt_handle(&stmt) == -1)
{
ns_db_odbc_close();
return;
}
ns_start_transaction("Run_insert");
// Executing select query
sprintf(qstr, "insert into %s values ('bedsheet', 'home', 2, 30);", tablename);
if(ns_db_execute(stmt, qstr) == -1){
ns_set_tx_status("Run_insert", NS_TX_ERROR);
fprintf(stderr, "Error in executing query: [%s]\n", qstr);
}
ns_end_transaction("Run_insert", NS_AUTO_STATUS);
ns_page_think_time(1);
ns_db_free_stmt(stmt);
ns_db_odbc_close();
}
db_log_result.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ns_string.h"
int db_log_result(char *operation, char *buf)
{
static char first_time = 1;
char db_result_filename[64];
sprintf(db_result_filename, "%s/logs/TR%d/db_result.csv", getenv("NS_WDIR"), ns_get_testid());
if(first_time)
{
ns_save_data_ex(db_result_filename, 1, "nvmid-userid,sessid,operation,productname,productcategory,quantityinstock,unitprice");
first_time = 0;
}
ns_save_data_ex(db_result_filename, 1, "UserId:%d-%d,SessionId:%d,Operation:%s\n%s\n",
ns_get_nvmid(), ns_get_userid(), ns_get_sessid(), operation, buf);
return 0;
}
Other APIs
ns_get_random_str()
Syntax: char* ns_get_random_str (int min, int max, char *format);
Descriptions: This API is used to generate random string of specified length and format.
Example:
char *ran_string;
ran_string = ns_get_random_str(4, 6, “a-c”); // abcb, abab, abcbac, etc
printf(“\n ##### Value of ran_string is [%s]\n”, ran_string);
// It will generate random strings of length 4 to 6 bytes including characters ‘a’, ‘b’ & ‘c’.
ns_page_think_time()
Syntax: int ns_page_think_time(double page_think_time);
Descriptions: This API is used to apply page think time between two web pages, two APIs & two actions.
Example:
ns_page_think_time(3.0);
// Vusers will go in thinking state for 3 seconds.
ns_save_data_ex()
Syntax: int ns_save_data_ex(char *file_name, int mode, char *format, …);
Descriptions: This API Is used to save data as per given format in the file. New line will be added by the API. Maximum data value can be 5 KB. If more than 5 KB, data is truncated.
Arguments: ·
- file_name: File name where data is stored. File name can be relative path or absolute path. If relative path, the file will be created in Test Run directory. File path is created if not existing.·
- Mode: Mode of opening data file. It has two values:
- NS_TRUNC_FILE (0): Truncate if file is present – Truncate file to zero length or create file for writing.
- NS_APPEND_FILE (1): Append if file is present – Open for appending (writing at end of file). The file is created if it does not exist.·
- format: Format is like format used in fprintf(). No NetStorm variable can be used in the format.
Return: This API always returns 0.
Examples:
int ret; static int iteration = 0; // This will save iteration message in the file in the append mode iteration++; ret = ns_save_data_ex(“/home/cavisson/work/data/messages.dat”, NS_APPEND_FILE, “Iteration number %d passed”, iteration);
ns_save_data_var()
Syntax: int ns_save_data_var(char *file_name, int mode, char *var_name);
Descriptions: This API is used to save variable value in file in APPEND & TRUNCATE modes.
Arguments:·
- file_name: File name where data is stored. File name can be relative path or absolute path. If relative path, the file will be created in Test Run directory. File path is created if not existing.·
- Mode: Mode of opening data file. It has two values:
- NS_TRUNC_FILE (0): Truncate if file is present – Truncate file to zero length or create file for writing.
- NS_APPEND_FILE (1): Append if file is present – Open for appending (writing at end of file). The file is created if it does not exist.·
- var_name: Variable name.
Example:
char *token=ns_eval_string(“{TokenId}”);ns_save_data_var(“/home/cavisson/work/tokens.txt”, 1, token);//It will write all token IDs in file tokens.txt
ns_cassdb_connect()
Syntax: int ns_cassdb_connect(char host, int port, char user, char *pass)
Description: This API is responsible for making connection to CassandraDB server. Here no actual connection is made, it just store all the input into cassdb object and hence no packet can be captured during this.
Input Args:
host:
- — To provide cassdb server ip/hostname.
- — If IP/hostname is not provided (i.e NULL) then ‘localhost’ is taken as cassdb server IP.
- — IP must be in the formate ‘xxx.xxx.xxx.xxx’ eg: 10.10.70.xx
- — It can be parameterized.
Port:
- — To provide cassdb server Port.
- — If Port is not provided (I.e < 0) then ‘9042’ is taken as cassdb server Port.
- — Post must be valid number.
- — It can be parameterized.
user:
- — To provide cassandra user name on which database is setup.
- — If user name is invalid then it will not create connection.
- — User must be valid.
- — It can be parameterize.
Password:
- — To provide cassandra password for given user name.
- — It can be parameterize.
- — Password must be valid.
Return Value:0 on success, 1 on failure
Example:ns_cassdb_connect(“www.dbserver.com”, 9042, “user”, “user123”);
ns_cassdb_disconnect()
Syntax: void ns_cassdb_disconnect()
Description: This API is used to disconnect running connection.
Input Args: No input is required.
Example: ns_cassdb_disconnect();
ns_cassdb_get_val()
Syntax: char *ns_cassdb_get_val()
Description: This API shows query result. API malloc memory for query result and return base address.
Input Args: No input is required.
Example:
ns_cassdb_connect(“www.dbserver.com”, 9042 ,”cassandra”,”cassandra”);ns_cassdb_execute_query(“select * from employee;”)char *buff;buff = ns_cassdb_get_val();printf(“***********output of ns_cassdb_get_val after executing query= %s\n”,buff);
ns_set_ssl_settings()
Syntax: int ns_set_ssl_settings(char *cert_file, char *key_file);
Description: To send SSL Certificate upon receiving client certificate request from server.
Input Arguments:
- cert_file – To provide certificate file name.
- key_file – To provide key file name.Note: certificate file must be placed “/home/cavisson/work/cert” directory
Example:
ns_set_ssl_settings(“client_openssl1_1_1b.pem” , “client_key_openssl1_1_1b.pem”);ns_web_url (“ClientAuth”, “URL=https://www.authenticatedserver.com/Client_Authentication/index.html“, );
ns_unset_ssl_settings()
Syntax: int ns_unset_ssl_settings();
Descriptions: To unset ssl settings which are set if not required.
Example: ns_unset_ssl_settings();
ns_protobuf_encode()
Syntax: int ns_protobuf_encode(char xml_data, int is_file_or_buffer, char proto_fname, char msg_type, char enc_param)
Input Arguments:·
- xml_data – xml file name or xml data. It can be pass through NS parameter also.·
- is_file_or_buffer – flag to know whether xml_data field is xml file name or xml data : 1- xml file name, 0- xml data·
- proto_fname – proto file name to be encoded.·
- msg_type – message type of proto file·
- enc_param – NS parameter in which encoded data will be stored.
Description: This API is used to encode the proto file and give result in protobuf encoded format(binary)
Example:
int len = ns_protobuf_encode(“/home/cavisson/work_2/scripts/Protobuf/Protobuf/Protobuf_Script/Noida.xml”, 1, “/home/cavisson/work_2/scripts/Protobuf/Protobuf/Protobuf_Script/data_2.proto”, “Noida”, “dec_encode”); //For XML File name(mode 1) int len = ns_protobuf_encode(“Cavisson_encode” , 0, “/home/cavisson/work_2/scripts/Protobuf/Protobuf/Protobuf_Script/wire_type.proto”, “DataType”, “dec_encode_wire_type”);//For Buffer(xml data)(mode 0)
ns_protobuf_decode()
Syntax: ns_protobuf_decode(char encoded_data_param, int len, int input_format, char proto_fname, char msg_type, char decoded_param)
Input Arguments:·
- encoded_data_param – NS parameter or buffer containing encoded data· len – length of encoded data·
- input_type – defines encoded_data_param field is NS parameter, buffer or fileThis parameter can have 3 values:
- BUFFER – Encoded data is provided in buffero
- PARAM – Encoded data is provided as NS paramo
- FILE – Encoded data is provided in a file.·
- proto_fname – proto file name·
- msg_type – msg_type of proto·
- decoded_data – NS parameter to store decoded data
Description: This API is used to decode the encoded data which are encoded by protobuf.
Example:
ns_protobuf_decode(“/home/cavisson/work_2/scripts/Protobuf/Protobuf/Protobuf_Script/Noida.xml”, 3, 2, “/home/cavisson/work_2/scripts/Protobuf/Protobuf/Protobuf_Script/data_2.proto”, “Address”, “dec_decode”); //For Data filens_protobuf_decode(“^FAsmita^R^Corg^Z^RFeatherstoneStreet\”^FLONDON2^GEC1Y8SY:^BUK@^K”, 4, 0, “/home/cavisson/work_2/scripts/Protobuf/Protobuf/Protobuf_Script/data_2.proto”, “Address”, “dec_decode”);//For datans_protobuf_decode(“dec_encode”, 1, 1, “/home/cavisson/work_2/scripts/Protobuf/Protobuf/Protobuf_Script/data_2.proto”, “Address”, “dec_decode”);//For Buffer