POST with more than one "body" - dart

This is my code to make the call, a POST. Until now I only needed to send one product in each post.
But, I wanted to start sending my list of products in just one POST.
Future DadosPagamento() async {
await Future.delayed(const Duration(milliseconds: 200));
var headers = {'Authorization': 'Bearer Gns2DfakHnjd9id', 'Content-Type': 'application/json'};
var request = http.Request(
'POST', Uri.parse('http://appdnz.ddns/APP1/Products'));
request.body = json.encode(
[
{
"OrderState": "",
"LineID": "1",
"ClientID": idCliente,
"ProductReference": ref,
"Color": color,
"Size": size,
"Quantity": quantity,
"UnitPriceWithoutTax": precoSemTax,
"ShippingAmount": envioPreco,
"OrderReference": "",
"CarrierID": idTrans,
"Comments": comentario,
"ProductDescription": descricaoProd,
"ShippingName": envioNome,
},
],
);
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
}
}
example of what i want to send
request.body = json.encode(
[
{
"Lineid" = "1",
"Reference"= "xpto",
"Quantity"= "1"
....
}
,
{
"Lineid" = "2",
"Reference" = "xpto2",
"Quantity" = "5"
...
}
,
{
"Lineid" = "3",
"Reference" = "xpto3",
"Quantity" = "6"
...
}
]
)
In the research I did, I realized that it might work if I create a list and put it in json.encode(list), I don't know if it's the best way or if there aren't any more ways.
Thanks

Related

forEach() iterates too fast with ASYNC AWAIT - Skipping data

I am re-writing my website and am trying to import my members from array of JSON objects.
Each object represents a band that the user has uploaded. So I wrote a quick file that works with the list and my new database / authentication system, auth0.
As outline in the comments below...
First I Request an access token so I can create an account for each member using Auth0. Then I iterate through my array of objects representing bands. For each band object I have the code do a few things... First, it creates a new account on my auth system. This sends back a user ID. I add the user ID to the band object to be stored in my database. It adds the location as well as adds a few posts that the user may have had from the old system.
This all works well if I do one user... But if I let it iterate through the whole array it doesn't work. It added about 15 bands to the auth system and 50 bands to the database... It seems like its going too fast to successfully publish them all. Any ideas on how to fix this?
** Also tried this with a for loop instead of for each. Moving everything inside the for loop creates both the same number of bands and user accounts, but now it times out at about 10 bands instead of doing all of them.
Thanks!
const uuidv4 = require('uuid')
const BulkBands = require('./BulkBands')
const fetch = require("node-fetch");
let bandCount = 0
//First I need to get an Access Token for my Auth Proider, Auth0
const getAccessToken = async () => {
try {
let response = await fetch(`https://nm-music.auth0.com/oauth/token`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: '{"client_id":"xxxxxxxxx","client_secret":"xxxxxxxxx", "audience":"https://xxxxxxxx.com/api/v2/","grant_type":"client_credentials"}'
})
const responseData = await response.json()
//Now I start The Process of Adding the Bands.
addTheBands(responseData.access_token)
} catch (error) {
console.log(error)
}
}
//Here I use the array method, forEach() to iterate over the list of about 77 bands.
const addTheBands = (accessToken) => {
BulkBands.forEach(band => {
//The first thing I want to do for each band is create an account for them on the Auth system.
createNewAccount(band, accessToken)
})
}
//Here is the function to create the account.
const createNewAccount = async (band, accessToken) => {
try {
const response = await fetch(`https://xxxxxxxxx.com/api/v2/users`, {
method: 'POST',
headers: {
'content-type': 'application/json;',
"Authorization": `Bearer ${accessToken}`,
},
body: JSON.stringify({
"connection": 'Username-Password-Authentication',
"email": band.bandEmail,
// "phone_number": "+19995550123",
"user_metadata": {},
"blocked": false,
"email_verified": false,
// "phone_verified": false,
"app_metadata": {},
// "given_name": band.bandName,
// "family_name": band.bandName,
"name": band.bandEmail,
// "nickname": "Johnny",
// "picture": "https://secure.gravatar.com/avatar/15626c5e0c749cb912f9d1ad48dba440?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png",
// "user_id": "",
// "connection": "Initial-Connection",
"password": "xxxxxxxx",
"verify_email": false,
// "username": band.bandEmail
})
})
let newUserResponse = await response.json()
//Now that their account has been made, I want to add the band to my database, and use the Account ID from newUserResponse as the userId for the band. That way the band is associted with their account.
addTheBand({
quoteGenerator: [],
userId: newUserResponse.identities[0].user_id,
posts: [
{
"type": "band",
"data": "",
"date": new Date(),
"postId": uuidv4(),
"approved": null,
"rockOn": []
},
],
type: 'band',
bandName: band.bandName,
bandEmail: band.bandEmail,
bandGenre: band.bandGenre,
bandBio: band.bandBio,
youtube: [band.youtube1, band.youtube2],
published: false,
cancellationPolicy: 'You may cancel this performance up to 2 weeks prior to the performance date without penalty. If this performance is cancelled within 2 weeks of the performance date the booking party will be required to pay 50% of the booking fee to the band. If the booking is cancelled within 3 days of the performance date the full payment is required to be paid to the band. ',
baseCost: band.baseCost,
mainDate: {
charge: 0,
sunday: 0,
monday: 0,
tuesday: 0,
wednesday: 0,
thursday: 0,
friday: 0,
saturday: 0,
}
}, band)
} catch (error) {
console.log(error)
}
}
//Now to start adding the band...
const addTheBand = async (newBand, band) => {
let newLocation = []
let accessToken = ''
//I need to geo-locate each band for my new system. So I use the google api to do so.
try {
let resposne = await fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=${band.bandLocation}&key=xxxxxxxxx`)
const responseLocation = await resposne.json()
newLocation = [responseLocation.results[0].geometry.location.lng, responseLocation.results[0].geometry.location.lat ]
// I store the geo location for the band and now I post the new band to my database. The Geo Location is Indexed and does not work if I post it - I need to do this after the band is posted - no clue why.
response = await fetch('http://localhost:5000/api/autoquotegenerators', {
method: 'POST',
headers: {
"Content-Type": 'application/json; charset=UTF-8'
},
body: JSON.stringify(newBand)
})
const responseData = await response.json()
if(responseData){
console.log('Band Added');
//Like I said before... I need to add the geo-location now. So this function will do so.
updateBandLocation({
geometry: {
coordinates: newLocation,
city: band.bandLocation,
}
}, responseData._id, responseData, band)
}
} catch (error) {
console.log(error)
}
}
//I send the geo-location data to this function... it also takes care of a few last minute things such as posts, and quote figures and such. It all works.
const updateBandLocation = async (newLocation, bandUserId, band, oldBand) => {
console.log('adding location...')
let newPosts = [...band.posts]
let newQuoteGenerator = []
if(oldBand.timedRate > 0 ){
newQuoteGenerator.push({
cardType: "timed",
inputType: "select",
cardTitle: "Hourly Rate",
charge: oldBand.timedRate,
price: 0,
cardId: uuidv4()
})
}
if(oldBand.youtube1){
newPosts.push({
type: "video",
data: oldBand.youtube1,
date: new Date(),
postId: uuidv4(),
rockOn: []
})
}
if(oldBand.youtube2){
newPosts.push({
type: "video",
data: oldBand.youtube2,
date: new Date(),
postId: uuidv4(),
rockOn: []
})
}
try {
const response = await fetch(`http://localhost:5000/api/autoquotegenerators/${bandUserId}`, {
method: 'PUT',
headers: {
"Content-Type": "application/json; charset=UTF-8",
},
body: JSON.stringify({
quoteGenerator: newQuoteGenerator,
bandLocation: newLocation,
posts: newPosts
})
})
const responseData = await response.json()
bandCount += 1
console.log(bandCount)
} catch (error) {
console.log(error)
}
}
getAccessToken()

How do I implement vaadin-grid-tree-column in polymer 3

I have the following in the application template:
<vaadin-grid id="directory">
<vaadin-grid-tree-column path="name" header="Name"></vaadin-grid-tree-column>
</vaadin-grid>
The iron-ajax calls the following on a successful response:
getlist(request) {
var myResponse = request.detail.response;
console.log(myResponse);
this.$.directory.items = myResponse;
}
The data that is returned is:
[
{
"name": "apps",
"fullpath": "/db/system/xqdoc/apps",
"children": [
{
"name": "xqDoc",
"fullpath": "/db/system/xqdoc/apps/xqDoc",
"children": [
{
"name": "modules",
"fullpath": "/db/system/xqdoc/apps/xqDoc/modules",
"children": [
{
"name": "config.xqm.xml",
"fullpath": "/db/system/xqdoc/apps/xqDoc/modules/config.xqm.xml"
},
{
"name": "xqdoc-lib.xqy.xml",
"fullpath": "/db/system/xqdoc/apps/xqDoc/modules/xqdoc-lib.xqy.xml"
}
]
}
]
}
]
}
]
The apps shows up, but when I expand the apps node, then xqDoc node doees not show up.
Do I need additional data in the dataset?
Am I missing some coding that is needed?
I have the solution.
<vaadin-grid id="directory" selected-items="{{selected}}">
<vaadin-grid-tree-column path="name" header="Name"item-has-children-path="hasChildren"></vaadin-grid-tree-column>
</vaadin-grid>
I setup the provider using the connectedCallback and not to use an iron-ajax for talking with the server.
connectedCallback() {
super.connectedCallback();
const grid = this.$.directory;
this.$.directory.dataProvider = function(params, callback) {
let url = "/exist/restxq/xqdoc/level" +
'?page=' + params.page + // the requested page index
'&per_page=' + params.pageSize; // number of items on the page
if (params.parentItem) {
url += '&path=' + params.parentItem.fullpath;
}
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var response = JSON.parse(xhr.responseText);
callback(
response.data, // requested page of items
response.totalSize // total number of items
);
};
xhr.open('GET', url, true);
xhr.send();
};
this.$.directory.addEventListener('active-item-changed', function(event) {
const item = event.detail.value;
if (item && item.hasChildren == false) {
grid.selectedItems = [item];
} else {
grid.selectedItems = [];
}
});
}
The web service returns a level of the tree:
{
"totalSize": 2,
"data": [
{
"name": "apps",
"fullpath": "/apps",
"hasChildren": true
},
{
"name": "lib",
"fullpath": "/lib",
"hasChildren": true
}
]
}
The codebase is here: https://github.com/lcahlander/xqDoc-eXist-db

Load images from JSON object containing image references

I'm in the process of building an API that will take the JSON object output from a Konva stage and convert that into images on the server-side. I'm making use of the konva-node npm package and it works really well until it comes to loading in remote images that may have been a part of the original "design". I can see from this answer as to how we would solve the problem in the browser, however this doesn't appear to work in the same way in the nodejs implementation of Konva.
An example JSON input is the following:
let json = {
"attrs": {
"width": 600,
"height": 600
},
"className": "Stage",
"children": [{
"attrs": {},
"className": "Layer",
"children": [{
"attrs": {
"src": "https://ichef.bbci.co.uk/onesport/cps/480/cpsprodpb/1859A/production/_101883799_gettyimages-844211624.jpg"
},
"className": "Image"
}]
}, {
"attrs": {},
"className": "Layer",
"children": [{
"attrs": {
"text": "Hello world.",
"x": 50,
"y": 50,
"fontSize": 20,
"fill": "blue"
},
"className": "Text"
}]
}]
}
As you can see, I've subbed in src attributes as a sort of placeholder for when we come to load up the data into a canvas again.
The issue that I'm having is with actually getting those images to load in again once I process the JSON on the server-side.
Here is my current code
var fs = require('fs')
const Konva = require('konva-node')
var Request = require('pixl-request')
let json = {"attrs":{"width":600,"height":600},"className":"Stage","children":[{"attrs":{},"className":"Layer","children":[{"attrs":{"src":"https://ichef.bbci.co.uk/onesport/cps/480/cpsprodpb/1859A/production/_101883799_gettyimages-844211624.jpg"},"className":"Image"}]},{"attrs":{},"className":"Layer","children":[{"attrs":{"text":"Hello world.","x":50,"y":50,"fontSize":20,"fill":"blue"},"className":"Text"}]}] }
var stage = new Konva.Stage()
let loadedDesign = Konva.Node.create(json)
loadedDesign.find('Image').forEach((imageNode) => {
const imageURL = imageNode.getAttr('src')
var request = new Request();
request.get(imageURL, function(err, resp, data) {
var img = new Konva.window.Image()
img.onerror = err => { throw err }
img.onload = () => {
imageNode.image(img);
imageNode.getLayer().batchDraw();
}
img.src = data;
});
});
loadedDesign.toDataURL({
callback: function(data) {
var base64Data = data.replace(/^data:image\/png;base64,/, '');
fs.writeFile('./images/out.png', base64Data, 'base64', function(err) {
err && console.log(err)
console.log('See out.png')
});
}
});
The current output results in an image with the text on the canvas but the image never makes it in.
You need to load all images, only then use toDataURL(). I guess your image is not visible, because you convert stage to dataURL before images are loaded and rend
var request = new Request();
function loadImage(url) {
return new Promise(resolve => {
request.get(url, function(err, resp, data) {
var img = new Konva.window.Image();
img.onerror = err => {
throw err;
};
img.onload = () => {
resolve(img);
};
img.src = data;
});
});
}
async function run() {
const stage = Konva.Node.create(json);
const images = stage.find('Image');
for (const imageNode of images) {
const imageURL = imageNode.getAttr('src');
const img = await loadImage(imageURL);
imageNode.setImage(img);
}
stage.findOne('Layer').draw();
const data = stage.toDataURL();
var base64Data = data.replace(/^data:image\/png;base64,/, '');
fs.writeFile('out.png', base64Data, 'base64', function(err) {
err && console.log(err);
console.log('See out.png');
});
}
run().catch(e => {
console.error(e);
});

Post method with multiple parameter

I am unable to insert multiple rows in database using Post method in MVC web API. I have written code for it but when i am testing by inserting multiple rows through postman it is giving error. At line first the variable "delegatetable" shows null due to which error is coming. i am not doing database connection through entity framework, i have created a DelegateTable class.
public HttpResponseMessage Post(List<DelegateTable> delegatetable)
{
try
{
using (var delegateContext = new ShowContext())
{
foreach (DelegateTable item in delegatetable)
{
DelegateTable delegates = new DelegateTable();
delegates.Salutation__c = item.Salutation__c;
delegates.First_Name__c = item.First_Name__c;
delegates.Last_Name__c = item.Last_Name__c;
delegates.Account_Name__c = item.Account_Name__c;
delegates.Contact_Email__c = item.Contact_Email__c;
delegates.Category__c = item.Category__c;
delegates.Conference_Type__c = item.Conference_Type__c;
delegates.Conference_Selection__c = item.Conference_Selection__c;
delegates.Payment_Statuss__c = item.Payment_Statuss__c;
delegates.Barcode__c = item.Barcode__c;
delegateContext.SaveChanges();
}
var message = Request.CreateResponse(HttpStatusCode.Created, delegatetable);
message.Headers.Location = new Uri(Request.RequestUri.ToString());
return message;
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
Json data that i am passing is below
[
{
"attributes": {
"type": "Registration__c",
"url": "/services/data/v43.0/sobjects/Registration__c/a3h8E0000009VuVQAU"
},
"Salutation__c": "Dr.",
"First_Name__c": "Test",
"Last_Name__c": "Test",
"Account_Name__c": "Test",
"Contact_Email__c": "test123#gmail.com",
"Category__c": "Test",
"Conference_Type__c": null,
"Conference_Selection__c": null,
"Payment_Statuss__c": null,
"Barcode__c": "Test"
},
{
"attributes": {
"type": "Registration__c",
"url": "/services/data/v43.0/sobjects/Registration__c/a3hD0000001kEfOIAU"
},
"Salutation__c": "Mr.",
"First_Name__c": "Demo",
"Last_Name__c": "Demo",
"Account_Name__c": "Demo",
"Contact_Email__c": "Demo#gmail.com",
"Category__c": "Demo",
"Conference_Type__c": null,
"Conference_Selection__c": null,
"Payment_Statuss__c": null,
"Barcode__c": null
}
]
You may try to reformat your payload as a JSON array, as the problem might be that the payload cannot be converted to a List.
Try this:
{
"delegates" :
[
{
"attributes": ..., ...
},
{ "attributes": ..., ...
},
...
]
}

Successful consumption of a Azure Machine Learning API?

Does anyone have good documentation of a successful implementation of the Azure ML studio API in a web app that's not ASP.net? I'd like to run on it with ruby on rails, but I guess I have to figure it out on my own.
It is simply a rest API call. Look at this...
data = {
"Inputs": {
"input1":
{
"ColumnNames": ["YearBuild", "City", "State", "HomeType", "TaxAssesmentYear", "LotSize", "HomeSize", "NumBedrooms"],
"Values": [ [ "0", "Anchorage", "AK ", "Apartment", "0", "0", "0", "0" ], [ "0", "Anchorage", "AK ", "Apartment", "0", "0", "0", "0" ], ]
}, },
"GlobalParameters": {
}
}
body = str.encode(json.dumps(data))
url = 'https://ussouthcentral.services.azureml.net/workspaces/45aeb4d8283d4be6ae211592f5366af5/services/07ffeeb6fcb84f16bc62cdcf67fd95b3/execute?api-version=2.0&details=true'
api_key = 'abc123' # Replace this with the API key for the web service
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib2.Request(url, body, headers)
Give a shot at trying with the postman app in chrome first. Setting your headers, just as above, your data goes in the post payload in the json format.
Here you'll find Ruby code (not python)
data = {
'Inputs' => {
'input1' => [
{
'weekday' => 1,
'hour' => 2,
'events' => 0
}
]
},
'GlobalParameters' => {}
}
body = data.to_json
url = 'https://asiasoutheast.services.azureml.net/subscriptions/[tour stuff...]execute?api-version=2.0&format=swagger'
api_key = '[your api key]'
headers = {'Content-Type': 'application/json', 'Authorization': ('Bearer '+ api_key)}
RestClient::Request.execute(method: :post, url: url, payload: body, headers: headers)

Resources