XMLHttpRequest Post in Razor Pages - xmlhttprequest

can some one look at the code and tell me, what Am i doing wrong here? At send, I am getting 400 error.Method downlaodPDF is not even hit.Here is my code.
$('#downloadPDF').on('click', function () {
var token = $("input[name='__RequestVerificationToken']").val();
var vehicle = { "fname": "henry", "lname": "ford" };
var dataJson = JSON.stringify(vehicle);
var req = new XMLHttpRequest();
req.open("POST", "/Test?handler=DownloadPDF");
req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
req.send(dataJson);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Report_" + new Date() + ".pdf";
link.click(); };
});
public void OnPostDownloadPDF([FromBody]ReportInput input)
{
//My code here
HttpContext.JsReportFeature().Recipe(Recipe.ChromePdf);
}

Related

Getting "spc message cannot be null" as response

Getting "spc message cannot be null" as response every time while providing implementation of Shaka player to play fairplay content on safari browser.Tried many ways to provide spc message in body and header also and we are actually sending it that i can see in network tab nut still cant find a solution. Here is the code below.
if (this.platform.getBrowserPlatform() === Constants.PLATFORMS.SAFARI_WEB) {
this.shakaPlayer.configure({
drm: {
servers: {
'com.apple.fps.1_0': `${this.config.baseUrl}${Constants.DRM_FAIRPLAY_LICENSE}`,
},
advanced: {
'com.apple.fps.1_0': {
serverCertificate: cert,
},
},
},
});
let that = this //,licenseUri;
this.shakaPlayer.configure('drm.initDataTransform', (initData) => {
const skdUri = shaka.util.StringUtils.fromBytesAutoDetect(initData);
var contentId = skdUri.substring(skdUri.indexOf('skd://') + 6);
// licenseUri = skdUri.replace('skd://', 'https://');
const url = new URL(contentId);
const urlParams = new URLSearchParams(url.search);
const cert = that.shakaPlayer.drmInfo().serverCertificate;
let id = urlParams.get('contentId');
that.id = id;
return shaka.util.FairPlayUtils.initDataTransform(initData, id, cert);
// let skdUrl = shaka.util.StringUtils.fromBytesAutoDetect(initData);
// licenseUri = skdUrl.replace('skd://', 'https://');
// const cert = that.shakaPlayer.drmInfo().serverCertificate;
// return shaka.util.FairPlayUtils.initDataTransform(initData, licenseUri, cert);
});
this.shakaPlayer.getNetworkingEngine().registerRequestFilter((type, request) => {
if (type != shaka.net.NetworkingEngine.RequestType.LICENSE) {
return;
}
let token = localStorage.getItem('auth');
let testToken = JSON.parse(token);
const originalPayload = new Uint8Array(request.body);
const base64Payload = shaka.util.Uint8ArrayUtils.toBase64(originalPayload);
const params = `{ "spc": "${base64Payload}", "assetId":"${that.id}"}`;
request.body = shaka.util.StringUtils.toUTF8(params);
request.headers['Content-Type'] = 'application/json';
request.headers['Authorization'] = `JWT ${testToken.access_token}`
console.log("request.body", request.body)
});
this.shakaPlayer.getNetworkingEngine().registerResponseFilter((type, response) => {
if (type != shaka.net.NetworkingEngine.RequestType.LICENSE) {
return;
}
console.log("license passed")
let responseText = shaka.util.StringUtils.fromUTF8(response.data);
responseText = responseText.trim();
if (responseText.substr(0, 5) === '<ckc>' &&
responseText.substr(-6) === '</ckc>') {
responseText = responseText.slice(5, -6);
}
response.data = shaka.util.Uint8ArrayUtils.fromBase64(responseText).buffer;
});
this.shakaPlayer.load(this.getProgramUrl(channel, program, restart)).then(() => {
console.log('1', this.shakaPlayer.isTextTrackVisible());
console.log('2', this.shakaPlayer.getTextTracks());
console.log('3', this.shakaPlayer.getTextLanguages());
}).catch((error) => {
console.log(error);
});
Smooth play of fairplay content on safari or some advise what can i do in this case

How to pass pdf file to Controller that requires IFormFile

I've been working on this the whole day and did my research already, I can't seem to find a solution anywhere. I have this function that calls a List in my controller, the List needs a IFormFile parameter,
here's my javascript method
function fileUploader_uploaded(e) {
const file = e.file;
const fileReader = new FileReader();
fileReader.onload = function () {
toggleDropZoneActive($("#dropzone-external")[0], false);
$("#dropzone-item")[0].data = fileReader.result;
}
fileReader.readAsDataURL(file);
const _fileReader = new FileReader();
var r = _fileReader.readAsBinaryString(file);
$("#dropzone-text")[0].style.display = "none";
$.ajax({
url: '#Url.Action("_Index", "FileUploader")',
data: { CFile: r}, // I'm trying to pass the pdf file here
cache: false,
success: function (data) {
console.log(data);
}
});
}
and this is my List in controller
public object _Index(IFormFile CFile)
{
if (CFile != null)
{
try
{
string documentText = "";
using PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor();
documentProcessor.LoadDocument(CFile.OpenReadStream());
documentText = documentProcessor.Text;
string word = #"([0-9]+.[0-9]+-[0-9]+)";
Regex regex = new Regex(word);
foreach (Match match in regex.Matches(documentText))
{
sectionsList.Add(match.Value.ToString());
}
}
catch
{
Response.StatusCode = 400;
}
}
else
{
_logger.LogInformation("empty");
}
return sectionsList;
}
the CFile is always empty i tried different ways already like passing
data: { CFile: e.file}
Does anyone else have idea?
From this code data: { CFile: e.file}, you post it as the string, so it can not be recognized as a file. You need to use FormData and change the contentType.
function fileUploader_uploaded(e) {
const file = e.file;
const fileReader = new FileReader();
fileReader.onload = function () {
toggleDropZoneActive($("#dropzone-external")[0], false);
$("#dropzone-item")[0].data = fileReader.result;
}
fileReader.readAsDataURL(file);
const _fileReader = new FileReader();
var r = _fileReader.readAsBinaryString(file);
$("#dropzone-text")[0].style.display = "none";
//----------edit here---------
var form = new FormData()
form.append('CFile', file)
$.ajax({
url: '#Url.Action("_Index", "FileUploader")',
method:'post',
data: form,
cache: false,
contentType: false,
processData: false,
success: function (data) {
}
});
}
The bakend should add [FromForm].
[HttpPost]
public object _Index([FromForm]IFormFile CFile)

Pagination for Google Apps Script with Shopify API

I am running into a bit of a snag setting up pagination in Google Apps Script. I am trying to use it for Shopify API. Reference links attached.
I attached the code below of what I have so far -
trying to figure out how to use the "While" statement to make it check if there is a Next Page URL
trying to figure out a way to parse the Link in the header. Example below. On pages 2+ there will be a next and previous link. We only need the next
https://shop-domain.myshopify.com/admin/api/2019-07/products.json?limit=50&page_info=eyJkaXJlY3Rpb24iOiJwcmV2IiwibGFzdF9pZCI6MTk4NTgyMTYzNCwibGFzdF92YWx1ZSI6IkFjcm9saXRoaWMgQWx1bWludW0gUGVuY2lsIn0%3D; rel="previous", https://shop-domain.myshopify.com/admin/api/2019-07/products.json?limit=50&page_info=eyJkaXJlY3Rpb24iOiJuZXh0IiwibGFzdF9pZCI6MTk4NTgzNjU0NiwibGFzdF92YWx1ZSI6IkFoaXN0b3JpY2FsIFZpbnlsIEtleWJvYXJkIn0%3D; rel="next
function callShopifyOrderCount() {
var accessToken = 'xxxx';
var store_url = 'https://xxxx.myshopify.com/admin/api/2021-01/orders.json?status=any&fields=created_at,id,name,total-price&limit=20';
var headers = {
"Content-Type": "application/json",
'X-Shopify-Access-Token': accessToken
};
var options = {
"method": "GET",
"headers": headers,
"contentType": "application/json",
"muteHttpExceptions": true,
}
var response = UrlFetchApp.fetch(store_url, options)
// Call the link header for next page
var header = response.getHeaders()
var linkHeader = header.Link;
var responseCode = response.getResponseCode();
var responseBody = response.getContentText();
if (responseCode === 200) {
var responseJson = JSON.parse(responseBody);
var objectLength = responseJson.orders.length;
for (var i = 0; i < objectLength; i++) {
var orderId = responseJson.orders[i].id;
var orderPrice = responseJson.orders[i].total_price;
var orderName = responseJson.orders[i].name;
}
} else {
Logger.log(
Utilities.formatString(
"First Request failed. Expected 200, got %d: %s",
responseCode,
responseBody
)
);
// ...
}
// *** NEED TO FIGURE OUT WHILE STATEMENT //
while (Link != null) {
var store_url = linkHeader;
var response = UrlFetchApp.fetch(store_url, options)
var responseCode = response.getResponseCode();
var responseBody = response.getContentText();
var header = response.getHeaders()
var linkHeader = header.Link;
if (responseCode === 200) {
var responseJson = JSON.parse(responseBody);
var objectLength = responseJson.orders.length;
for (var i = 0; i < tweetLength; i++) {
var orderId = responseJson.orders[i].id;
var orderPrice = responseJson.orders[i].total_price;
var orderName = responseJson.orders[i].name;
}
}
else {
Logger.log(
Utilities.formatString(
"Second Request failed. Expected 200, got %d: %s",
responseCode,
responseBody
)
);
}
}
}
References:
https://shopify.dev/tutorials/make-paginated-requests-to-rest-admin-api
https://www.shopify.com/partners/blog/relative-pagination

Custom Authentication Azure Mobile Services by Api

I am creating a custom authentication via API on Azure Mobile Service, and picked based on this answer:
Registering and login users in Azure Mobile Services
Then joined with the code of the previous link to create the authentication token.
But I get "internal server error" when I invoke the API. The error happens in here: "...results.length..."
var crypto = require('crypto');
var iterations = 1000;
var bytes = 32;
var aud = "Custom";
var masterKey = "wkeHEoWUaPJSHsSOcWgmVLOZbIpeeg92";
var _request;
var _response;
exports.post = function(request, response) {
var user = request.body.userName;
var pass = request.body.password;
_request = request;
_response = response
validateUserNamePassword(user, pass, function(error, userId, token) {
if (error) {
response.send(401, { error: "Unauthorized" });
} else {
response.send(200, { user: userId, token: token });
}
});
}
function validateUserNamePassword(user, pass, funcao){
var accounts = _request.service.tables.getTable('account');
accounts
.where({ userid : user })
.read({
success: function(results)
{
if (results.length === 0)
{
_response.send(401, { error: "Unauthorized1" });
console.log("Incorrect username or password");
_request.respond(401, "Incorrect username or password");
}
else
_response.send(401, { error: "Unauthorized2" });
var account = results[0];
hash(item.password, account.salt, function(err, h) {
var incoming = h;
if (slowEquals(incoming, account.password)) {
var expiry = new Date().setUTCDate(new Date().getUTCDate() + 30);
var userId = aud + ":" + account.id;
_request.respond(200, {
userId: userId,
token: zumoJwt(expiry, aud, userId, masterKey)
});
}
else {
_request.respond(401, "Incorrect username or password");
}
});
}
}
});
}
function hash(text, salt, callback) {
crypto.pbkdf2(text, salt, iterations, bytes, function(err, derivedKey){
if (err) { callback(err); }
else {
var h = new Buffer(derivedKey).toString('base64');
callback(null, h);
}
});
}
function slowEquals(a, b) {
var diff = a.length ^ b.length;
for (var i = 0; i < a.length && i < b.length; i++) {
diff |= (a[i] ^ b[i]);
}
return diff === 0;
}
function zumoJwt(expiryDate, aud, userId, masterKey) {
var crypto = require('crypto');
function base64(input) {
return new Buffer(input, 'utf8').toString('base64');
}
function urlFriendly(b64) {
return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(new RegExp("=", "g"), '');
}
function signature(input) {
var key = crypto.createHash('sha256').update(masterKey + "JWTSig").digest('binary');
var str = crypto.createHmac('sha256', key).update(input).digest('base64');
return urlFriendly(str);
}
var s1 = '{"alg":"HS256","typ":"JWT","kid":0}';
var j2 = {
"exp":expiryDate.valueOf() / 1000,
"iss":"urn:microsoft:windows-azure:zumo",
"ver":1,
"aud":aud,
"uid":userId
};
var s2 = JSON.stringify(j2);
var b1 = urlFriendly(base64(s1));
var b2 = urlFriendly(base64(s2));
var b3 = signature(b1 + "." + b2);
return [b1,b2,b3].join(".");
}
I'm invoking like this:
try
{
var loginInput = new JObject();
loginInput.Add("userName", "breno");
loginInput.Add("password", "test");
var loginResult = await LoginAuthenticationService.InvokeApiAsync("login", loginInput);
LoginAuthenticationService.CurrentUser = new MobileServiceUser((string)loginResult["user"]);
LoginAuthenticationService.CurrentUser.MobileServiceAuthenticationToken = (string)loginResult["token"];
}
catch (MobileServiceInvalidOperationException e)
{
var exception = e;
}
If you're getting this error "Failed to load script file 'login.js': SyntaxError: Unexpected token }" as seen in the comments, there is a syntax issue with your script. You'll need to go through your scripts and figure out where the issue is at.

google maps api v2 map.removeOverlay() marker array issue

To start off with, I would like to say that I have been looking on the internet for a really long time and have been unable to find the answer, hence my question here.
My latest school project is to create an admin page for adding articles to a database, the articles are connected to a point on a google map. The requirement for adding the point on the map is that the user is able to click the map once and the marker is produced, if the map is clicked a second time the first marker is moved to the second location. (this is what I am struggling with.)
The problem is, as the code is now, I get the error that markersArray is undefined. If I place the var markersArray = new Array; underneath the eventListener then I get an error that there is something wrong the main.js (googles file) and markersArray[0] is undefined in the second if.
By the way, I have to use google maps API v2, even though it is old.
<script type="text/javascript">
//<![CDATA[
var map;
var markers = new Array;
function load() {
if (GBrowserIsCompatible()) {
this.counter = 0;
this.map = new GMap2(document.getElementById("map"));
this.map.addControl(new GSmallMapControl());
this.map.addControl(new GMapTypeControl());
this.map.setCenter(new GLatLng(57.668911, 15.203247), 7);
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var Articles = xml.documentElement.getElementsByTagName("article");
for (var i = 0; i < Articles.length; i++) {
var id = Articles[i].getAttribute("id");
var title = Articles[i].getAttribute("title");
var text = Articles[i].getAttribute("text");
var searchWord = Articles[i].getAttribute("searchWord");
var point = new GLatLng(parseFloat(Articles[i].getAttribute("lat")),
parseFloat(Articles[i].getAttribute("lng")));
var article = createMarker(point, id, title, text);
this.map.addOverlay(article);
}
});
}
var myEventListener = GEvent.bind(this.map,"click", this, function(overlay, latlng) {
if (this.counter == 0) {
if (latlng) {
var marker = new GMarker(latlng);
latlng1 = latlng;
this.map.addOverlay(marker);
this.counter++;
markers.push(marker); //This is where I get the error that markersArray is undefined.
}
}
else if (this.counter == 1) {
if (latlng){
alert (markers[0]);
this.map.removeOverlay(markers[0]);
var markers = [];
this.map.addOverlay(marker);
this.counter++;
}
}
});
}
function createMarker(point, id, title, text) {
var article = new GMarker(point);
var html = "<b>" + title + "</b> <br/>"
GEvent.addListener(article, 'click', function() {
window.location = "article.php?id=" + id;
});
return article;
}
I solved the problem. I'm not exactly sure why it worked but this is what it looks like now:
var markersArray = [];
function load() {
if (GBrowserIsCompatible()) {
this.counter = 0;
this.map = new GMap2(document.getElementById("map"));
this.map.addControl(new GSmallMapControl());
this.map.addControl(new GMapTypeControl());
this.map.setCenter(new GLatLng(57.668911, 15.203247), 7);
GDownloadUrl("genxml.php", function(data) {
var xml = GXml.parse(data);
var Articles = xml.documentElement.getElementsByTagName("article");
for (var i = 0; i < Articles.length; i++) {
var id = Articles[i].getAttribute("id");
var title = Articles[i].getAttribute("title");
var text = Articles[i].getAttribute("text");
var searchWord = Articles[i].getAttribute("searchWord");
var type = Articles[i].getAttribute("type");
var point = new GLatLng(parseFloat(Articles[i].getAttribute("lat")),
parseFloat(Articles[i].getAttribute("lng")));
var article = createMarker(point, id, title, text);
this.map.addOverlay(article);
}
});
}
var myEventListener = GEvent.bind(this.map,"click", this, function(overlay, latlng) {
var marker = new GMarker(latlng);
if (this.counter == 0) {
if (latlng) {
latlng1 = latlng;
this.map.addOverlay(marker);
markersArray.push(marker);
this.counter++;
}
}
else if (this.counter == 1) {
if (latlng){
this.map.removeOverlay(markersArray[0]);
this.map.addOverlay(marker);
this.counter++;
}
}
});
}
function createMarker(point, id, title, text) {
var article = new GMarker(point);
var html = "<b>" + title + "</b> <br/>"
GEvent.addListener(article, 'click', function() {
window.location = "article.php?id=" + id;
});
return article;
}