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

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();

Related

How to add more ccRecipients in microsoft graph?

I'm using Microsoft Graph to connect with Outlook. Can someone please help me with my issue. I need to add more than one ccRecipient and bccRecipient. My web application sends, receives and reads emails through API. But I cant send email to more than one cc and bcc recipient. This is the function i`m using to send email.
edit: Right now function does not have two ccRecipients and two bccRecipients in JSON. I have tried in many different ways but when i test it in microsoft graph-explorer it fails to send on more than one address.
function sendEmail(){
getAccessToken(function(accessToken) {
if (accessToken) {
// Create a Graph client
var client = MicrosoftGraph.Client.init({
authProvider: (done) => {
// Just return the token
done(null, accessToken);
}
});
var recipient = $("#recipient").val();
var subject = $("#subject").val();
var carbon_copies = $("#carbon_copies").val();
var blind_carbon_copies = $("#blind_carbon_copies").val();
var filename_attachment = $("#filename").text();
var attachments_base64 = $("#attachment_base64").val();
var attachments_base64_replaced = attachments_base64.substring(attachments_base64.indexOf(",")+1);
alert(attachments_base64_replaced);
tinyMCE.triggerSave();
var body = $("#moj_tekst_editor").val();
var body_escape_double_qoute = body.replace(/"/g, '\\"');
//var body_escape_single_qoute = body_escape_double_qoute.replace(/'/g, "\\'");
var body_escape_forward_slash = body_escape_double_qoute.replace("/", "\\/");
var body_escape_forward_slash = body_escape_double_qoute.replace("/", "\\/");
alert(body_escape_forward_slash);
var email = '{"message":{"subject": "'+subject+'","body": {"contentType": "HTML","content": "'+body_escape_forward_slash+'"},"toRecipients": [{"emailAddress": {"address": "'+recipient+'"}}],"ccRecipients": [{"emailAddress": {"address": "'+carbon_copies+'"}}],"bccRecipients": [{"emailAddress": {"address": "'+blind_carbon_copies+'"}}],"attachments":[{"#odata.type":"#Microsoft.OutlookServices.FileAttachment","name":"'+filename_attachment+'","contentBytes":"'+attachments_base64_replaced+'"}]}, "saveToSentItems": "true"}'
console.log(email);
// Send Email
client
.api('/me/sendMail')
.header('Content-Type', "application/json")
.post(email, (err, res) => {
if (err) {
callback(null, err);
} else {
callback(res.value);
}
});
} else {
var error = { responseText: 'Could not retrieve access token' };
callback(null, error);
}
});
}
What do I need to do to be able to send email to more than one ccRecipient and bccRecipient? When I add more than one cc recipient message always comes to last one.
Thanks in advance!!
I found I can send emails to multiple toRecipients or ccRecipients by formatting the emailAddress in the following way:
{
"emailAddress": {
"address": "cc1#email.com"
}
},
{
"emailAddress": {
"address": "cc2#email.com"
}
}
Full request body looks like this:
{
"message": {
"subject": "Meet for lunch?",
"body": {
"contentType": "Text",
"content": "The new cafeteria is open."
},
"toRecipients": [
{
"emailAddress": {
"address": "address1#email.com"
}
},
{
"emailAddress": {
"address": "address2#email.com"
}
}
],
"ccRecipients": [
{
"emailAddress": {
"address": "cc1#email.com"
}
},
{
"emailAddress": {
"address": "cc2#email.com"
}
}
]
},
"saveToSentItems": "true"
}

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();

Spotify API top-tracks broken

I'm trying to get the first top-track preview url from an artist but everytime I do the search it returns a broken json. I can parse it as a string to get what I need but a json would be a lot easier. Here is my code:
const https = require('https');
var open = require('open')
function songError(){
console.log('There was some kind of error fetching your artist ;(');
}
function getTopSong(p_id){
https.get('https://api.spotify.com/v1/artists/'+p_id+'/top-tracks?country=BR', function(res){
res.on("data", function(chunk){
var json = JSON.parse(chunk.toString('utf8'));
console.log(json);
});
});
}
function getArtistID(p_name) {
https.get('https://api.spotify.com/v1/search?q='+encodeURI(p_name)+'&type=artist', function(res){
res.on("data", function(chunk) {
var json = JSON.parse(chunk.toString('utf8'));
if(json['artists']['items'][0]['id'] != undefined || json['artists']['items'][0]['id'] != null){
console.log('id: ',json['artists']['items'][0]['id']);
getTopSong(json['artists']['items'][0]['id']);
}else
{
songError();
}
});
});
}
getArtistID("rage against the machine");
There seems to be an error in line 329:
undefined:329
"available_markets" : [ "AR", "AU", "AT", "BE", "BO", "BR", "BG", "CA", "CL", "CO", "CR", "CY", "CZ", "DK", "DO", "DE", "EC", "EE", "SV", "FI", "FR", "GR", "
My question is, am I doing something wrong or is it really broken?
Thanks!
I could curl it without any problems at least:
$ curl -s 'https://api.spotify.com/v1/artists/2d0hyoQ5ynDBnkvAbJKORj/top-tracks?country=BR' | python -mjson.tool | tail
"id": "25CbtOzU8Pn17SAaXFjIR3",
"name": "Take The Power Back - Remastered",
"popularity": 58,
"preview_url": "https://p.scdn.co/mp3-preview/b44e8f96a219871587d0559970ca5dce71c891f2",
"track_number": 3,
"type": "track",
"uri": "spotify:track:25CbtOzU8Pn17SAaXFjIR3"
}
]
}
I don't know much about nodejs, but don't you need to concatenate all callbacks to res.on("data"?
https://nodejs.org/api/http.html#http_http_request_options_callback
https.get('https://api.spotify.com/v1/artists/' + p_id + '/top-tracks?country=BR', function(res) {
var body = [];
res.on("data", function(chunk) {
body.push(chunk);
});
res.on("end", function() {
var json = JSON.parse(Buffer.concat(body).toString("utf8"));
console.log(json);
});
});
If the response is long and Spotify's servers decides to send the response back chunked transfer encoding, then the nodejs http module probably splits the response up as well.

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);
}

Use JSON data coming from WebApi in AngularJS application

I get some data from a WebApi, the answer (below the code to get the datas) is in JSON. But I can't access this result from angularJS. The datas look like :
{
"$id": "1",
"result": [
{
"$id": "2",
"name": "Français",
"code": "FR",
"id": 1
},
{
"$id": "3",
"name": "Néerlandais",
"code": "NL",
"id": 2
},
{
"$id": "4",
"name": "English",
"code": "EN",
"id": 3
}
]
}
But I get the error below when I try to display the result :
data.result is undefined
I get the data like this :
(function () {
angular.module('myApp')
.factory('dataService', ['$q', '$http', dataService]);
function dataService($q, $http) {
return {
initFormCustomer: initFormCustomer
};
function initFormCustomer() {
return $http({
method: 'GET',
url: 'http://localhost:123456/api/forminit/customer/',
headers: {
},
transformResponse: transformCustomer,
cache: true
})
.then(sendResponseData)
.catch(sendGetCustomerError)
}
function sendResponseData(response) {
return response.data;
}
function transformCustomer(data, headersGetter) {
var transformed = angular.fromJson(data.result);
console.log(data.result[0]);
return transformed;
}
function sendGetCustomerError(response) {
return $q.reject('Error retrieving customer(s). (HTTP status: ' + response.status + ')');
}
}
}());
The controller :
(function () {
angular.module('myApp')
.controller('customerController', ['$location', '$scope', 'dataService', CustomerController]);
function CustomerController($location, $scope, dataService) {
var vm = this;
vm.languages = dataService.initFormCustomer();
}
}());
I think the transform function gets a json string that you have to deserialize before using it as an object... try sth like:
function transformCustomer(data, headersGetter) {
var transformed = angular.fromJson(data);
console.log(transformed.result[0]);
return transformed.result;
}
Additionally you may look at the docs https://docs.angularjs.org/api/ng/service/$http . There is some code showing how to append a transform to the default one (that do the deserialization and XSRF checks)