jmeter - counting cookie values - cookies

I'm playing around with jmeter to validate a bug fix.
Server logic sets the cookie "mygroup" it can be either "groupa" or "groupb". I want to be able fire a series of requests and be able to see there is a proper balanced distribution between the values of this cookie. Ie make 100 requests and 50 times the cookie will be set to "groupa" and "groupb".
I'm a bit stuck on this. I currently have the following. I can see the cookies being set in the results tree but I'd like to be able to display the a table with the version and the number of requests of each.
Thread Group
HTTP Cookie Manager
HTTP Request
View Results Tree
Within the results tree I can see Set-Cookie: mygroup="groupa" and also sometimes mygroup="groupb" how do I tabulize this ??

You can have cookies values exported as JMeter variables by setting:
CookieManager.save.cookies=true
in user.properties.
Add a Cookie Manager to your Test Plan.
In this case you will have the var COOKIE_mygroup set by JMeter.
You can then count it like this using a JSR223 Sampler + Groovy (add groovy-all-version.jar in jmeter/lib folder:
String value = vars.get("COOKIE_mygroup");
Integer counterB = vars.getObject("counterB");
Integer counterA = vars.getObject("counterA");
if(counterA == null) {
counterA = new Integer(0);
vars.putObject("counterA", counterA);
}
if(counterB == null) {
counterB = new Integer(0);
vars.putObject("counterB", counterB);
}
if(value.equals("groupa")) {
counterA = counterA+1;
vars.putObject("counterA", counterA);
} else {
counterB = counterB+1;
vars.putObject("counterB", counterB);
}
Asyou have only one thread, at end of loop you can then compare the 2 values or just display the value:
add a debug sampler
add a view tree result
Run test plan, in view result tree click on debug sampler , select response tab and you should have your values

Related

Adding a cookie to DocumentRequest

Using AngleSharp v 0.9.9, I'm loading a page with OpenAsync which sets a bunch of cookies, something like:
var configuration = Configuration.Default.WithHttpClientRequester().WithCookies();
var currentContext = BrowsingContext.New(configuration);
// ....
var doc = context.OpenAsync(url, token);
This works fine and I can see the cookies have been set. For example, I can do this:
var cookieProvider = currentContext.Configuration.Services.OfType<ICookieProvider>().First() as MemoryCookieProvider;
And examine it in the debugger and see the cookies in there (for domain=.share.state.nm.us)
Then I need to submit a post:
var request = new DocumentRequest(postUrl);
request.Method = HttpMethod.Post;
request.Headers["Content-Type"] = "application/x-www-form-urlencoded";
request.Headers["User-Agent"] = userAgent;
//...
Which eventually gets submitted:
var download = loader.DownloadAsync(request);
And I can see (using Fiddler) that it's submitting the cookies from the cookieProvider.
However, I need to add a cookie (and possible change the value in another) and no matter what I try, it doesn't seem to include it. For example, I do this:
cookieProvider.Container.Add(new System.Net.Cookie()
{
Domain = ".share.state.nm.us",
Name = "psback",
Value = "somevalue",
Path = "/"
});
And again I can examine the cookieProvider in the debugger and see the cookie I set. But when I actually submit the request and look in fiddler, the new cookie isn't included.
This seems like it should be really simple, what is the correct way to set a new cookie and have it included in subsequent requests?
I think there are two potential ways to solve this.
either use document.Cookie for setting a new cookie (would require an active document that already is at the desired domain) or
Use a Filter for getting / manipulating the request before its send. This let's you really just change the used cookie container before actually submitting.
The Filter is set in the DefaultLoader configuration. See https://github.com/AngleSharp/AngleSharp/blob/master/src/AngleSharp/ConfigurationExtensions.cs#L152.

Meteor regex find() far slower than in MongoDB console

I've been researching A LOT for past 2 weeks and can't pinpoint the exact reason of my Meteor app returning results too slow.
Currently I have only a single collection in my Mongo database with around 2,00,000 documents. And to search I am using Meteor subscriptions on the basis of a given keyword. Here is my query:
db.collection.find({$or:[
{title:{$regex:".*java.*", $options:"i"}},
{company:{$regex:".*java.*", $options:"i"}}
]})
When I run above query in mongo shell, the results are returned instantly. But when I use it in Meteor client, the results take almost 40 seconds to return from server. Here is my meteor client code:
Template.testing.onCreated(function () {
var instance = this;
// initialize the reactive variables
instance.loaded = new ReactiveVar(0);
instance.limit = new ReactiveVar(20);
instance.autorun(function () {
// get the limit
var limit = instance.limit.get();
var keyword = Router.current().params.query.k;
var searchByLocation = Router.current().params.query.l;
var startDate = Session.get("startDate");
var endDate = Session.get("endDate");
// subscribe to the posts publication
var subscription = instance.subscribe('sub_testing', limit,keyword,searchByLocation,startDate,endDate);
// if subscription is ready, set limit to newLimit
$('#searchbutton').val('Searching');
if (subscription.ready()) {
$('#searchbutton').val('Search');
instance.loaded.set(limit);
} else {
console.log("> Subscription is not ready yet. \n\n");
}
});
instance.testing = function() {
return Collection.find({}, {sort:{id:-1},limit: instance.loaded.get()});
}
And here is my meteor server code:
Meteor.publish('sub_testing', function(limit,keyword,searchByLocation,startDate,endDate) {
Meteor._sleepForMs(200);
var pat = ".*" + keyword + ".*";
var pat2 = ".*" + searchByLocation + ".*";
return Jobstesting.find({$or:[{title:{$regex: pat, $options:"i"}}, { company:{$regex:pat,$options:"i"}},{ description:{$regex:pat,$options:"i"}},{location:{$regex:pat2,$options:"i"}},{country:{$regex:pat2,$options:"i"}}],$and:[{date_posted: { $gte : endDate, $lt: startDate }},{sort:{date_posted:-1},limit: limit,skip: limit});
});
One point I'd also like to mention here that I use "Load More" pagination and by default the limit parameter gets 20 records. On each "Load More" click, I increment the limit parameter by 20 so on first click it is 20, on second click 40 and so on...
Any help where I'm going wrong would be appreciated.
But when I use it in Meteor client, the results take almost 40 seconds to return from server.
You may be misunderstanding how Meteor is accessing your data.
Queries run on the client are processed on the client.
Meteor.publish - Makes data available on the server
Meteor.subscribe - Downloads that data from the server to the client.
Collection.find - Looks through the data on the client.
If you think the Meteor side is slow, you should time it server side (print time before/after) and file a bug.
If you're implementing a pager, you might try a meteor method instead, or
a pager package.

Add cookie for Xdebug in Paw

I debug my API using Xdebug and PHPStorm's debugging features. For this to work, the client needs a cookie named XDEBUG_SESSION.
When using Postman, I used to use a Chrome extension to add this cookie, and Postman's cookie interception feature to get this to work in Postman (since it's a sandboxed app).
However, I cannot create cookies in Paw. So, as a workaround, I modified the API response cookie to have the key as XDEBUG_SESSION and value as PHPSTORM, and debugging worked fine. However, this is not ideal as I would also like to set the expiry date to something far in the future (which I can't in Paw).
So, my questions are:
Is there a way to add custom cookies in Paw?
If not, is there a way to to edit the expiry date for an existing cookie (considering that name, value, domain and path are editable)?
Are there any other alternatives to achieve my objective?
I just managed to achieve this exact thing to debug my APIs with Paw (2.1.1).
You just have to Add a Header with the name Cookie and a value of Cookies picked from the dropdown that will appear. You then have to insert a Cookie named XDEBUG_SESSION with a value of PHPSTORM inside the Cookies value of the header just created.
To be more clear, you can see it in the screenshot below:
I messed around with it to see if I could create an extension. I wasn't able to, and the below does not work but thought I'd share in case anyone knows the missing pieces.
First off, there is no extension category (generator, dynamic value, importer) that this functionality falls into. I tried to make use of the dynamic value category but was unsuccessful:
CookieInjector = function(key, value) {
this.key = "XDEBUG_SESSION";
this.value = "PHPSTORM";
this.evaluate = function () {
var f = function (x,y) {
document.cookie=this.key+"="+this.value;
return true;
}
return f(this.key, this.value);
}
// Title function: takes no params, should return the string to display as
// the Dynamic Value title
this.title = function() {
return "Cookie"
}
// Text function: takes no params, should return the string to display as
// the Dynamic Value text
this.text = function() {
return this.key+"="+this.value;
}
}
// Extension Identifier (as a reverse domain name)
CookieInjector.identifier = "com.luckymarmot.PawExtensions.CookieInjector";
// Extension Name
CookieInjector.title = "Inject Cookie Into Cookie Jar";
// Dynamic Value Inputs
CookieInjector.inputs = [
DynamicValueInput("key", "Key", "String"),
DynamicValueInput("value", "Value", "String")
]
// Register this new Extension
registerDynamicValueClass(CookieInjector);
The main thing stopping this from working is I'm not sure how the request is built in PAW and not sure how to attach the cookie. I've looked through the documentation here: https://luckymarmot.com/paw/doc/Extensions/Reference/Reference, and can't find what I need.

How can I force the __utmz cookie to be set on the first page load

I am using a sweet little function to track visitors to my site and dump the info to Salesforce. However many form submissions have (none) set for many values because (as I understand it) the cookie is not set until the second page load.
I have tested this and that seems to be accurate, the problem is many people fill out a form on the first page, and I don't get any info through these submissions.
I am loading GA as follows:
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-29066630-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script');
ga.src = ('https:' == document.location.protocol ? 'https://ssl' :
'http://www') + '.google-analytics.com/ga.js';
ga.setAttribute('async', 'true');
document.documentElement.firstChild.appendChild(ga);
})();
</script>
And then running a php function to parse the __utmz cookie apart:
function tracking_cookie() { // ver 1.5
$trackarr = split('[|]',$_COOKIE["__utmz"]);
$conversion = $_COOKIE["Conversion"];
for($i=0;$i<count($trackarr);$i++){
$keyvalues=split('[=]',$trackarr[$i]);
$key=substr($keyvalues[0],-6);
switch ($key){
case "utmcsr":
$cookie['SearchEngine'] = $keyvalues[1];break;
case "utmccn":
$cookie['SearchCampaign'] = $keyvalues[1];break;
case "utmcmd":
$cookie['SearchType'] = $keyvalues[1];break;
case "utmcct":
$cookie['AdText'] = $keyvalues[1];break;
case "utmctr":
$cookie['Keyword'] = $keyvalues[1];break;
case "mgclid":
$cookie['isPPC'] = $keyvalues[1];break;
}
}
I have more code running after this. Any ideas on how to force the cookie to load the first time around?
A cookie isn't readable until the second page load - because they get sent in the request.
What you could do is on the initial page load (and no _utmz cookie is found in PHP) append another JS file / invoke some JS that will run an ajax command back to your server after the page has loaded.
This will act as the second page load and should have access to the new cookie (and the user wouldn't have left the page)
Have you taken a look at this Force.com Toolkit for Google Analytics? May be more reliable to get the information right from Google. Without knowing what else you are tracking or how you are storing it in Salesforce it is hard to give more detail.
https://github.com/mavens/Force.com-Toolkit-for-Google-Analytics
There is also some discussion on Google Groups - http://groups.google.com/a/googleproductforums.com/forum/#!category-topic/analytics/discuss-tracking-and-implementation-issues/bVR84di07pQ
You did say, "Many form submissions have none", so does that mean you do get data from time to time? Can you narrow it down to a browser?

Is there a way to get a Sharepoint site's locale with web services?

I've looked through the wss 3.0 documentation, but I can't find anything. I would like to retrieve the locale for a Sharepoint 2007 site using web services (no access to server so can't deploy anything on it), so as to know what time zone is site the configured in. Is that possible?
thx
The time zone of a SharePoint web site can be obtained by the GetList method of the Lists web service. It seems weird to ask for information about a list to get regional settings of a web site but that's it :-)
This is an excerpt of the method response about a single list:
<List>
...
<RegionalSettings>
<Language>1033</Language>
<Locale>1033</Locale>
<AdvanceHijri>0</AdvanceHijri>
<CalendarType>1</CalendarType>
<Time24>False</Time24>
<TimeZone>-60</TimeZone>
<SortOrder>2070</SortOrder>
<Presence>True</Presence>
</RegionalSettings>
...
</List>
The time zone is returned as an offset to the UTC time in minutes. If you add it to the time in the web site local time zone you will get the time in the UTC time zone. (If you want to get the correct value you will have to consider the daylight saving changes and apply them according to the season of the time.).
// Instantiate the web service. Don't forget to dispose it later.
// Append the web service suffix (/_vti_bin/Lists.asmx) to the URL
// of the web site which time zone of you are interested in.
// If you don't use IWA or the current user has no access to the
// web site set the service.Credentials instead.
var service = new Lists();
service.Url = "http://myhost/sites/mysite/_vti_bin/Lists.asmx";
service.UseDefaultCredentials = true;
// Get all lists from the web site you want to get the time zone of.
// Get the XML element at /Lists/List[1]. It can be any accessible list.
// We will use just the unique list identifier from the atribute ID.
var lists = service.GetListCollection();
var list = lists.ChildNodes.OfType<XmlElement>().FirstOrDefault();
if (list == null)
throw new ApplicationException("The web has no lists.");
// Get information about the list which a little about the web too.
// Get the XML element at /List/RegionalSettings/TimeZone.
list = (XmlElement) service.GetList(list.GetAttribute("ID"));
var regionalSettings = list.ChildNodes.OfType<XmlElement>().First(
item => item.LocalName == "RegionalSettings");
var timeZone = regionalSettings.ChildNodes.OfType<XmlElement>().First(
item => item.LocalName == "TimeZone");
// The offset can be added to the time in the web site local time zone
// to get the UTC time. For example, UTC+1 has the offset -60 minutes.
var utcOffset = new TimeSpan(0, int.Parse(timeZone.InnerText), 0);
--- Ferda
Ok, here's what I did to solve this:
make a query to the list for 1 element, getting times set for site's locale
make a query for that element, getting times in UTC
calculate the difference between the 2 results.
Code:
/// <summary>
/// Gets the difference between local time and UTC to calculate offset.
/// Makes a query to the list that returns 1 element with times using the locale as set in the site's settings.
/// Then makes another query for the same element with UTC times to calculate the difference.
/// </summary>
/// <param name="list">list to query</param>
/// <param name="client">WS object</param>
/// <returns>Time offset as TimeSpan object</returns>
private TimeSpan getSiteTZOffset(List list, WSLists.Lists client )
{
//Set up query parameters
XmlDocument xmlDoc = new XmlDocument();
XmlNode emptyQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode queryWithID = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode ndOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
ndOptions.InnerXml = "<DateInUtc>True</DateInUtc>";
XmlNamespaceManager xnm = new XmlNamespaceManager(xmlDoc.NameTable);
xnm.AddNamespace("z", "#RowsetSchema");
// Gets the attribute that serves as modified date
MapAttribute modifiedDateAttr = attributes.Single(x => x.Value.DateTimeModifiedField).Value;
// Gets the Id attribute
MapAttribute idAttr = attributes.Single(x => x.Value.KeyReference).Value;
//Get 1 result with site's local time
XmlNode resLocalTime = client.GetListItems(list.ListID, list.ViewID, emptyQuery, null, "1", null, null);
XmlNodeList itemsLocalTime = resLocalTime.SelectNodes("//z:row", xnm);
// 2nd query filters on ID of the item returned by 1st query
queryWithID.InnerXml = string.Format("<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>{0}</Value></Eq></Where>",
itemsLocalTime[0].Attributes[idAttr.Name].Value);
//get the result with UTC time
XmlNode resUtc = client.GetListItems(list.ListID, list.ViewID, queryWithID, null, "1", ndOptions, null);
XmlNodeList itemsUtc = resUtc.SelectNodes("//z:row", xnm);
//Converts string values to DateTime objects
DateTime localTime = DateTime.Parse(itemsLocalTime[0].Attributes[modifiedDateAttr.Name].Value);
DateTime utcTime = getUtcTime(itemsUtc[0].Attributes[modifiedDateAttr.Name].Value);
// Gets offset
TimeSpan offset = localTime - utcTime;
return offset;
}