Suitelet redirect to record - netsuite

I have a suitelet script that creates a csv format file from the line-items of Opportunity. on Opportunity created a 'Export CSV' button which calls this suitelet.
var fileObj = file.create({
name: 'transactions.csv',
fileType: file.Type.CSV,
contents: data,
description: 'This is transactions',
folder: 13497862
});
var Fileid = fileObj.save();
var loadFile = file.load({ id: Fileid });
var fileurl = loadFile.url;
var html = "";
html += "<html>";
html += "<script>";
html += 'window.location.href="' + fileurl + '";\n';
html += "</script>";
html += "</html>";
response.write(html);
After response.write executes, the file gets downloaded in computer. but after that I want it to redirect again to the Opportunity. But its returning a blank screen.
I used redirect.toRecord() but it is not executing because response.write(html) executes first and script stops there.

You can try forcing the browser to download the file and then redirect to the opportunity record.
var html = '';
html += '<html>'
'<script>' +
'var a = document.createElement('a');' +
'a.href = "' + fileurl + '";' +
'a.download = "' + fileurl + '";'
'document.body.appendChild(a);' +
'a.click();'; +
'setTimeout(function(){' +
' window.location.href = "REDIRECT_URL";' +
'}, 5000);' +
'</script>' +
'</html>';
response.write(html);
However, this solution may not always bring the exact same results on all browsers. A client script could be more appropriate for your requirement.

Related

sharepoint - starting workflow jsom script works on premise but fails online?

I have a piece of javascript code starting a workflow.
It all works on my on premise dev machine.
But as soon as I try to run it on an online site, it fails.
It is based on the workflow.asmx web service, and I get error 500 - value does not fall on expected range...
I suspect this is in the workflow parameters. But I cannot see what exactly. The user login differs but it is compliant with oneline format...
Any idea about any possible differences between on premise vs online that might explain this?
just in case, here's my code (again, perfectly fine onpremise):
function StartMyWorkflow(listGUID, itemId) {
var wfDefinitionId = "{9279E1FF-1D32-4423-85B7-C7F21998A701}";
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getById(listGUID);
var item = list.getItemById(itemId);
var currentUser = web.get_currentUser();
ctx.load(web);
ctx.load(item);
ctx.load(currentUser);
ctx.executeQueryAsync(
Function.createDelegate(this, function () {
var login = currentUser.get_loginName();
var name = currentUser.get_title();
var xml = getWFAssocData(name, login);
var fileRef = "https://" + location.host + item.get_item("FileRef");
$().SPServices({
operation: "StartWorkflow",
item: fileRef,
templateId: wfDefinitionId,
workflowParameters: xml,
completefunc: function () {
SP.UI.Notify.addNotification('workflow started', false);
}
});
}),
function (s, a) { console.error(a.get_message());}
);
}
function getWFAssocData(name, login) {
var assocData = '<dfs:myFields xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:dms="http://schemas.microsoft.com/office/2009/documentManagement/types" xmlns:dfs="http://schemas.microsoft.com/office/infopath/2003/dataFormSolution" xmlns:q="http://schemas.microsoft.com/office/infopath/2009/WSSList/queryFields" xmlns:d="http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields" xmlns:ma="http://schemas.microsoft.com/office/2009/metadata/properties/metaAttributes" xmlns:pc="http://schemas.microsoft.com/office/infopath/2007/PartnerControls" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">' +
'<dfs:queryFields></dfs:queryFields>' +
'<dfs:dataFields>' +
'<d:SharePointListItem_RW>' +
'<d:Approvers>' +
'<d:Assignment>' +
'<d:Assignee>' +
'<pc:Person><pc:DisplayName>' + name + '</pc:DisplayName><pc:AccountId>' + login + '</pc:AccountId><pc:AccountType>User</pc:AccountType></pc:Person>' +
'</d:Assignee>' +
'<d:Stage xsi:nil="true" />' +
'<d:AssignmentType>Serial</d:AssignmentType>' +
'</d:Assignment>' +
'</d:Approvers>' +
'<d:ExpandGroups>true</d:ExpandGroups>' +
'<d:NotificationMessage>Please approve test</d:NotificationMessage>' +
'<d:DueDateforAllTasks xsi:nil="true" /><d:DurationforSerialTasks xsi:nil="true" />' +
'<d:DurationUnits>Day</d:DurationUnits>' +
'<d:CC />' +
'<d:CancelonRejection>true</d:CancelonRejection>' +
'<d:CancelonChange>false</d:CancelonChange>' +
'<d:EnableContentApproval>false</d:EnableContentApproval>' +
'</d:SharePointListItem_RW>' +
'</dfs:dataFields>' +
'</dfs:myFields>';
return assocData;
}
It turns out to be as silly as obvious. I was just missing a 's' in the fileRef url... I've corrected the above script, so it's actually fully functional.

Remove all but the text written by user

I use Outlook API to fetch the sent email's body. Now, I want to clean the body to remove all links, headers, etc. and keep only the text written by user. Following is my regex function:
function getRegex() {
var regex1 = /^(?=.*Forwarded message)[^]*/m;
var regex2 = /^(?=.*From: )[^]*/m;
var regex3 = /^(?=.*On )[^]*/m;
var regex4 = /^(?=.*http)[^]*/m;
return new RegExp("(" + regex1.source + ")|(" + regex2.source + ")|(" + regex3.source + ")|(" + regex4.source + ")");
}
Following is function to fetch sent emails from Outlook:
outlook.mail.getMessages({
token: token.token.access_token,
odataParams: queryParams,
folderId: 'SentItems'
}, function (err, result) {
if (err){
console.log(err);
return;
}
var mail_array = result.value;
var outlook_sent_emails = '';
mail_array.forEach(function (mail) {
if (mail.BodyPreview !== '') {
outlook_sent_emails += (mail.BodyPreview + " ");
}
});
console.log(outlook_sent_emails.replace(getRegex(), "")); //This is not working
});
This line console.log(outlook_sent_emails.replace(getRegex(), "")); shows I am still getting all links, headers, etc.
The same regex is working elsewhere in my code.
EDITED:
Sample Text:
From: <Name>
Sent: <Datetime>
To: <Name>
Subj Dear Sir/Madam
Hi Vaibhav,
Hope you are doing well.
http://developer.android.com/sdk/index.html
Sent from my Windows 10 phone
I want to remove all kinds of links and text like as follows from the string:
From: <Name>
Sent: <Datetime>
To: <Name>
Subj Dear Sir/Madam
EXPECTED OUTPUT:
Hi Vaibhav,
Hope you are doing well.
UPDATE: added http
You may try this:
^.*(From:|Sent:|Sent\s+From|To:|Subj|Dear\s+(Sir|Madam)|http).*$
and replace by ""
Demo
const regex = /^.*(From:|Sent:|Sent\s+From|To:|Subj|Dear\s+(Sir|Madam)|http).*$/gmi;
const str = ` From: <Name>
Sent: <Datetime>
To: <Name>
Subj Dear Sir/Madam
Hi Vaibhav,
Hope you are doing well.
http://developer.android.com/sdk/index.html
Sent from my Windows 10 phone`;
const subst = ``;
const result = str.replace(regex, subst).trim();
console.log(result);

How to create csv or Excel file using javascript in Cordova android app

I am trying to create android app using phoneGap. I have written code for creating csv file in javascript ,which works fine on browser,but its not working in mobile app created using cordova.Everything other than file creation works fine in cordova app.Pl. guide
I have used following permissions in manifest,
Code for creating csv file:-
var link = document.getElementById("dataLink");
var csv = "";
//we should have the same amount of name/cookie fields
var name = "testdata1";
var cookies = "testdata2",
csv = csv + ""+ name + "," + cookies + "\n";
console.log("csv-"+csv);
$("#dataLink").attr("href", 'data:Application/octet-stream,' + encodeURIComponent(csv))[0].click();
You will need to use the File Plugin of Crodova to write file to the file system as different Operating System have only certain directories accessible to the Application to read/write.
The code to create the file object and writing will look something like this
window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(dir) {
console.log("got main dir", dir);
dir.getFile("myfile.csv", {
create: true
}, function(file) {
console.log("got the file", file);
logOb = file;
var csv = "";
//we should have the same amount of name/cookie fields
var name = "testdata1";
var cookies = "testdata2",
csv = csv + "" + name + "," + cookies + "\n";
console.log("csv-" + csv);
writeLog(csv);
});
});
function writeLog(str) {
if (!logOb) return;
logOb.createWriter(function(fileWriter) {
fileWriter.seek(fileWriter.length);
var blob = new Blob([str], {
type: 'text/plain'
});
fileWriter.write(blob);
console.log("ok, in theory i worked");
}, fail);
}
You can refer to this tutorial to better understand the process of file writing.

Docusign API - request for signature using Template

I am trying to test the REST API for request a signature on a document referenced through a template using C# in a WCF webservice.
The Step 1 for Login works & returns the accountID & baseURl;
The Step 2 fails with a Bad Request.
Here is my code:
try {
...
string requestBody = "<envelopeDefinition xmlns=\"http://www.docusign.com/restapi\">" +
"<accountId>" + accountId + "</accountId>" +
"<status>" + "sent" + "</status>" +
"<emailSubject>" + "API Call for Embedded Sending" + "</emailSubject>" +
"<emailBlurb>" + "This comes from C#" + "</emailBlurb>" +
"<templateId>" + "9A535489-0FB6-42B2-82C1-A06DA36025B4" + "</templateId>" +
"<templateRoles>" +
"<email>" + "abc#gmail.com" + "</email>" + // NOTE: Use different email address if username provided in non-email format!
"<name>" + "GRAVITY1003" + "</name>" + // username can be in email format or an actual ID string
"<roleName>" + "GRAVITY1003" + "</roleName>" +
"</templateRoles>" +
"</envelopeDefinition>";
// append "/envelopes" to baseUrl and use in the request
request = (HttpWebRequest)WebRequest.Create(baseURL + "/envelopes");
request.Headers.Add("X-DocuSign-Authentication", authenticateStr);
request.ContentType = "application/xml";
request.Accept = "application/xml";
request.ContentLength = requestBody.Length;
request.Method = "POST";
// write the body of the request
byte[] body = System.Text.Encoding.UTF8.GetBytes(requestBody);
Stream dataStream = request.GetRequestStream();
dataStream.Write(body, 0, requestBody.Length);
dataStream.Close();
// read the response
webResponse = (HttpWebResponse)request.GetResponse();------> It fails here
sr = new StreamReader(webResponse.GetResponseStream());
responseText = sr.ReadToEnd();
uri = responseText;
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
Console.WriteLine(text);
}
}
}
Can anyone tell me what I am doing wrong ? I looked at the API walkthrough's & coded this accordingly. Not sure why this is happening.
Looks like there was a bug in the Gist you were working off of, the wrong version was mistakenly uploaded. The Gist has been fixed, the issue was just one xml node that was missing.
Since you can have multiple template roles on a given template, there needs to be an extra xml node that separates each role. What you need to do is add singular <templateRole></templateRole> xml nodes in between the <templateRoles></templateRoles> nodes.
So your request body should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<envelopeDefinition xmlns="http://www.docusign.com/restapi">
<accountId>123456</accountId>
<status>sent</status>
<emailSubject>API Call for sending signature request from template</emailSubject>
<emailBlurb>This comes from Java</emailBlurb>
<templateId>EA64D446-3BFA-*********************</templateId>
<templateRoles>
<templateRole>
<email>recipient_email_address</email>
<name>recipient_name</name>
<roleName>template_role_name</roleName>
</templateRole>
</templateRoles>
</envelopeDefinition>

How to get the favorites from flickr

I am working on Node.js to get the list of favorites photos from a user in flickr, I know there is other method to get the public list of favorites, and that one works fine to me, but using this the flickr API return me this error.
{"stat":"fail", "code":98, "message":"Invalid auth token"}
This is my code:
var util = require('util'),
http = require('http'),
keys = require(__dirname + '/../oauth/flickrKeys'),
utilities = require(__dirname + '/Utilities');
var getPhotos = function(userInfo, callback) {
var requestResponse,
parameters,
requestPoint,
url,
toHash,
secretKey,
api_signature,
method = "flickr.favorites.getList",
format = "json";
requestPoint = 'http://api.flickr.com/services/rest/';
url = requestPoint
+ '?api_key=' + keys.clave
+ '&auth_token=' + userInfo.oauth_token
+ '&format=' + format
+ '&method=' + method
+ '&min_fave_date=' + userInfo.min_fave_date
+ '&nojsoncallback=1'
+ '&user_id=' + encodeURIComponent(userInfo.user_nsid);
parameters = 'api_key=' + keys.clave
+ '&auth_token=' + userInfo.oauth_token
+ '&format=' + format
+ '&method=' + method
+ '&min_fave_date=' + userInfo.min_fave_date
+ '&nojsoncallback=1'
+ '&user_id=' + encodeURIComponent(userInfo.user_nsid);
toHash = 'GET&'
+ encodeURIComponent(requestPoint) + '&'
+ encodeURIComponent(parameters);
// coding hash.
secretKey = keys.secreto + "&" + userInfo.oauth_token_secret;
api_signature = utilities.generateFlickrSignatureHex(toHash, secretKey);
// adding api signature to the url.
url = url + '&api_sig=' + encodeURIComponent(api_signature);
http.get(url, function(res) {});
}
at the below line
url = requestPoint
+ '?api_key=' + keys.clave
+ '&auth_token=' + userInfo.oauth_token
+ '&format=' + format
+ '&method=' + method
+ '&min_fave_date=' + userInfo.min_fave_date
+ '&nojsoncallback=1'
+ '&user_id=' + encodeURIComponent(userInfo.user_nsid);
i think you haven't initialized userInfo object before this, which causes the mentioned authentication error related to userInfo.oauth_token
updated to question edit
make sure userInfo has a oauth_token attribute before calling the api.just like you can wrap the api call inside a check like
if(typeof(userInfo)!="undefined" && typeof(userInfo.oauth_token)!="undefined" && userInfo.oauth_token!="") {
//code for api call
}

Resources