Error Running jsx file from Indesign to export each text frame as a .txt file - text

Last year my colleague helped to build a script for Indesign.
Subsequently, after a system update we no longer have the script as Indesign CS6 was reinstalled, all we have is a version as below.
Using this code in Adobe Indesign to export each text frame that begins with a particular Paragraph stylesheet "PRODUCT HEADING" however I get an error message when I run the script...
Script is based on the ExportAllStories.jsx bundled with InDesign, plus a few mods found online.
//ExportAllStories.jsx
//An InDesign CS6 JavaScript
/*
###BUILDINFO### "ExportAllStories.jsx" 3.0.0 15 December 2009
*/
//Exports all stories in an InDesign document in a specified text format.
//
//For more on InDesign scripting, go to http://www.adobe.com/products/indesign/scripting/index.html
//or visit the InDesign Scripting User to User forum at http://www.adobeforums.com
//
main();
function main(){
//Make certain that user interaction (display of dialogs, etc.) is turned on.
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;
if(app.documents.length != 0){
if (app.activeDocument.stories.length != 0){
myDisplayDialog();
}
else{
alert("The document does not contain any text. Please open a document containing text and try again.");
}
}
else{
alert("No documents are open. Please open a document and try again.");
}
}
function myDisplayDialog(){
with(myDialog = app.dialogs.add({name:"ExportAllStories"})){
//Add a dialog column.
myDialogColumn = dialogColumns.add()
with(myDialogColumn){
with(borderPanels.add()){
staticTexts.add({staticLabel:"Export as:"});
with(myExportFormatButtons = radiobuttonGroups.add()){
radiobuttonControls.add({staticLabel:"Text Only", checkedState:true});
radiobuttonControls.add({staticLabel:"RTF"});
radiobuttonControls.add({staticLabel:"InDesign Tagged Text"});
}
}
}
myReturn = myDialog.show();
if (myReturn == true){
//Get the values from the dialog box.
myExportFormat = myExportFormatButtons.selectedButton;
myDialog.destroy;
myFolder= Folder.selectDialog ("Choose a Folder");
if((myFolder != null)&&(app.activeDocument.stories.length !=0)){
myExportAllStories(myExportFormat, myFolder);
}
}
else{
myDialog.destroy();
}
}
}
//myExportStories function takes care of exporting the stories.
//myExportFormat is a number from 0-2, where 0 = text only, 1 = rtf, and 3 = tagged text.
//myFolder is a reference to the folder in which you want to save your files.
function myExportAllStories(myExportFormat, myFolder){
for(myCounter = 0; myCounter < app.activeDocument.stories.length; myCounter++){
myStory = app.activeDocument.stories.item(myCounter);
myID = myStory.id;
switch(myExportFormat){
case 0:
myFormat = ExportFormat.textType;
myExtension = ".txt"
break;
case 1:
myFormat = ExportFormat.RTF;
myExtension = ".rtf"
break;
case 2:
myFormat = ExportFormat.taggedText;
myExtension = ".txt"
break;
}
if (myStory.paragraphs[0].appliedParagraphStyle.name == "PRODUCT HEADING"){
myFileName = myFileName.replace(/\s*$/,' ');
myFileName2 = myFileName.replace(/\//g, ' ');
myFilePath = myFolder + "/" + myFileName2;
myFile = new File(myFilePath);
myStory.exportFile(myFormat, myFile);
}
}
}
This results in an error on
if (myStory.paragraphs[0].appliedParagraphStyle.name == "PRODUCT HEADING"){
Any advice would be appreciated.
There is definitely a block of text with the style PRODUCT HEADING (all caps) in the Indesign File. We run Indesign CS6 as previous
thanks!

Your problem is most likely with this part: myStory.paragraphs[0]. If the story has no paragraphs this will give you an error.
You could add a condition before running this line, like this for example:
if(myStory.paragraphs.length){
if (myStory.paragraphs[0].appliedParagraphStyle.name == "PRODUCT HEADING"){
myFileName = myFileName.replace(/\s*$/,' ');
myFileName2 = myFileName.replace(/\//g, ' ');
myFilePath = myFolder + "/" + myFileName2;
myFile = new File(myFilePath);
myStory.exportFile(myFormat, myFile);
}
}

Related

Using File Type Array in Extendscript

I am trying to integrate an Array containing a list of image file types that can be used in my Extendscript, this is what I have:
DFgroup.DFBtn.onClick = function(){
DFdefault = new Folder(DARKinputFolder); //stores the current folder in case of cancel.
DFdefault = Folder.selectDialog('****Please Select The Folder Where Your DARK FRAMES Are Located****',DARKinputFolder);
if ( DFdefault != null ) {
DARKinputFolder = DFdefault.fsName.toString()
DFgroup.DFlabel.text = DARKinputFolder;
if(DFdefault){DARKinputFolder = DFdefault}; //if cancel is hit, this statement becomes false, and myFolder remains untouched.
//if it's true, then the selected folder from the holdFolder is transferred to myfolder.
var FILE_TYPE, FTlen i;
FILE_TYPE = [".orf", ".tif", ".tiff", ".jpg", ".jpeg"];
FTlen = FILE_TYPE.length;
for (i = 0; i < FTlen; i++){
var SEARCH_MASK = "*" + FILE_TYPE[i];}
var DARKfileList = DARKinputFolder.getFiles(SEARCH_MASK) ;
//if (DARKfileList.length <= 0)
//{
//var FILE_TYPE = ".jpg"; // The type of files that this script works on -- you can change
//var SEARCH_MASK = "*" + FILE_TYPE; // Image file filter to find only those files
//var DARKfileList = DARKinputFolder.getFiles(SEARCH_MASK);
//}
if (DARKfileList.length == 0)
{
alert('The DARK FRAME folder you have chosen is either empty or does not contain image files of the correct type.\r\rPlease locate & select the correct image folder.','DARK FRAME folder error');
DFgroup.DFlabel.text = 'No DARK FRAMES folder has been selected...';
DFdefault = '';
DFgroup.DFlabelQ.text = '';
}
else{
DFgroup.DFlabelQ.text = '[' + DARKfileList.length + ']';
var DFCurrFolder = (new File(DARKinputFolder)).fsName;
DFgroup.DFlabel.helpTip = 'Location of files to process:\r' + DFCurrFolder;
FolderChecker()
}}
} //opens the folder browse UI using you main folder.
When a user hits the 'DFBtn' an open folder dialog appears and they can choose a folder that contains images.
This folder path along with the number of images contained within it are retrieved and output as text label on a dialog box.
The problem is that through testing and choosing a folder that does contain an image and that image is of the allowed type, the script goes straight to the 'Alert' message stating that the "folder you have chosen is either empty....." etc..
Now if I alter a small section of the code as:
if (DARKfileList.length <= 0)
{
var FILE_TYPE, FTlen, i;
FILE_TYPE = [".orf", ".tif", ".tiff", ".jpg", ".jpeg"];
FTlen = FILE_TYPE.length;
for (i = 0; i < FTlen; i++){
var SEARCH_MASK = "*" + FILE_TYPE[i];}
var DARKfileList = DARKinputFolder.getFiles(SEARCH_MASK) ;}
The code now no longer goes straight to the 'Alert' message even if I deliberately choose a folder that is empty.
UPDATE
To aid in finding out what is going on I have added an extra line of code:
var FILE_TYPE, FTlen i;
FILE_TYPE = [".orf", ".tif", ".tiff", ".jpg", ".jpeg"];
FTlen = FILE_TYPE.length;
for (i = 0; i < FTlen; i++){
var SEARCH_MASK = "*" + FILE_TYPE[i];}
var DARKfileList = DARKinputFolder.getFiles(SEARCH_MASK);
alert (SEARCH_MASK);
By just adding this line alert (SEARCH_MASK); straight away I had an insight to what is occurring.
Yes the FILE_TYPE Array is being iterated through but then the SEARCH_MASK is formed using just the last FILE_TYPE in the array, so in the case above the SEARCH_MASK is always created as:
*.jpeg
Therefore it will only be looking for files of that type within the chosen folder.
This is not what I am trying to achieve.
I want to know if the chosen folder contains ANY files of ANY of the types listed in the array.
For instance, the chosen folder could contain all *.tif files or even one of each file type.
How can I achieve what I require the code to do?
Regards..,
UPDATE 2 BOILED DOWN SCRIPT
Here's a boiled down script as requested:
var DARKfileList = '';
var AllowedFileTypes = Array( "orf", "tif", "tiff", "jpg", "jpeg" );
var dlgM = new Window('dialog','***###***###',undefined,{closeButton:false});
dlgM.center();
var DARKinputFolder = new Folder('/C/'); //create a folder to have the dialog start on.
var DFdefault = new Folder(); //create a holding folder for canceling.
DFg = dlgM.add('panel {text:"DARK FRAMES",preferredSize:[450,15]}');
DFg.margins = [5,10,5,10];
DFg.alignChildren = 'left';
DFgroup = DFg.add('group');
DFgroup.DFBtn = DFgroup.add('button{text:"Select Folder...",preferredSize:[100,25]}');
DFgroup.DFBtn.helpTip = 'Please select your DARK FRAMES folder.';
DFgroup.DFlabel = DFgroup.add( 'statictext', undefined, DARKinputFolder, { truncate:'middle' } );
DFgroup.DFlabel.helpTip = 'Location of files to process';
DFgroup.DFlabel.preferredSize.width = '275';
DFgroup.DFlabel.text = 'No DARK FRAMES folder has been selected...';
DFgroup.DFlabelQ = DFgroup.add( 'statictext', undefined, '');
DFgroup.DFlabelQ.helpTip = 'Number of DARK FRAMES to process';
DFgroup.DFlabelQ.preferredSize.width = '40';
DFgroup.DFlabelQ.text = '';
BTNg = dlgM.add('group {alignment: "center"}');
BTNg.ExitBtn = BTNg.add('button{text:"Exit",preferredSize:[105,25]}');
BTNg.ProcessBtn = BTNg.add('button{text:"Process",preferredSize:[105,25]}');
BTNg.ProcessBtn.enabled = false;
DFgroup.DFBtn.onClick = function(){
DFdefault = new Folder(DARKinputFolder); //stores the current folder in case of cancel.
DFdefault = Folder.selectDialog('****Please Select The Folder Where Your DARK FRAMES Are Located****',DARKinputFolder);
if ( DFdefault != null ) {
DARKinputFolder = DFdefault.fsName.toString()
DFgroup.DFlabel.text = DARKinputFolder;
if(DFdefault){DARKinputFolder = DFdefault}; //if cancel is hit, this statement becomes false, and myFolder remains untouched.
//if it's true, then the selected folder from the holdFolder is transferred to myfolder.
var FTlen, i;
FTlen = AllowedFileTypes.length;
for (i = 0; i < FTlen; i++){
var SEARCH_MASK = "*." + AllowedFileTypes[i]};
var DARKfileList = DARKinputFolder.getFiles(SEARCH_MASK) ;
if (DARKfileList.length == 0)
{
alert('The DARK FRAME folder you have chosen is either empty or does not contain image files of the correct type.\r\rPlease locate & select the correct image folder.','DARK FRAME folder error');
DFgroup.DFlabel.text = 'No DARK FRAMES folder has been selected...';
DFdefault = '';
DFgroup.DFlabelQ.text = '';
}
else{
DFgroup.DFlabelQ.text = '[' + DARKfileList.length + ']';
var DFCurrFolder = (new File(DARKinputFolder)).fsName;
DFgroup.DFlabel.helpTip = 'Location of files to process:\r' + DFCurrFolder;
FolderChecker()
}}
} //opens the folder browse UI using you main folder.
BTNg.ExitBtn.onClick = function(){
dlgM.close();
}
function FolderChecker(){
if (DFdefault.exists){
BTNg.ProcessBtn.enabled = true;
}
}
BTNg.ProcessBtn.onClick = function(){
// THIS IS WHERE IMAGE PROCESSING STARTS -- REMOVED THIS HUGE SECTION FOR BREVITY
}
dlgM.show();
UPDATE 3 Final Issue
As per my comment about the need to check for illegal file types etc, here's what I have so far:
if (DARKfileList.length == 0)
{
alert('empty folder!','DARK FRAME folder error');
DFgroup.DFlabel.text = 'No DARK FRAMES folder has been selected...';
DFdefault = '';
DFgroup.DFlabelQ.text = '';
}
else if (DARKfileList.length > 1)
{
alert('too many file types!','DARK FRAME folder error');
DFgroup.DFlabel.text = 'No DARK FRAMES folder has been selected...';
DFdefault = '';
DFgroup.DFlabelQ.text = '';
}
else{
DFgroup.DFlabelQ.text = '[' + DARKfileList.length + ']';
var DFCurrFolder = (new File(DARKinputFolder)).fsName;
DFgroup.DFlabel.helpTip = 'Location of files to process:\r' + DFCurrFolder;
FolderChecker()
}
Now this works perfectly if the chosen folder contains only one file & that file is not in the FILE_TYPE array as DARKfileList.length returns zero. As Required
Similarly if the folder contains more than one of any file no matter what type the check fails. As Required
However, if a chosen folder contains one allowed FILE_TYPE & one file type that is not in the FILE_TYPE array the check fails. Needs Sorting Out
I need something along the lines of:
if (DARKfileList != FILE_LIST)
{
alert('Illegal file type!);
DFgroup.DFlabel.text = 'No DARK FRAMES folder has been selected...';
DFdefault = '';
DFgroup.DFlabelQ.text = '';
}
The problem is that each iteration you overriding the resulting search mask.
You need to merge all the resulting into one array, and then to check if your array is empty:
var DARKfileList = [], FILE_TYPE, FTlen, i, SEARCH_MASK;
FILE_TYPE = ["orf", "tif", "tiff", "jpg", "jpeg"];
FTlen = FILE_TYPE.length;
for (i = 0; i < FTlen; i++) {
SEARCH_MASK = "*." + FILE_TYPE[i];
DARKfileList = DARKfileList.concat(DARKinputFolder.getFiles(SEARCH_MASK));
}
alert('found: ' + DARKfileList.length + ' files');
Alternative: getFiles can get regex as parameter, so if you familiar with regex you can simply use the following regex:
/.+\.(?:jpe?g|tiff?|orf)$/i
Regex explanation: match in the filename any character, then dot character, and then one of the extension option and then the i flag used to ignore case sensitive. In your example you get only files that the extension is in lowercase.
To add another extensions to the regex, just add pipe(|) after orf and then your extension. ex: to add pdf extension:
/.+\.(?:jpe?g|tiff?|orf|pdf)$/i
Usage of regex in your code:
DARKfileList = DARKinputFolder.getFiles(/.+\.(?:jpe?g|tiff?|orf|pdf)$/i);
You can also use array to store all of your extensions and use it like:
var regex = new RegExp('.+\.(?:' + FILE_TYPE.join('|')+ ')$','i');
DARKfileList = DARKinputFolder.getFiles(regex);

NSSpeechSynthesizer Saving to URL

I'm creating a MacOS application that generates dialog files from a tab-delimited text file. The text file is formatted (output filename) [tab] (text to be spoken to that file). I got the program working perfectly running in the main thread, but this blocked the UI, of course. When I moved the meat of the application to a User Initiated thread, I unblocked the UI, but now it occasionally and randomly speaks a line out the speaker instead of to a file. A file is still created, but it's of zero duration. If the script contains 1,000 lines, it might get through the whole thing perfectly, or it might "speak" ten or more of them out the speaker. It's almost always different lines each time.
This is the code that speaks to a file:
// Set URL to save file to disk
if let speechFileURL = NSURL(string: speechFilePath) {
speechSynth.startSpeakingString(spokenText, toURL: speechFileURL) // Speak to file
}
else {
dialogAlert("Invalid File: ", text: speechFileName)
}
while(NSSpeechSynthesizer.isAnyApplicationSpeaking() == true) {
if self.gUserClickedStop {
speechSynth.stopSpeaking()
self.gIsSpeaking = false
break
}
}
This is the call to the function that parses the script and generates the speech files:
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [unowned self] in
self.parseTheScript()
}
As mentioned above, calling parseTheScript() without wrapping it in the Grand Central Dispatch call makes it work perfectly, except for the blocking issue.
I'm new to programming in Swift and the idea of multithreaded programming, so I'm sure I'm doing something wrong, but I'm stumped as to how to fix this problem.
Thank you in advance for your help.
Edit to add...
This is the entire function that parses the text file and generates the dialog files:
// This opens the text file and generates the spoken audio files
func parseTheScript() {
let filemgr = NSFileManager.defaultManager()
print("Chosen path: \(scriptFileTextField.stringValue)") // debug
if filemgr.fileExistsAtPath(scriptFileTextField.stringValue) {
print("File exists")
do {
outputFilename.stringValue = ""
scriptToSpeak.stringValue = ""
outputFilename.hidden = false
scriptToSpeak.hidden = false
progressBar.minValue = 0
progressBar.doubleValue = 0.0
progressBar.hidden = false
filenameLabel.hidden = false
let text = try String(contentsOfFile: scriptFileTextField.stringValue, encoding: NSUTF8StringEncoding)
let lines: [String] = text.componentsSeparatedByString("\n")
var progressEndValue = Double(lines.count)
progressBar.maxValue = progressEndValue
let speechSynth = NSSpeechSynthesizer.init()
let theVoice = gVoiceList[voiceListPopup.indexOfSelectedItem - 1] // Not sure why it's off by one
speechSynth.setVoice(theVoice)
for line in lines {
let thisLine: [String] = line.componentsSeparatedByString("\t") // Split the line at the tab character
if (thisLine.count == 2) { // Did the line split into two parts?
let speechFileName = thisLine[0]
let spokenText = thisLine[1]
outputFilename.stringValue = speechFileName
scriptToSpeak.stringValue = spokenText
let speechFilePath = destinationFolderTextField.stringValue + speechFileName + ".aif" // Build the path string for the output speech file
print("Filename: \(speechFilePath)")
print("SpokenText: \(spokenText)")
if(gSpeakToFile) {
// Set URL to save file to disk
if let speechFileURL = NSURL(string: speechFilePath) {
speechSynth.startSpeakingString(spokenText, toURL: speechFileURL) // Speak to file
}
else {
dialogAlert("Invalid File: ", text: speechFileName)
}
}
else {
speechSynth.startSpeakingString(spokenText) // Speak to audio output
}
while(NSSpeechSynthesizer.isAnyApplicationSpeaking() == true) {
if self.gUserClickedStop {
speechSynth.stopSpeaking()
self.gIsSpeaking = false
break
}
}
progressBar.incrementBy(1.0)
}
if gUserClickedStop {
gUserClickedStop = false
gIsSpeaking = false
progressEndValue = 0
generateButton.title = "Start"
break
}
}
gIsSpeaking = false
progressBar.doubleValue = progressEndValue
generateButton.title = "Start"
filenameLabel.hidden = true
outputFilename.stringValue = ""
scriptToSpeak.stringValue = ""
} catch let error as NSError {
dialogAlert("Error:", text: String(error.localizedDescription))
print("Error: \(error)")
}
} else {
print("File does not exist")
}
}

Select text between two bookmarks in Komodo Edit

Let's say I have the following (example) code in combined.js:
/* jQuery, Moment.js, Bootstrap, etc. */
Child.prototype.doSchool = function(data) { // Bookmarked
var essay = data.essay || {};
if (essay) {
var spelling = checkSpelling(essay, EN_US_GRADE_7);
return spelling.grade();
}
}
/* Extensive and Turing-complete code base */
var burt = new Child();
if (burt.doSchool({essay: "i like trains"}) < .65) burt.comfort(); // Bookmarked
/* jQuery extensions, Fallout 4, etc. */
The file is bookmarked in Komodo Edit 9.3.x in the locations marked by // inline comments.
Any /* block comments */ indicate thousands of lines of code.
The source between the bookmarks exists in another file, school.inc.js. I want to know if there is an easy way to select all the text between the bookmarks, so that combined.js can be easily updated by pasting the contents of school.inc.js over it without having to use a combining utility.
There is no built in way to do this but you could possible do it by writing a Userscript.
You'll want to use the Komodo Editor SDK.
// This assumes you're running the Userscript starting at the first bookmark
var editor = require("ko/editor");
var startSelect;
var endSelect;
var done = false;
function selectBookmarkRegion(){
if(editor.bookmarkExists()) { // check if bookmark is set on current line
startSelect = { // save it's line start
line: editor.getLineNumber(),
ch: 0
};
} else {
alert("Start me on a line with a Bookmark");
}
editor.goLineDown();
while(!done){
if(editor.bookmarkExists())
{
endSelect = {
line: editor.getLineNumber(),
ch: editor.getLineSize()
};// Save line end
done = true;
}
editor.goLineDown();
// found a bug as I was writing this. Will be fixed in the next releases
if (editor.getLineNumber() + 1 == editor.lineCount())
{
done = true;
}
}
editor.setSelection(startSelect, endSelect); // Wrap the selection
}
selectBookmarkRegion();

Retrieve entire Word document in task pane app / office.js

Working in Word 2013 (desktop) and office.js, we see some functionality around the user's selection (GetSelectedDataAsync, SetSelectedDataAsync), but nothing that might let you view the entire (OpenXML) document. Am I missing something?
Office.context.document.getFileAsync will let you get the entire document in a choice of 3 formats:
compressed: returns the entire document (.pptx or .docx) in Office Open XML (OOXML) format as a byte array
pdf: returns the entire document in PDF format as a byte array
text: returns only the text of the document as a string. (Word only)
Here's the example taken from MSDN:
var i = 0;
var slices = 0;
function getDocumentAsPDF() {
Office.context.document.getFileAsync("pdf", { sliceSize: 2097152 }, function (result) {
if (result.status == "succeeded") {
// If the getFileAsync call succeeded, then
// result.value will return a valid File Object.
myFile = result.value;
slices = myFile.sliceCount;
document.getElementById("result").innerText = " File size:" + myFile.size + " #Slices: " + slices;
// Iterate over the file slices.
for (i = 0; i < slices; i++) {
var slice = myFile.getSliceAsync(i, function (result) {
if (result.status == "succeeded") {
doSomethingWithChunk(result.value.data);
if (slices == i) // Means it's done traversing...
{
SendFileComplete();
}
}
else
document.getElementById("result").innerText = result.error.message;
});
}
myFile.closeAsync();
}
else
document.getElementById("result2").innerText = result.error.message;
});
}
This is not exactly what you asked for (it is only the body of the document) but it helped me... So I post it here as it is where I landed when I googled my problem.
The documentation here: https://dev.office.com/reference/add-ins/word/body suggests that getOoxml() will get you the body of the document. There is also the property text which will return you the plain text content.
The way this API works is not overly straight forward - however the examples in the online doc really help in getting started.
All the best,

Fast access to excel data in X++

Can someone give me a clue how can I get the fast access of the excel data. Currently the excel contains more than 200K records and when I retrieve from the X++ code it takes a lot of time to retrieve all the records.
Following are the classes I am using to retrieve the data.
1 - SysExcelApplication, SysExcelWorksheet and SysExcelCells.
I am using the below code to retrieve cells.
excelApp.workbooks().open(filename);
excelWorksheet = excelApp.worksheets().itemFromName(itemName);
excelCells = excelWorkSheet.cells();
///pseudo code
loop
excelCells.item(rowcounter, column1);
similar for all columns;
end of loop
If any of the special property needs to be set here please tell me.
Overall performance will be a lot better (huge!) if you can use CSV files. If you are forced to use Excel files, you can easy and straigforward convert this excel file to a csv file and then read the csv file. If you can't work that way, you can read excel files throug ODBC (using a query string like connecting to a database) that will perform better that the Office API.
First things, reading Excel files (and any other file) will take a while for 200 K records.
You can read an Excel file using ExcelIo, but with no performance guaranties :)
As I see it, you have 3 options (best performance listed first):
Convert your Excel file to CSV file, then read with CommaIo.
Read the Excel file using C#, then call back to X++
Accept the fact and take the time
use CSV, it is faster, below is code example:
/* Excel Import*/
#AviFiles
#define.CurrentVersion(1)
#define.Version1(1)
#localmacro.CurrentList
#endmacro
FilenameOpen filename;
CommaIo file;
Container con;
/* File Open Dialog */
Dialog dialog;
dialogField dialogFilename;
dialogField dialogSiteID;
dialogField dialogLocationId;
DialogButton dialogButton;
InventSite objInventSite;
InventLocation objInventLocation;
InventSiteID objInventSiteID;
InventLocationId objInventLocationID;
int row;
str sSite;
NoYes IsCountingFound;
int iQty;
Counter insertCounter;
Price itemPrice;
ItemId _itemid;
EcoResItemColorName _inventColorID;
EcoResItemSizeName _inventSizeID;
dialog = new Dialog("Please select file");
dialogSiteID = dialog.addField(extendedTypeStr(InventSiteId), objInventSiteId);
dialogLocationId = dialog.addField(extendedTypeStr(InventLocationId), objInventLocationId);
dialogFilename = dialog.addField(extendedTypeStr(FilenameOpen));
dialog.filenameLookupFilter(["#SYS100852","*.csv"]);
dialog.filenameLookupTitle("Please select file");
dialog.caption("Please select file");
dialogFilename.value(filename);
if(!dialog.run())
return;
objInventSiteID = dialogSiteID.value();
objInventLocationID = dialogLocationId.value();
/*----- validating warehouse*/
while
select maxof(InventSiteId) from objInventLocation where objInventLocation.InventLocationId == objInventLocationId
{
If(objInventLocation.InventSiteID != objInventSiteID)
{
warning("Warehouse not belongs to site. Please select valid warehouse." ,"Counting lines import utility");
return;
}
}
filename = dialogFilename.value();
file = new commaIo(filename,'r');
file.inFieldDelimiter(',');
try
{
if (file)
{
ttsbegin;
while(file.status() == IO_Status::OK)
{
con = file.read();
if (con)
{
row ++;
if(row == 1)
{
if(
strUpr(strLtrim(strRtrim( conpeek(con,1) ))) != "ITEM"
|| strUpr(strLtrim(strRtrim( conpeek(con,2) ))) != "COLOR"
|| strUpr(strLtrim(strRtrim( conpeek(con,3) ))) != "SIZE"
|| strUpr(strLtrim(strRtrim( conpeek(con,4) ))) != "PRICE"
)
{
error("Imported file is not according to given format.");
ttsabort;
return;
}
}
else
{
IsCountingFound = NoYes::No;
_itemid = "";
_inventColorID = "";
_inventSizeID = "";
_itemid = strLtrim(strRtrim(conpeek(con,1) ));
_inventColorID = strLtrim(strRtrim(conpeek(con,2) ));
_inventSizeID = strLtrim(strRtrim(conpeek(con,3) ));
itemPrice = any2real(strLtrim(strRtrim(conpeek(con,4) )));
}
}
}
if(row <= 1)
{
ttsabort;
warning("No data found in excel file");
}
else
{
ttscommit;
}
}
}
catch
{
ttsabort;
Error('Upload Failed');
}

Resources