Import collection using button importing same collection multiple times - Postman - html

I'm using Postman version 6.6.0, and trying import API collection via Run in Postman button. I have one HTML page which looks like:
<div id="hiddenEnv" class="nodisplay highlight highlight-attention">
<p>
Click the button below to import into Postman
</p>
<p>
<div class="postman-run-button"
data-postman-action="collection/import"
data-postman-var-1="abcd"></div>
<script type="text/javascript">
(function (p,o,s,t,m,a,n) {
!p[s] && (p[s] = function () { (p[t] || (p[t] = [])).push(arguments); });
!o.getElementById(s+t) && o.getElementsByTagName("head")[0].appendChild((
(n = o.createElement("script")),
(n.id = s+t), (n.async = 1), (n.src = m), n
));
}(window, document, "_pm", "PostmanRunObject", "https://run.pstmn.io/button.js"));
</script>
</p>
</div>
And js code:
$(function() {
var lastEnv;
function newEnv(name) {
debugger;
var env = {
"id": generateUUID(),
"name": "MyProject-" + name,
"values": [{
"key": "hostenv",
"value": "",
"type": "text",
"enabled": true
},
{
"key": "username",
"value": "",
"type": "text",
"enabled": true
},
{
"key": "password",
"value": "",
"type": "text",
"enabled": true
}
],
"timestamp": 1544608923,
"synced": false,
"syncedFilename": "",
"team": null,
"isDeleted": false
};
return env;
}
$('#enter-creds').on('click', function(ev) {
var options = {
"name": "sampleBasicModal",
"content": $("script#envModal").html(),
onComplete: function(ev) {
console.log(ev);
var modal = $(ev.currentTarget).closest('.modal');
var form = modal.find('form');
console.log(form);
var formArr = form.serializeArray();
var envName = _.find(formArr, {name: 'hostenv'}).value.split('.')[0];
var envOutput = newEnv(envName);
var formObj = {};
formObj.hostenv = _.find(formArr, {name: 'hostenv'}).value;
formObj.username = _.find(formArr, {name: 'username'}).value;
formObj.password = _.find(formArr, {name: 'password'}).value;
if (!_pm('env.create', 'MyProject-' + envName, formObj)) {
_pm('env.replace', 'MyProject-' + envName, formObj);
}
lastEnv = envOutput;
$('#shownEnv').remove();
$('#hiddenEnv').slideDown(750);
}
};
var inst = Olive.modal.show(options);
ev.preventDefault();
});
});
I'm able to import my collections to Postman environment. However, same collection keep adding 7 to 8 times. I couldn't find where is the issue!
Edit:
I have checked it few times and then found that issue occurred when I have multiple environments.

After discussing this issue with a Postman team member, they found that there is an issue in the Postman with Windows OS, here is the reported link
Collection getting imported multiple times when using RiP button [Windows]

Related

Getting inventory contexts of Steam users

A stack overflow answer explains how to retrieve a user's public inventory
http://steamcommunity.com/profiles/<PROFILEID>/inventory/json/<APPID>/<CONTEXTID>
I read that context ID must be set as 2 to find items for most games, but this is not always the case. Is there any official API to find a user's inventory contexts? steamapis.com already has a paid API which performs this task:
{
"steamID": {
"universe": 1,
"type": 1,
"instance": 1,
"accountid": 78261062
},
"name": "PEPZ",
"onlineState": "online",
"stateMessage": "Online",
"privacyState": "public",
"visibilityState": "3",
"avatarHash": "5b702b331ddeb928225ad562a3e729aecd191b9a",
"vacBanned": false,
"tradeBanState": "None",
"isLimitedAccount": false,
"customURL": "pepzwee",
"memberSince": "2011-02-21T22:00:00.000Z",
"location": "Estonia",
"realName": "SteamApis.com Developer",
"summary": "",
"groups": [
{
"universe": 1,
"type": 7,
"instance": 0,
"accountid": 28077004
},
...
],
"primaryGroup": {
"universe": 1,
"type": 7,
"instance": 0,
"accountid": 28077004
},
"contexts": {
"440": {
"appid": 440,
"name": "Team Fortress 2",
"icon": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/apps/440/e3f595a92552da3d664ad00277fad2107345f743.jpg",
"link": "http://steamcommunity.com/app/440",
"asset_count": 11,
"inventory_logo": "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/apps/440/e613d1d46de26ea755105b898cc8830d305353f3.png",
"trade_permissions": "FULL",
"load_failed": 0,
"rgContexts": {
"2": {
"asset_count": 11,
"id": "2",
"name": "Backpack"
}
}
},
...
}
}
Where "rgContexts" contains inventory context for each game.
I found out with some inspect element work, that there is a script tag available with the exact information you need. This is an example of my profile:
var g_rgWalletInfo = {"success":false};
var g_bInventoryIsInModalDialog = false;
var g_bIsInMarketplace = false;
UserYou.SetSteamId( '76561199033382814' );
var g_rgAppContextData = {"753":{"appid":753,"name":"Steam","icon":"https:\/\/cdn.cloudflare.steamstatic.com\/steamcommunity\/public\/images\/apps\/753\/135dc1ac1cd9763dfc8ad52f4e880d2ac058a36c.jpg","link":"https:\/\/steamcommunity.com\/app\/753","asset_count":303,"inventory_logo":"https:\/\/cdn.cloudflare.steamstatic.com\/steamcommunity\/public\/images\/apps\/753\/db8ca9e130b7b37685ab2229bf5a288aefc3f0fa.png","trade_permissions":"FULL","load_failed":0,"store_vetted":"1","rgContexts":{"6":{"asset_count":303,"id":"6","name":"Community"}}},"730":{"appid":730,"name":"Counter-Strike: Global Offensive","icon":"https:\/\/cdn.cloudflare.steamstatic.com\/steamcommunity\/public\/images\/apps\/730\/69f7ebe2735c366c65c0b33dae00e12dc40edbe4.jpg","link":"https:\/\/steamcommunity.com\/app\/730","asset_count":61,"inventory_logo":"https:\/\/cdn.cloudflare.steamstatic.com\/steamcommunity\/public\/images\/apps\/730\/3ab6e87a04994b900881f694284a75150e640536.png","trade_permissions":"FULL","load_failed":0,"store_vetted":"1","rgContexts":{"2":{"asset_count":61,"id":"2","name":"Backpack"}}}};
var g_strInventoryLoadURL = 'https://steamcommunity.com/id/stoplookingatmyid/inventory/json/';
$J( function() {
UserYou.LoadContexts( g_rgAppContextData );
} );
$J( function() {
var bHasPendingGifts = false;
InitInventoryPage( bHasPendingGifts, -1, false );
});
var g_bInClient = false;
var g_bInChinaRealm = false;
var g_bViewingOwnProfile = false;
var g_bMarketAllowed = false;
var g_strLanguage = 'english';
var g_strCountryCode = "US";
var g_strProfileURL = 'https://steamcommunity.com/id/stoplookingatmyid';
Some of this data is junk, but g_rgAppContextData is exactly what you need in JSON format, and it just needs to be parsed if your programming language of choice. In this example, 753 is the app id of Steam, with 6 being the context id, and 730 is CSGO'S app id, with 2 as the context id. with This data won't be present if the user has a private steam inventory.

Not reading the second data from json

I am trying to read data from json (2 cycles) and add an entry. the first time, the data added successfully but during the second cycle, it failed. below are the details. Also working when run with page object and without reading from json;
The "test_pom_fromjson" added successfully but when running for the test_pom_fromjson_first it failed with error saying no element found using element(by.id('s2id_autogen10')).click(); which is the locator for location column.
Refer the screenshot and html code for the page - https://pastebin.com/ZXyRx1tv
mo.ts: pageobject for the below spec file
var mo = function () {
this.createbutton = function () {
var createb = element(by.css('button[title="Add Master Obligation"]'))
//var createbutton = element(by.buttonText('↵ ↵ Add Master Obligatio...↵ '))
browser.executeScript("arguments[0].scrollIntoView();arguments[1].click();", createb, createb);
}
this.MasterObligationName = function (value) {
element(by.model('obligation.ObligationName')).sendKeys(value);
}
this.Module = function (value) {
element(by.id('s2id_TaxProcess')).click();
element.all(by.repeater('item in obligation.TaxProcess.list')).get(value).click();
}
this.Location = function (value) {
element(by.id('s2id_autogen10')).click();
element.all(by.repeater('item in obligation.Jurisdiction.list')).get(value).click();
}
this.CentralObligation = function (value) {
element.all(by.model('obligation.CentralObligation')).get(value).click();
}
this.Type = function (value) {
element(by.id('s2id_txtReturnType')).click();
element.all(by.repeater('item in obligation.ReturnType.list')).get(value).click();
}
this.Years = function (value) {
element(by.id('s2id_txtTaxYear')).click();
element.all(by.repeater('item in obligation.TaxYears.list')).get(value).click();
}
this.Periods = function (value) {
element(by.id('s2id_txtPeriod')).click();
element.all(by.repeater('tem in obligation.Periods.list')).get(value).click();
}
this.Forms = function (value) {
element.all(by.id('s2id_txtForms')).get(0).click();
element.all(by.repeater('item in obligation.Forms.list')).get(value).click();
}
this.Reports = function (value) {
element.all(by.id('s2id_txtForms')).get(1).click();
element.all(by.repeater('item in obligation.Reports.list')).get(value).click();
}
this.savebutton = function () {
var saveb = element(by.css('button[title="Save"]'))
browser.executeScript("arguments[0].scrollIntoView();arguments[1].click();", saveb, saveb);
}
module.exports = new mo();
spec.ts: var mo = require("../page/mo.ts")
var testData = require('../testdata/testdata.json');
testData.forEach(function (data) {
it('create and save master obligation', function () {
browser.sleep(10000);
mo.createbutton();
browser.sleep(10000);
mo.MasterObligationName(data.Master_Obligation_Name)
mo.Module(data.Module);
mo.Location(data.Location);
mo.CentralObligation(data.Central_Obligation);
mo.Type(data.Type);
mo.Years(data.Years);
mo.Periods(data.Periods);
mo.Forms(data.Forms);
mo.Reports(data.Reports);
mo.savebutton();
})
})
testdata.json:
[{
"Master_Obligation_Name": "test_pom_fromjson",
"Module": "2",
"Location": "1",
"Central_Obligation": "0",
"Type": "2",
"Years": "1",
"Periods": "1",
"Forms": "1",
"Reports": "0"
},
{
"Master_Obligation_Name": "test_pom_fromjson_first",
"Module": "2",
"Location": "1",
"Central_Obligation": "0",
"Type": "2",
"Years": "1",
"Periods": "1",
"Forms": "1",
"Reports": "0"
}]
Two options you can try:
1.Wait for some time before that click
2.Either id number is auto generated so it might be changed everytime, so use some other locator.
If the id is auto-generated then look for some other locator then:
element.all(by.id('s2id_Jurisdiction')).get(1).click();
element.all(by.repeater('item in obligation.Jurisdiction.list')).get(value).click();
OR you can also try the following way:
var module = element(by.xpath("//input[starts-with(#id, 's2id_autogen')]")).get(1).click();
var location= element(by.xpath("//input[starts-with(#id, 's2id_autogen')]")).get(2).click();
var type = element(by.xpath("//input[starts-with(#id, 's2id_autogen')]")).get(3).click();

How to POST Geolocation values to a Sharepoint List Field with Rest API?

I need to post two values Caption and Location, later being a GeoLocation field in Sharepoint list. I am using the following JSON:
{"__metadata": { "type": "SP.ListItem" }, "Caption": "Testing", "Location": "POINT (78.4 17.4)"}
But it's not working. Shows the following error:
Cannot deserialize data for type Microsoft.SharePoint.SPFieldGeolocationValue
I am doing this from Xcode.
SharePoint REST service expects SP.FieldGeolocationValue to be specified in the following format:
{
"__metadata": {
"type": "SP.FieldGeolocationValue"
},
"Altitude": <val>,
"Latitude": <val>,
"Longitude": <val>,
"Measure": <val>
}
JavaScript example
The example demonstrates how to create list item in Contacts list and set Geolocation value for Location field:
function createContact(name,location){
var listTitle = 'Contacts';
var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('" + listTitle + "')/items";
var payload = {
"__metadata": { "type": "SP.ListItem" },
"Title": name,
"Location": {
"__metadata": {"type": "SP.FieldGeolocationValue"},
"Latitude": location[0],
"Longitude": location[1],
}
};
return executeJson(url,'POST',null,payload);
}
createContact("Work Address", [60.2872339,24.8516785])
.done(function(data)
{
console.log('Contact has been created');
})
.fail(function(error){
console.log('An error occured while creating contact');
});
where
function executeJson(url,method,headers,payload)
{
method = method || 'GET';
headers = headers || {};
headers["Accept"] = "application/json;odata=verbose";
if(method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if (typeof payload != 'undefined') {
ajaxOptions.data = JSON.stringify(payload);
}
return $.ajax(ajaxOptions);
}

How to receive a json string after a jquery post in WebMatrix?

If I have the following post call:
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"uno": "lalala",
"dos": "jojojo"
}
var data = JSON.stringify(datos);
$.post(url, data, function (resultado) {
$('#posted_values').html(resultado);
});
});
How can I receive and process the json object in a cshtml file? I mean what I put in Decode call:
if (IsPost)
{
var json_object = Json.Decode(Request???);
}
Edited to complete the answer of #MikeBrind, to help others with the same problem.
Example of using decode for a more complex json object.
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"firstName": "John",
"lastName": "Smith",
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumber": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "fax",
"number": "646 555-4567"
}
]
}
var data = JSON.stringify(datos);
$.post(url, {"person": data}, function (resultado) {
$('#posted_values').html(resultado);
});
});
Receiving and using:
#{
dynamic json_object;
if (IsPost)
{
json_object = Json.Decode(Request["person"]);
#json_object.firstName<br/>
#json_object.lastName<br/>
#json_object.address.city<br/>
#json_object.address.postalCode<br/>
foreach (dynamic phone in json_object.phoneNumber)
{
#phone.type<br/>
#phone.number
}
}
}
Don't JSON.stringify the data if it is just key/value pairs like this. Do a form post:
$('#json_form').submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var datos = {
"uno": "lalala",
"dos": "jojojo"
}
//var data = JSON.stringify(datos); no need for this
$.post(url, datos, function (resultado) {
$('#posted_values').html(resultado);
});
});
Then the values are available from Request["uno"] and Request["dos"]
If you ever do need to use JSON.stringify (which you would for more complex data structures), the JSON is transmitted in the Request body, so you need to extract it from Request.InputStream:
var reader = new StreamReader(Request.InputStream);
var json = reader.ReadToEnd();

Validate Json Schema

I'm getting an error when using json-schema-validator API v4.
I try to do :
final JsonValidator validator = new JsonValidator(JsonLoader.fromPath("schema.json"));
ValidationReport report = validator.validate(data);
but every time I get an error : # [schema]: unknown keyword contacts
schema.json :
{
"contacts": {
"description": "The list of contacts",
"type": "array",
"optional": true,
"items": {
"description": "A contact",
"type": "object",
"properties": {
"givenName": {
"description": "Person's first name",
"type": "string",
"maxLength": 64,
"optional": true
},
"familyName": {
"description": "A person's last name",
"type": "string",
"maxLength": 64,
"optional": true
}
}
}
}
}
Regards
As far as I can intuit, your data looks like this-> json_data={"contacts":array}. If this is true, basically your outermost thing is an object (basically the full json object itself), for which you "might" need to define the schema starting from the "top level root" of your json as->
schema.json:
{
"description": "the outer json",
"type": "object",
"properties": {
"contacts": {
"description": "The list of contacts",
"type": "array",
"optional": true,
"items": {
"description": "A contact",
"type": "object",
"properties": {
"givenName": {
etc.....
Forgive me for rough indentations. Also, I have not tested this, please see if it works, if it does not, I would suggest you to provide your json_data (example at least) and the API's examples so that one can try to locate where what is wrong.
Use AVJ. Instead of having your data validation and sanitization logic written as lengthy code, you can declare the requirements to your data with concise, easy to read and cross-platform JSON Schema or JSON Type Definition specifications and validate the data as soon as it arrives to your application.
// validationSchema.js
import Ajv from "ajv";
import addFormats from "ajv-formats";
import ajvErrors from "ajv-errors";
const schemas = {
newUser: {
{
type: "object",
properties: {
lastName: {
type: "string",
minLength: 1,
maxLength: 255
},
firstName: {
type: "string",
minLength: 1,
maxLength: 255
},
description: {
type: "string"
},
birthday: {
type: "string",
format: "date-time"
},
status: {
type: "string",
enum: ["ACTIVE", "DELETED"]
},
},
required: ["name"]
}
}
};
const ajv = new Ajv({ allErrors: true });
addFormats(ajv);
ajvErrors(ajv /*, {singleError: true} */);
const mapErrors = (errorsEntry = []) => {
const errors = errorsEntry.reduce(
(
acc,
{ instancePath = "", message = "", params: { missingProperty = "" } = {} }
) => {
const key = (instancePath || missingProperty).replace("/", "");
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(`${key} ${message}`);
return acc;
},
[]
);
return errors;
};
const validate = (schemaName, data) => {
const v = ajv.compile(schemas[schemaName]);
let valid = false,
errors = [];
valid = v(data);
if (!valid) {
errors = mapErrors(v.errors);
}
return { valid, errors };
};
export default { validate };
You can validate it like this:
import validationSchema from "your_path/validationSchema.js"
const user = {
firstName: "",
lastName: "",
....
};
const { valid, errors = [] } = validationSchema.validate("newUser", user);
if(valid){
console.log("Data is valid!");
} else {
console.log("Data is not valid!");
console.log(errors);
}