Friday, 16 September 2016

LoadRunner - Selecting random value using lr_paramarr_random function


In performance testing, it is really important to simulate a realistic user path through an application. For example, randomly select an image link from a gallery or select a share from a share list. In such situations, you can use the LoadRunnerlr_paramarr_random function to select a random value from a captured parameter array. Similarly, you can also write a code to do the same.

Before you use the above function, you will need to use web_reg_save_paramfunction to capture all the ordinal values. This can be achieved by passing "ORD=ALL" into the function.

The following code demonstrates the use of lr_paramarr_random function. The code saves link Ids using  web_reg_save_param function and then useslr_paramarr_random function to randomly select an Id value. The value is passed as a parameter in web_text_link function to navigate to the appropriate webpage.

Action()
{

 //Capture all the Link IDs
 web_reg_save_param("LinkID","LB=id=\"","RB=\" href=\"default.aspx?content=business_","ORD=ALL",LAST);

 lr_start_transaction("VU01_01_Homepage");
 web_browser("website", 
  DESCRIPTION, 
  ACTION, 
  "Navigate={WebsiteUrl}", 
  LAST);

 lr_end_transaction("VU01_01_Homepage",LR_AUTO);

 lr_think_time(10);


 //Save a randomly selected ID to a Parameter
 lr_save_string(lr_paramarr_random("LinkID"),"RandomLink"); 

 //Printout the randomly selected parameter
 lr_output_message("%s",lr_eval_string("{RandomLink}"));

 //Navigate to the appropriate webpage associated to the ID
 lr_start_transaction("VU01_02_RandomLink");

 web_text_link("Links", 
  "Snapshot=t2.inf", 
  DESCRIPTION, 
  "Id={RandomLink}",
  ACTION, 
  "UserAction=Click", 
  LAST);

 lr_end_transaction("VU01_02_RandomLink",LR_AUTO);
 
 web_browser("Sync", 
  "Snapshot=t3.inf", 
  DESCRIPTION, 
  ACTION, 
  "Sync", 
  LAST);

 return 0;
}
Following is a screenshot of replay log, displaying the random id's selected for each iteration. It also displays the values captured using web_reg_save_param function. 

Wednesday, 14 September 2016

MQ scripting vugen code for pushing message in Queue


            //Message Injection loop
            for(i=0;i<injectionRate;i++)
            {

                if (numberOfMsgsInjected==totalMessages)
                                break;
                try
                {
                text.delete(0,text.length());
                //appending the xml message.
                text.append(lr.eval_string("<Items MessageType=\"ADJUSTMENT\"><Item AdjustmentType=\"ADJUSTMENT\" Availability=\"TRACK\" ItemID=\"[ItemID]\" OrganizationCode=\"DEFAULT\" ProductClass=\"GOOD\" Quantity=\"10\" RemoveInventoryNodeControl=\"Y\" ShipNode=\"[BrandID]\" SupplyType=\"ONHAND\" UnitOfMeasure=\"EACH\"></Item></Items>"));

                //Convert to String 
                String str = text.toString();
                System.out.println(str);
       
                //Creating Message Queue
                MQMessage XMLMessage = new MQMessage();

                //Setting Message format
                XMLMessage.format = "MQSTR";
                //UTF encoding Supports
                XMLMessage.writeString(str)
               
                System.out.println("string" + XMLMessage);                  
                  // specify the message options...
            
                  MQPutMessageOptions pmo = new MQPutMessageOptions();    // same as MQPMO_DEFAULT
            
                 // put the message on the queue
            
                  qName.put(XMLMessage,pmo);
                  numberOfMsgsInjected = numberOfMsgsInjected + 1;
                   lr.start_transaction("MessageSend");
                  System.out.println("msg sent ...");
                  lr.end_transaction("MessageSend",lr.PASS);
                               
                }

                catch(Exception e)
                {
                System.out.println("error here");
                e.printStackTrace();
                System.exit(0);
                }

            }

            //Getting the time stamp in millisecond after message injection.
            timeInMillis2 = System.currentTimeMillis();
           
        //Calculating the message injection rate
        double timespend = (double)(timeInMillis2 - timeInMillis1);
        double injectionIntervalMillisec = multiplyingFactor * injectionInterval * 1000;
        try
        {

            if(injectionIntervalMillisec > timespend)
            {
           
            Thread.sleep((long)(injectionIntervalMillisec-timespend));
            
            }
        }
            catch (Exception e)
            {}

        if (numberOfMsgsInjected==totalMessages)
         {

            lr.exit(lr.EXIT_VUSER,lr.PASS);
         }

    return 0;
    }//end of action

 /**
 * LoadRunner method to terminate the established  connection
 * with middleware.
 */

    public int end() throws Exception
    {
        // Close the queue...
        qName.close();

        // Disconnect from the queue manager 
        qMgr.disconnect();
        return 0;
    }//end of end

}

Friday, 9 September 2016

Validation check in web services protocol using lr_XML_get_values()

The function lr_xml_get_values executes queries on the string xml_input. The results of each query are stored in the parameter Result.

#include "as_web.h"

/* The XML Data */
char *xml_input=
"<acme_org>"
     " <accounts_dept>"
          "<employee>"
               " <name>Kevin Sharp</name>"
               "<cubicle>227</cubicle>"
               "<extension>2145</extension>"
          "</employee>"
     "</accounts_dept>"
     "<engineering_dept>"
          "<employee>"
               "<name>John Smith</name>"
               "<cubicle>372</cubicle>"
               "<extension>2970</extension>"
          "</employee>"
          "<employee level=\"manager\">"
               "<name>Sue Jones</name>"
               "<extension>2375</extension>"
          "</employee>"
     "</engineering_dept>"
"</acme_org>";

Action() {
    int query_number = 1;
// Save data as parameter
    lr_save_string(xml_input, "XML_Input_Param");
    /* Query 1: Find the first employee's name
        (To find the names of all employees
        see Multiple Query Matching)    */
    lr_xml_get_values("XML={XML_Input_Param}",
        "ValueParam=Result",
        "Query=/acme_org/*/employee/name",
        LAST );
    /* Query 2: Find the first extension number one
        or more levels deep */
    lr_xml_get_values("XML={XML_Input_Param}",
        "ValueParam=Result",
        "Query=//extension",
        LAST );
    /* Query 3: Find the name of the manager
        of the engineering department. */
    lr_xml_get_values("XML={XML_Input_Param}",
        "ValueParam=Result",
"Query=/acme_org/engineering_dept/employee[@level=\"manager\"]/name",
        LAST );
    /* Query 4: Find the name of an employee
    whose extension number is 2970 */
    lr_xml_get_values("XML={XML_Input_Param}",
        "ValueParam=Result",
        "Query=/acme_org/*/employee[extension=\"2970\"]/name",
        LAST );
    return 0;
}
Output from Execution Log Window:
Action.c(33): Saving Parameter "Result = Kevin Sharp"
Action.c(33): "lr_xml_get_values" was successful, 1 match processed
Action.c(37): Saving Parameter "Result = 2145"
Action.c(37): "lr_xml_get_values" was successful, 1 match processed
Action.c(41): Saving Parameter "Result = Sue Jones"
Action.c(41): "lr_xml_get_values" was successful, 1 match processed
Action.c(46): Saving Parameter "Result = John Smith"
Action.c(46): "lr_xml_get_values" was successful, 1 match processed

Saturday, 27 August 2016

IP spoofing in loadrunner vugen and performance center

IP of client machine's is identity used by Servers and Network devices like routers to recognize them and then to cache the information and optimize themselves.
Sometimes we need to use different IPs to emulate the real world scenarios to make servers and devices see as if users are coming from different sources.

But this task is not simple.

Our job here is to fool the devices and it requires three simple steps:

1. Run IP Wizard (Start > Program Files > LoadRunner > Tools > IP Wizard) on LG to add the IPs you want to emulate in scenario.

2. Update the server’s routing table with new IPs, this is done so that servers are able trace back to the client. If client and server are in same network and subnet mask then not need of modification is required.
To update the table edit the batch file in IP wizard summary use route command as below to update:
“route ADD [IPs you want to add] MASK 255.255.255.255 [Your_IP] METRIC1”
“route ADD [IPs you want to add] MASK 255.255.255.255 [Your_IP] METRIC2”
Now run this .bat file on server to update.

3. Enable IP Spoofing ( Scenario > Enable IP Spoofer ) from Controller, before connecting to LG.

Thursday, 11 August 2016

Replace function used Vugen scripts

char *strSource;

void Replace( char *strSource, char *strFrom, char *strTo, char *strParam)
{

   char strTemp[1024];

char *s= (char *)strSource;
int i=0;
int iLenFrom = strlen (strFrom);

int iLenTo = strlen(strTo);

while(*s)
{

if(strncmp (s,strFrom, iLenFrom) ==0)
{

strncpy(&(strTemp[i]), strTo, iLenTo);
i+=iLenTo;
s+ =iLenFrom;
}

else
{
  strTemp[i++] =*s;
s++;
}


}


strTemp[i] =0;
lr_save_string(strTemp,strParam);

}


//how  to call replace function

strSource= lr_eval_string("{c_ESS}");

lr_save_string(strSource,"c_ESS_New");

Replace(strSource,"&#x21", "!","c_ESS_New");





Tuesday, 5 July 2016

Server has shut down the connection prematurely

Server has shut down the connection prematurely

First thing "Server xyz has shut down the connection prematurely " is not a webserver issue.
This is purely loadrunner issue and is one of the major pain area.

Solutions:
1. Make sure we are not ramping up all user simultaneously
2. Rendez point are not holding up too many users.
3. Make sure retry option is greater than 5
4. Check network connectivity or blockage.
5. Decrease the load from loadrunner machine
6. Clear the Temp folder in (Documents and Settings-->user-->Local Settings)-->Temp
    and restart the machine on which loadrunner is installed (This one is my favorite, it has always helped me in getting rid from this error, but the condition is that scripts ran successfully before and now you suddenly start seeing this error)
7. If above solution also doesn't work then, Recently I observed that if we suddenly start seeing this issue, then best option is to restart all machines and servers in your network or load test domain (after following point No. 6) .

Put this in script, not a solution but just the workaround, you will not see error, but issue will still exist
web_set_sockets_option ("NEW_BEHAVIOR_OF_OVERLAPPED_SEND", "1");
If none of the above option helps then put web_set_sockets_option("IGNORE_PREMATURE_SHUTDOWN", "1");  in vuser_init()

You can also try following
Run time settings --> Preferences --> Use WinInet Replay instead of Sockets (windows only)
but it worked in very specific cases. Not a general solution.

Friday, 17 June 2016

How to put strtok function in a vugen script


put the logic after the co-related string

strtok is used when you get a long value from load runner seperated by delimiters for example,( and you want to seperate each value from the delimiters

logic()
{

extern char *strtok(char * string,const char * delimiters); // explicit declaration

char seperators[]= "(,";

char *token;

char c[100];
char * a[100];
char * d[100];
int i=0;

strcpy(c,lr_eval_string("{c_ContentGUID}"));

token= (char *) strtok(c,seperators); //Get the first token

if(!token)
{

lr_output_message("No token found in the string");

return (-1);

}

for(i=0; token !=NULL;i++)
{
 a[i]=token;

lr_output_message("%s", a[i]);

token= (char *) strtok(c,seperators); // get the next token

}

lr_save_string( a[6],"c_ContentGUID");

lr_save_string( a[5],"c_fgfgh");

lr_save_string( a[2],"c_xyz");
lr_save_string( a[1],"c_sret");

lr_output_message("c_ContentGUID : %s", lr_eval_string("{c_ContentGUID}"));


return 0;

}