Anyone know how to proper use the nsIFilePicker ? - file

I am trying to copy a text file from one folder to another. Issue is once you select the folder to save to what is the proper code to get the file to copy to that folder? I and using NSI Filepicker modeOpen and modeSave and can't find any code on how to save file properly. the MDN is lacking code.
var dispdir = Components.classes["#mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("ProfD", Components.interfaces.nsIFile);
var nsIFilePicker = Components.interfaces.nsIFilePicker;
var fp = Components.classes["#mozilla.org/filepicker;1"]
.createInstance(nsIFilePicker);
fp.init(window, "Select a File", nsIFilePicker.modeOpen);
fp.appendFilters(nsIFilePicker.filterText);
fp.displayDirectory = dispdir;
var rv = fp.show();
if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnCancel) {
var file = fp.file;
var path = fp.file.path;
}
var savedir = Components.classes["#mozilla.org/file/directory_service;1"].
getService(Components.interfaces.nsIProperties).
get("ProfD", Components.interfaces.nsIFile);
savedir.append("Test Folder");
if( !savedir.exists() || !savedir.isDirectory() ) {
// if it doesn't exist,create
savedir.create(Components.interfaces.nsIFile.DIRECTORY_TYPE, 0777);
alert(savedir.path + "\n" + "Folder was made");
}
var fp2 = Components.classes["#mozilla.org/filepicker;1"]
.createInstance(nsIFilePicker);
fp2.init(window, "Save file to?", nsIFilePicker.modeSave);
fp2.appendFilters(nsIFilePicker.filterText);
fp2.displayDirectory = savedir;
fp2.defaultString = fp.file.leafName;
var rv = fp2.show();
if (rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace) {
}
var aDir = Components.classes["#mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
aDir.append(fp2.file.parent.path);
alert(fp2.file.parent.path)
fp.file.copyTo(aDir, null);
copyFile(fp.file.path);
alert(fp2.file.path + "\n" + "File copied successfuly!")

Use fp.file to create a stream, see
https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FO#Synchronous
I have a question for you though, where is 'window' from fp.init(window defined?

Related

How to replace Pipelet for ExportCustomerGroups in SFCC? (For removing Deprecated API usage)

function abc(){
var Site = require('dw/system/Site');
var utils= require('app_nars/cartridge/scripts/util/utils.js');
var mySite : String = (Site.getCurrent().getID() == "a") ? "" : "-" + Site.getCurrent().getID();
var customerGroupName : String ;
if (mySite == "A") {
customerGroupName = "A";
} else {
customerGroupName = "B";
}
var grpNam= utils.getGroup(customerGroupName);
var grpFileName = 'test';
/* No script api available for pipelet ExportCustomerGroups*/
var Pipelet = require('dw/system/Pipelet');
var PipeletExecutionResponse = new dw.system.Pipelet('ExportCustomerGroups').execute({
CustomerGroups: grpNam.iterator(),
ExportFile : grpFileName,
OverwriteExportFile:true
});
app.getView().render('path/templateName');
}
How can we replace the Pipelet ExportCustomerGroups here , i could see in documentation we can use job steps and there is no script replacement
You have to create with your own code, construct the xml needed while parsing the customers.[enter image description here][1]
Or you can use this step when configuring job if no custom code needed there:
[1]: https://i.stack.imgur.com/s1VQa.png

Import large amounts of data from Excel file into SQL Server using .NET Core and Angular

I want to import data from Excel files into SQL Server. The size of the file is 22 MB and contains approximately 1 million rows, but I get the error timeout.
This is the code of my controller
[System.Web.Http.Route("UploadExcel")]
[System.Web.Http.HttpPost]
[RequestFormLimits(MultipartBodyLengthLimit = 409715200)]
[RequestSizeLimit(409715200)]
public string ExcelUpload()
{
string message = "";
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
using (AngularDBEntities objEntity = new AngularDBEntities())
{
if (httpRequest.Files.Count > 0)
{
HttpPostedFile file = httpRequest.Files[0];
Stream stream = file.InputStream;
IExcelDataReader reader = null;
if (file.FileName.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (file.FileName.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
else
{
message = "This file format is not supported";
}
DataSet excelRecords = reader.AsDataSet();
reader.Close();
var finalRecords = excelRecords.Tables[0];
for (int i = 0; i < finalRecords.Rows.Count; i++)
{
UserDetail objUser = new UserDetail();
objUser.UserName = finalRecords.Rows[i][0].ToString();
objUser.EmailId = finalRecords.Rows[i][1].ToString();
objUser.Gender = finalRecords.Rows[i][2].ToString();
objUser.Address = finalRecords.Rows[i][3].ToString();
objUser.MobileNo = finalRecords.Rows[i][4].ToString();
objUser.PinCode = finalRecords.Rows[i][5].ToString();
objEntity.UserDetails.Add(objUser);
}
int output = objEntity.SaveChanges();
if (output > 0)
{
message = "Excel file has been successfully uploaded";
}
else
{
message = "Excel file uploaded failed";
}
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
return message;
}
I added maxRequestLength="1048576" executionTimeout="999999" to the web.config file in the system.web section, and maxAllowedContentLength="1073741824" to security tag, but I am still facing this problem.
Knowing that when I upload small files, the data is added to the table
you can add all items in a list and finally use bulk insert. use can use Entity Framework Extensions.

Read content from PDF using React Native

I am trying to read text from PDF file using expo and React Native. I used the below code to read but it's not working. On click of a button i use the DocumentPicker to select the PDF file and then i wanted to extract the text from the document alone. I am trying to create a app to read out the text for me.
But i am not able to do that. Thanks in advance.
loadText = async()=>{
//Alert.alert("load text triggered");
let result = await DocumentPicker.getDocumentAsync({});
if(result.type == 'success') {
// alert(result.uri);
let contents = await FileSystem.readAsStringAsync(result.uri);
//console.warn('content', contents);
if(contents.length > 0){
//let res = base64.fromByteArray(this.stringToUint8Array(contents));
//alert("t" + res);
this.setState({textToBeRead : this.atob(contents)});
alert("test" + this.state.textToBeRead);
}
}
};
atob = (input) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let str = input.replace(/=+$/, '');
let output = '';
if (str.length % 4 == 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (let bc = 0, bs = 0, buffer, i = 0;
buffer = str.charAt(i++);
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
buffer = chars.indexOf(buffer);
}
return output;
}

Validation xpages file download control

I have to do a validation in component file download Control, checking if any file is listed. Does anyone know how to do this validating. How can I get the object representing the xpages component and list the files by any of its methods?
here is some code I use to get hold on the upload via ssjs (if you want that)
var con = facesContext.getExternalContext();
var request:com.sun.faces.context.MyHttpServletRequestWrapper = con.getRequest();
var fileDataName = getClientId('ctrlUpload') ;
var map:java.util.Map = request.getParameterMap();
var fileData:com.ibm.xsp.http.UploadedFile = map.get(fileDataName);
if( fileData == null ){
growl.createGrowlMessage("<strong>Warning</strong> no file to upload selected","danger");
return;
}
var tempClientFile = fileData.getClientFileName();
var tempFile:java.io.File = fileData.getServerFile();
var filePath = tempFile.getParentFile().getAbsolutePath();
var correctedFile = new java.io.File(filePath+java.io.File.separator + tempClientFile );
var success = tempFile.renameTo(correctedFile);
var doc:NotesDocument = attachDoc.getDocument(true);
var rtFiles:NotesRichTextItem = null;
if(!(doc.hasItem("Files"))){
rtFiles = doc.createRichTextItem("Files");
}else{
rtFiles = doc.getFirstItem("Files");
}
rtFiles.embedObject(lotus.domino.local.EmbeddedObject.EMBED_ATTACHMENT,"",correctedFile.getAbsolutePath(), null);
correctedFile.renameTo(tempFile);
attachDoc is the reference to the data-binding I have set up:
<xp:this.data>
<xp:dominoDocument formName="fa_Attachment"
var="attachDoc">
</xp:dominoDocument>
</xp:this.data>

Looping through all images within multiple directories in ColdFusion

I'm working on an image manipulation script to create smaller thumbnail images of the images that are already on the server.
The directory structure that I need to search through is as follows:
Content
-Att1
-image1
-imgA1_1.png
-imgA1_1_large.png
-image2
-imgA1_2.png
-imgA2_large.png
-image3
-imgA1_3.png
-imgA1_3_large.png
-Att2
-image1
-imgA2_1.png
-imgA2_1_large.png
-image2
-imgA2_2.png
-imgA2_2_large.png
-image3
-imgA2_3.png
-imgA2_3_large.png
-Att3
-image1
-imgA3_1.png
-imgA3_1_large.png
-image2
-imgA3_2.png
-imgA3_2_large.png
-image3
-imgA3_3.png
-imgA3_3_large.png
etc...
So what I would like to to is be able to loop through all of the images shown above and if the dimensions of that image exceed 500-500 then create a thumbnail that is 100-100.
Is there any way of doing this without looping through each directory?
cfdirectory has a recurse attribute. This will loop through all the folders, but it won't require you to write code to loop through all the folders
<cfdirectory directory="yourDirectory" recurse="yes">
If you are dealing with very large directories cfdirecotry ends up being very slow. Here is a function that uses java that I wrote since we have some directories that have 1000s of images. It looks through and creates a query result for all your files and is MUCH faster
<cffunction name="getDirectorylisting" returntype="query" output="true">
<cfargument name="dirName" type="string" required="true" />
<cfargument name="recurse" type="boolean" default="false" required="false" />
<cfargument name="dirInfo1" type="query" default="#queryNew('datelastmodified,name,size,type,directory,hidden,pathname')#">
<cfscript>
var thisFile = '';
var listFiles = '';
var pathToParse = trim(dirName);
var thisPath = '';
var relPath = '';
var theFileObj = '';
var isDir = '';
var isFile = '';
var thisSize = '';
var lastModified = '';
var isHidden = '';
var theType = '';
if (left(dirName,2) == 'c:' || left(dirName,2) == 'd:' || left(dirName,2) == 'e:' || left(dirName,2) == '\\'){
//do nothing path is already absolute
} else {
pathToParse = expandPath(pathToparse);
}
if(right(pathToParse,1) == '/' || right(pathToParse,1) == '\'){pathToParse = left(pathToParse,len(pathToParse)-1);}
if(right(dirName,1) == '/' || right(dirName,1) == '\'){dirName = left(dirName,len(dirName)-1);}
if (directoryExists(pathToParse)){
listFiles = createObject("java","java.io.File").init(pathToParse).list();
for (thisFile=1;thisFile<=arrayLen(listFiles);thisFile=thisFile+1){
queryAddRow(arguments.dirInfo1);
thispath = "#pathToParse#\#listFiles[thisFile]#";
relpath = "#dirName#/#listFiles[thisFile]#";
theFileObj = createObject("java","java.io.File").init(thispath);
isDir = theFileObj.isDirectory();
isFile = theFileObj.isFile();
thisSize = val(theFileObj.length());
lastModified = theFileObj.lastModified();
isHidden = theFileObj.isHidden();
theType = "dir";
if (isFile){theType = "file";}
querySetCell(arguments.dirInfo1,"datelastmodified", lastModified );
querySetCell(arguments.dirInfo1,"name", listFiles[thisFile] );
querySetCell(arguments.dirInfo1,"size", thisSize );
querySetCell(arguments.dirInfo1,"directory", pathToParse );
querySetCell(arguments.dirInfo1,"hidden", isHidden );
querySetCell(arguments.dirInfo1,"type", theType );
querySetCell(arguments.dirInfo1,"pathName", relPath );
if (arguments.recurse && isDir && !isHidden){
arguments.dirInfo1 = getDirectoryListing(relPath,true, arguments.dirInfo1);
}
}
}
return arguments.dirInfo1;
</cfscript>
</cffunction>

Resources