IE crossdomain filter on flex application - flex3

I have an application that uses a flex form to capture user input. When the user has entered the form data (which includes a drawing area) the application creates a jpg image of the form and sends back to the server. Since the data is sensitive, it has to use https. Also, the client requires both jpg and pdf versions of the form to be stored on the server.
The application sends data back in three steps
1 - send the jpg snapshot with ordernumber
2 - send the form data fields as post data so it is not visible in the address bar
3 - send the pdf data
I am sending the jpg data first using urlloader and waiting for the server to respond before performing opperation 2 and 3 to ensure that the server has created the record associated with the new orderNumber.
This code works fine in IE over http. But If I try to use the application over https, IE blocks the page response from store jpg step and the complete event of the urlloader never fires. The application works fine in FireFox over http or https.
Here is the crossdomain.xml (I have replaced the domain with ""):
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*.<mydomain>.com" to-ports="*" secure="false"/>
<allow-http-request-headers-from domain="*.<mydomain>.com" headers="*">
</cross-domain-policy>
Here is the code that is executed when the user presses the submit button:
private function loaderCompleteHandler(event:Event):void {
sendPDF();
sendPatientData();
}
private function submitOrder(pEvt:MouseEvent):void
{
//disable submit form so the order can't be submitted twice
formIsValid = false;
waitVisible = true;
//submit the jpg image first with the order number, userID, provID
//and order type. The receiveing asp will create the new order record
//and save the jpg file. jpg MUST be sent first.
orderNum = userID + "." + provID + "." + Date().toString() + "." + orderType;
var jpgURL:String = "https://orders.mydomain.com/orderSubmit.asp?sub=jpg&userID=" + userID + "&provID=" + provID + "&oNum=" + orderNum + "&oType=" + orderType;
var jpgSource:BitmapData = new BitmapData (vbxPrint.width, vbxPrint.height);
jpgSource.draw(vbxPrint);
var jpgEncoder:JPEGEncoder = new JPEGEncoder(100);
var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
var header:URLRequestHeader = new URLRequestHeader ("content-type", "application/octet-stream");
//Make sure to use the correct path to jpg_encoder_download.php
var jpgURLRequest:URLRequest = new URLRequest (jpgURL);
jpgURLRequest.requestHeaders.push(header);
jpgURLRequest.method = URLRequestMethod.POST;
jpgURLRequest.data = jpgStream;
//navigateToURL(jpgURLRequest, "_blank");
var jpgURLLoader:URLLoader = new URLLoader();
try
{
jpgURLLoader.load(jpgURLRequest);
}
catch (error:ArgumentError)
{
trace("An ArgumentError has occurred.");
}
catch (error:SecurityError)
{
trace("A SecurityError has occurred.");
}
jpgURLLoader.addEventListener(Event.COMPLETE, loaderCompleteHandler);
}
private function sendPatientData ():void
{
var dataURL:String = "https://orders.mydomain.com/orderSubmit.asp?sub=data&oNum=" + orderNum + "&oType=" + orderType;
//Make sure to use the correct path to jpg_encoder_download.php
var dataURLRequest:URLRequest = new URLRequest (dataURL);
dataURLRequest.method = URLRequestMethod.POST;
var dataUrlVariables:URLVariables = new URLVariables();
dataUrlVariables.userID = userID
dataUrlVariables.provID = provID
dataUrlVariables.name = txtPatientName.text
dataUrlVariables.dob = txtDOB.text
dataUrlVariables.contact = txtPatientContact.text
dataUrlVariables.sex=txtSex.text
dataUrlVariables.ind=txtIndications.text
dataURLRequest.data = dataUrlVariables
navigateToURL(dataURLRequest, "_self");
}
private function sendPDF():void
{
var url:String = "https://orders.mydomain.com/pdfOrderForm.asp"
var fileName:String = "orderPDF.pdf&sub=pdf&oNum=" + orderNum + "&oType=" + orderType + "&f=2&t=1" + "&mid=" + ModuleID.toString()
var jpgSource:BitmapData = new BitmapData (vbxPrint.width, vbxPrint.height);
jpgSource.draw(vbxPrint);
var jpgEncoder:JPEGEncoder = new JPEGEncoder(100);
var jpgStream:ByteArray = jpgEncoder.encode(jpgSource);
myPDF = new PDF( Orientation.LANDSCAPE,Unit.INCHES,Size.LETTER);
myPDF.addPage();
myPDF.addImageStream(jpgStream,0,0, 0, 0, 1,ResizeMode.FIT_TO_PAGE );
myPDF.save(Method.REMOTE,url,Download.ATTACHMENT,fileName);
}
The target asp page is not sending back any data, except the basic site page template.
Can anyone help me figure out how to get around this IE crossdomain issue? I have turned off the XSS filter in IE tools security settings, but that still didn't solve the problem.
THANKS

Do everything over https. Load the swf from an https url. Send the initial form post via https. Send the images via https.

Related

PKCE flow Error code: 500 code challenge required

I'm trying to get the PKCE example to work, but I keep hitting
Error code: 500
Error: invalid_request : code challenge required
Here's a sample url, it does include a code_challenge param generated with the example code.
https://login.xero.com/identity/connect/authorize
?client_id=XXX
&response_type=code
&scope=openid%20profile%20email%20offline_access%20files%20accounting.transactions%20accounting.contacts&redirect_uri=https%3A%2F%2Flocalhost%3A5001%2F
&code_challenge=tj6n3SLd6FZ8g6jjSJYvfC--4r2PHGnpbSGTwIreNqQ
&code_challenge_method=S256
The registered app is a PKCE flow, kind of out of options what it could be.
Here's the code I use, the only changes are the last 2 lines where I launch the browser a I'm connecting from a desktop app. Tried pasting the generated url into the browser directly but that also didn't work.
XeroConfiguration xconfig = new XeroConfiguration();
xconfig.ClientId = "XXX";
xconfig.CallbackUri = new Uri("https://localhost:5001"); //default for standard webapi template
xconfig.Scope = "openid profile email offline_access files accounting.transactions accounting.contacts";
//xconfig.State = "YOUR_STATE"
var client = new XeroClient(xconfig);
// generate a random codeVerifier
var validChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~";
Random random = new Random();
int charsLength = random.Next(43, 128);
char[] randomChars = new char[charsLength];
for (int i = 0; i < charsLength; i++) {
randomChars[i] = validChars[random.Next(0, validChars.Length)];
}
string codeVerifier = new String(randomChars);
var uri = client.BuildLoginUriPkce(codeVerifier);
Clipboard.SetText(uri);
System.Diagnostics.Process.Start("explorer.exe", $"\"{uri}\"");

Convert PDF from Google Drive to Image and send to Telegram via Bot

Currently the step by step I use is as follows:
First step -> Create a PDF of the Page Jogos na TV from my spreadsheet:
function CreatePDF() {
var ss = SpreadsheetApp.getActive();
SpreadsheetApp.flush();
var theurl = 'https://docs.google.com/a/mydomain.org/spreadsheets/d/' +
'ID CODE TO SPREADSHEET' +
'/export?format=pdf' +
'&size=0' +
'&portrait=true' +
'&fitw=true' +
'&top_margin=0' +
'&bottom_margin=0' +
'&left_margin=0' +
'&right_margin=0' +
'&sheetnames=false&printtitle=false' +
'&pagenum=false' +
'&gridlines=false' +
'&fzr=FALSE' +
'&gid=' +
'ID CODE TO SPREADSHEET PAGE';
var token = ScriptApp.getOAuthToken();
var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' + token } });
var pdfBlob = docurl.getBlob();
//...get token and Blob (do not create the file);
var fileName = ss.getSheetByName("Jogos na TV").getRange("A1").getValue();
//Access or create the 'PDF' folder;
var folder;
var folders = DriveApp.getFoldersByName("PDF");
if(folders.hasNext()) {
folder = folders.next();
}else {
folder = DriveApp.createFolder("PDF");
}
//Remove duplicate file with the same name;
var existing = folder.getFilesByName(fileName);
if(existing.hasNext()) {
var duplicate = existing.next();
if (duplicate.getOwner().getEmail() == Session.getActiveUser().getEmail()) {
var durl = 'https://www.googleapis.com/drive/v3/files/'+duplicate.getId();
var dres = UrlFetchApp.fetch(durl,{
method: 'delete',
muteHttpExceptions: true,
headers: {'Authorization': 'Bearer '+token}
});
var status = dres.getResponseCode();
if (status >=400) {
} else if (status == 204) {
folder.createFile(pdfBlob.setName(fileName));
}
}
} else {
folder.createFile(pdfBlob.setName(fileName));
}
}
Second Step -> Manually copy the PDF link created in Google Drive
Step Three -> I send the text with the PDF minature to my group on Telegram:
function EnviarTelegram(botSecret, chatId, photoUrl, caption) {
var response = UrlFetchApp.fetch("https://api.telegram.org/bot" + botSecret + "/sendPhoto?caption=" + encodeURIComponent(caption) + "&photo=" + encodeURIComponent(photoUrl) + "&chat_id=" + chatId + "&parse_mode=HTML");
}
The current formula for sending to Telegram via spreadsheet:
=EnviarTelegram("botSecret","chatId","Url to PDF","Programação de jogos na TV
"&TEXT('Jogos Hoje'!B1,"DD/MM/YYYY")&" e "&TEXT('Jogos Amanhã'!B1,"DD/MM/YYYY"))
The thumbnail created for the PDF is cut so the image sent to Telegram is also cut and the spreadsheets cannot be saved as an image, just document or PDF.
Is there any way to automatically convert PDF to image and be able to send to Telegram?
Issue and workarounds:
Unfortunately, there are no methods for directly converting the PDF format to the image data in the methods of Google Apps Script. So, in this case, I thought that it is required to use the workarounds for achieving your goal.
Workaround 1:
In this workaround, the external API is used. When you want to directly convert the PDF data to an image data, how about using an external API? Ref
You can see the sample script for this at this thread.
Workaround 2:
In this workaround, the range of sheet is exported as an image. When I saw your Spreadsheet, it seems that the data range of a sheet in Google Spreadsheet is exported as a PDF data. From this situation, as the other workaround, how about converting the range of Spreadsheet to an image?
You can see the sample script for this at this thread.
Workaround 3:
In this workaround, the PDF data is sent with sendDocument. Ref In this case, it seems that the data is required to be sent as multipart/form-data. The sample script is as follows.
Sample script:
var url = "https://api.telegram.org/bot" + botSecret + "/sendDocument?chat_id=" + chatId;
var blob = DriveApp.getFileById("### file ID of PDF file ###").getBlob();
var res = UrlFetchApp.fetch(url, {method: "post", payload: {document: blob}});
console.log(res.getContentText())
References:
PDF to PNG API
sendDocument
Related threads.
Convert a gdoc into image
How to copy a range from a spreadsheet as an image to Google Slides?

Pentaho - upload file using API

I need to upload a file using an API.
I tried REST CLIENT and didn't find any options.
Tried with HTTP POST and that responded with 415.
Please suggest how to accomplish this
Error 415 is “Unsupported media type”.
You may need to change the media type of the request or check whether that type of file us accepted by the remote server.
https://en.m.wikipedia.org/wiki/List_of_HTTP_status_codes
This solution uses only standard classes of jre 7. Add a step Modified Java Script Value in your transformation. You will have to add two columns in the flow: URL_FORM_POST_MULTIPART_COLUMN and FILE_URL_COLUMN, you can add as many files as you want, you will just have to call outputStreamToRequestBody.write more times.
try
{
//in this step you will need to add two columns from the previous flow -> URL_FORM_POST_MULTIPART_COLUMN, FILE_URL_COLUMN
var serverUrl = new java.net.URL(URL_FORM_POST_MULTIPART_COLUMN);
var boundaryString = "999aaa000zzz09za";
var openBoundary = java.lang.String.format("\n\n--%s\nContent-Disposition: form-data\nContent-Type: text/xml\n\n" , boundaryString);
var closeBoundary = java.lang.String.format("\n\n--%s--\n", boundaryString);
// var netIPSocketAddress = java.net.InetSocketAddress("127.0.0.1", 8888);
// var proxy = java.net.Proxy(java.net.Proxy.Type.HTTP , netIPSocketAddress);
// var urlConnection = serverUrl.openConnection(proxy);
var urlConnection = serverUrl.openConnection();
urlConnection.setDoOutput(true); // Indicate that we want to write to the HTTP request body
urlConnection.setRequestMethod("POST");
//urlConnection.addRequestProperty("Authorization", "Basic " + Authorization);
urlConnection.addRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundaryString);
var outputStreamToRequestBody = urlConnection.getOutputStream();
outputStreamToRequestBody.write(openBoundary.getBytes(java.nio.charset.StandardCharsets.UTF_8));
outputStreamToRequestBody.write(java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(FILE_URL_COLUMN)));
outputStreamToRequestBody.write(closeBoundary.getBytes(java.nio.charset.StandardCharsets.UTF_8));
outputStreamToRequestBody.flush();
var httpResponseReader = new java.io.BufferedReader(new java.io.InputStreamReader(urlConnection.getInputStream()));
var lineRead = "";
var finalText = "";
while((lineRead = httpResponseReader.readLine()) != null) {
finalText += lineRead;
}
var status = urlConnection.getResponseCode();
var result = finalText;
var time = new Date();
}
catch(e)
{
Alert(e);
}
I solved this by using the solution from http://www.dietz-solutions.com/2017/06/pentaho-data-integration-multi-part.html
Thanks Ben.
He's written a Java class for Multi-part Form submission. I extendd by adding a header for Authorization...

How to show the custom PDF template while clicking the button

I want to show the PDF Template in new window while clicking the button in Sales Order. I created the button in sales order process using user event script. after that i'm unable to proceed it. It is possible to show the custom PDF template in new window while clicking the sales order?
My CODE:
USER EVENT SCRIPT:
// creating button in user event script before load event in view mode
unction userEventBeforeLoad(type, form, request){
if(type == 'view'){
var internalId = nlapiGetRecordId();
if (internalId != null) {
var createPdfUrl = nlapiResolveURL('SUITELET', 'customscript_back0rdered_itm_pdf', 'customdeploy_backord_itm_pdf_dep', false);
createPdfUrl += '&id=' + internalId;
//---add a button and call suitelet on click that button and it will open a new window
var addButton = form.addButton('custpage_printpdf', 'Print PDF', "window.open('" + createPdfUrl + "');");
}
else {
nlapiLogExecution('DEBUG', 'Error', 'Internaal id of the record is null');
}
}
}
SUITELET SCRIPT:
function suitelet(request, response){
var xml = "<?xml version=\"1.0\"?>\n<!DOCTYPE pdf PUBLIC \"-//big.faceless.org//report\" \"report-1.1.dtd\">\n";
xml += "<pdf>";
xml += "<head><macrolist><macro id=\"myfooter\"><p align=\"center\"><pagenumber /></p></macro></macrolist></head>";
xml += "<body size= \"A4\" footer=\"myfooter\" footer-height=\"0.5in\">";
var record = request.getParameter('internalId');
xml +="record"; //Add values(in string format) what you want to show in pdf
xml += "</body></pdf>";
var file = nlapiXMLToPDF(xml);
response.setContentType('PDF', 'Print.pdf ', 'inline');
response.write(file.getValue());
}
thanks in advance
The way I did it recently:
User Event Adds the Button that calls a suitelet (window.open('suitelet URL'))
Suitelet Renders the custom template
You can do the rendering like this insise a Suitelet (params: request, response), the custscript_pdf_template points to an html file on the cabinet using the NetSuite Advanced HTML syntax
var template = nlapiGetContext().getSetting('SCRIPT', 'custscript_pdf_template');
var purchaseOrder = nlapiLoadRecord('purchaseorder', tranId);
var xmlTemplate = nlapiLoadFile(template);
var renderer = nlapiCreateTemplateRenderer();
var file;
xmlTemplate = xmlTemplate.getValue();
renderer.setTemplate(xmlTemplate);
renderer.addRecord('record', purchaseOrder);
xmlTemplate = renderer.renderToString();
file = nlapiXMLToPDF(xmlTemplate);
resObj = file.getValue();
response.setContentType('PDF', 'printOut.pdf', 'inline');
response.write(resObj)

How to insert rule in Google Calendar ACL from Google Apps Script

How can I add a new user to the ACL for a Google Calendar? I'm trying to send a POST HTTP request. Perhaps there is something wrong with the XML? The code below generates a server error (400). (Edit: Shows the oAuth).
//---------------------------------------------------------------
// Add a rule to the Access Control List for 'Fake Calendar 1.0'
//---------------------------------------------------------------
function addRule() {
// Get Calendar ID, script user's email, and the API Key for access to Calendar API
var calId = '12345calendar.google.com';
var userEmail = Session.getActiveUser().getEmail();
var API_KEY = 'ABC123';
var newUserEmail = 'person#example.net';
// Get authorization to access the Google Calendar API
var apiName = 'calendar';
var scope = 'https://www.googleapis.com/auth/calendar';
var fetchArgs = googleOAuth_(apiName, scope);
fetchArgs.method = 'POST';
var rawXML = "<entry xmlns='http://www.w3.org/2005/Atom' " +
"xmlns:gAcl='http://schemas.google.com/acl/2007'>" +
"<category scheme='http://schemas.google.com/g/2005#kind' " +
"term='http://schemas.google.com/acl/2007#accessRule'/>" +
"<gAcl:role value='owner'/>" +
"<gAcl:scope type='user' value='"+userEmail+"'/>" +
"</entry>";
fetchArgs.payload = rawXML;
fetchArgs.contentType = 'application/atom+xml';
// Get the requested content (the ACL for the calendar)
var base = 'https://www.googleapis.com/calendar/v3/calendars/';
var url = base + calId + '/acl?key=' + API_KEY;
var content = UrlFetchApp.fetch(url, fetchArgs).getContentText();
Logger.log(content);
}
//--------------------------------------------------------------
// Google OAuth
//--------------------------------------------------------------
function googleOAuth_(name,scope) {
var oAuthConfig = UrlFetchApp.addOAuthService(name);
oAuthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope="+scope);
oAuthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oAuthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oAuthConfig.setConsumerKey("anonymous");
oAuthConfig.setConsumerSecret("anonymous");
return {oAuthServiceName:name, oAuthUseToken:"always"};
}
Have you gone through the oAuth authorization process before executing this piece of code. Your app has to be explicitly authorized before it can do anything significant with the Calendar API
Srik is right. You need to use oAuth Arguments in your UrlFetchApp.
Given Reference URL shows few examples for using oAuth in Apps script to work with Google's REST APIs
https://sites.google.com/site/appsscripttutorial/urlfetch-and-oauth