I'd like to insert all Labels from a labelModuleId in an AX2009 table.
I have this job, that does nearly everything I need. But I have to enter the max Id (toLabel = 1000):
static void OcShowAllLabel(Args _args)
{
xInfo xinfo;
LanguageId currentLanguageId;
LabelModuleId labelModuleId = 'OCM'; // hier evt eine Eingabe durch Benutzer zur Auswahl
LabelIdNum frLabel;
LabelIdNum toLabel = 1000;
LabelId labelId;
OcShowAllLabels_RS tab;
Label blub = new Label();
str label;
;
xInfo = new xInfo();
currentLanguageId = xInfo.language();
delete_from tab
where tab.LanguageId == currentLanguageId
&& tab.LabelModuleId == labelModuleId;
for (frLabel = 1; frLabel <= toLabel; frLabel++)
{
labelId = strfmt('#%1%2', labelModuleId, frLabel);
label = SysLabel::labelId2String(labelId, currentLanguageId);
if (labelId != label)
{
tab.initValue();
tab.LabelId = labelId;
tab.Label = label;
tab.LanguageId = currentLanguageId;
tab.LabelModuleId = labelModuleId;
tab.insert();
}
}
Info('done');
}
If this is a one-time job, you can just stop the AOS and open the label file in notepad. It's in your application folder called axXXXen-us.ald, where XXX is your label file name and en-us is your language.
Look at classes\Tutorial_ThreadWork\doTheWork to see where they use a while(sLabel) instead of a for loop like you have.
container doTheWork(Thread t,LabelType searchFor)
{
container retVal;
SysLabel sysLabel = new SysLabel(LanguageTable::defaultLanguage());
str slabel;
;
slabel = sysLabel.searchFirst(searchFor);
while (slabel)
{
retVal += sLabel;
slabel = sysLabel.searchNext();
}
return retVal;
}
Since the label file is a text file, it would make sense that you can't just select the last one, but you have to iterate through the file. AX caches the labels however, but I don't believe you can just readily access the label cache as far as I know.
Lastly, hopefully you won't try this, but don't try to just read in the label text file, because AX sometimes has labels that it hasn't flushed to that file from the cache. I think Label::Flush(...) will flush them, but I'm not sure.
Here is another option I suppose. You can insert a label to get the next label number and then just immediately delete it:
static void Job32(Args _args)
{
SysLabel sysLabel = new SysLabel(LanguageTable::defaultLanguage());
SysLabelEdit sysLabelEdit = new SysLabeLEdit();
LabelId labelid;
;
labelId = syslabel.insert('alextest', '', 'OCM');
info(strfmt("%1", labelId));
sysLabelEdit.labelDelete(labelId, false);
}
It does seem to consume the number from the number sequence though. You could just do a Label::Flush(...) and then check the text file via code. Look at Classes\SysLabel* to see some of how the system deals with labels. It doesn't look very simple by any means.
Here is another option that might work for you. This will identify missing labels too. Change 'en-us' to your language. This is a "dirty" alternative I suppose. You might need to add something to say "if we find 5 labels in a row where they're like '#OCM'".
for (i=1; i<999; i++)
{
labelId = strfmt("#%1%2", 'OCM', i);
s = SysLabel::labelId2String(labelId, 'en-us');
if (s like '#OCM*')
{
info (strfmt("%1: Last is %2", i, s));
break;
}
info(strfmt("%1: %2", i, s));
}
Related
I'm doign a file transfer manager on Dialog the needs to dynamically generate a couple of UI elements. Here is the function that generates it:
void TransferData::createGraphicalUI(QDialog *parent, qint32 td_id){
status = new QLabel(parent);
filename = new QLabel(parent);
contact_label = new QLabel(parent);
accept = new IDPushButton(parent,td_id);
reject = new IDPushButton(parent,td_id);
cancel = new IDPushButton(parent,td_id);
progress = new QProgressBar(parent);
statlayout = new QHBoxLayout();
frameLayout = new QVBoxLayout();
frame = new QFrame(parent);
// Stylying the frame
frame->setStyleSheet("background-color: rgb(255, 255, 255);");
// Setting the messages.
QString htmlHeader = "<html><head/><body><p><span style='font-weight:792; color:#0000ff;'>";
QString htmlEnder = "</span></p></body></html>";
QString contactMsg = "Transfer ";
QString filenameMsg = "File name: </span><span>" + getFileToBeSent();
QString statusMsg = "Status: </span><span>";
cancel->setText("Cancel");
cancel->setIcon(QIcon(":/Icons/icons/cancel.png"));
cancel->setVisible(false);
if (getIsATransfer()){
// This is a transfer TO, the file will be uploaded
contactMsg = contactMsg + "to: </span><span> " + getConctacName();
statusMsg = statusMsg + "Waiting for file to be accepted.";
statlayout->addWidget(status);
statlayout->addWidget(cancel);
accept->setVisible(false);
reject->setVisible(false);
}
else{
// This is a transfer FROM, the file will be downlaoded
contactMsg = contactMsg + "from: </span><span> " + getConctacName();
statusMsg = statusMsg + "Transfer must be accepted before it begins.";
accept->setText("Accept");
accept->setIcon(QIcon(":/Icons/icons/ok.png"));
reject->setText("Reject");
reject->setIcon(QIcon(":/Icons/icons/cancel.png"));
statlayout->addWidget(status);
statlayout->addWidget(accept);
statlayout->addWidget(reject);
statlayout->addWidget(cancel);
}
status->setText(htmlHeader + statusMsg + htmlEnder);
filename->setText(htmlHeader + filenameMsg + htmlEnder);
contact_label->setText(htmlHeader + contactMsg + htmlEnder);
// Resettign the progress bar
progress->setValue(0);
// Putting it all together.
frameLayout->addWidget(contact_label);
frameLayout->addWidget(filename);
frameLayout->addLayout(statlayout);
frameLayout->addWidget(progress);
frame->setLayout(frameLayout);
}
This is called from a function that has a list of TransferData objects:
qint32 TransferManager::addTransfer(TransferData td){
// Getting the ID for this tranfer
qint32 transferID = transfers.size();
td.createGraphicalUI(this,transferID);
// Adding it to the UI
ui->globalTMLayout->addWidget(td.getFrame());
connect(td.getAcceptButton(),SIGNAL(wasClicked(qint32)),this,SLOT(onTransferAccepted(qint32)));
connect(td.getRejectButton(),SIGNAL(wasClicked(qint32)),this,SLOT(onTransferRejected(qint32)));
connect(td.getCancelButton(),SIGNAL(wasClicked(qint32)),this,SLOT(onTransferCanceled(qint32)));
// Adding the TD
transfers << td;
// If a transfer is added this needs to be shown
this->show();
return transferID;
}
Once the transfer is done I need to delete all the elements of the created UI. I do it like this:
void TransferManager::removeTransferData(qint32 which){
if (which < transfers.size()){
// Deleting the UI
transfers[which].removeGraphicalUI();
// Removing the frame
QFrame *frame = transfers.at(which).getFrame();
ui->globalTMLayout->removeWidget(frame);
// Removing the data itself
transfers.removeAt(which);
}
}
Where removeGraphicalUI is this function:
void TransferData::removeGraphicalUI(){
frameLayout->removeWidget(progress);
frameLayout->removeWidget(filename);
frameLayout->removeWidget(contact_label);
statlayout->removeWidget(cancel);
statlayout->removeWidget(status);
if (!getIsATransfer()){
statlayout->removeWidget(accept);
statlayout->removeWidget(reject);
}
}
What happens is that the frame is removed but everythign that was inside the frame remains. I've checked with a printed message an the code IS enering the removeUI function.
So why does this not work and what Is the proper way to delete dinamically generated UI?
Thanks!
Ok, so I haven't found the answer to my question but I did find the way to do this:
Basically the documentation says that when a QWidget descendant object is deleted, all their childs are deleted.
So what I did is basically used the QFrame as the parent for everything BUT the the layouts.
Then when I wanted to delete said frame I would simply invoke:
frame->~QFrame()
In the removeGraphicalUI() function and NOTHING more. Also I've commented this:
void TransferManager::removeTransferData(qint32 which){
if (which < transfers.size()){
// Deleting the UI
transfers[which].removeGraphicalUI();
// Removing the frame
// QFrame *frame = transfers.at(which).getFrame();
// ui->globalTMLayout->removeWidget(frame);
// Removing the data itself
transfers.removeAt(which);
}
}
As removing the frame from the GUI was no longer necessary. I hope this helps someone.
I have a pdf file that as the follow security properties: printing: allowed; document assembly: NOT allowed; content copy: allowed; content copy for accessibility: allowed; page extraction:NOT allowed;
I try to get text with sample code as documentation sample as follow:
pdftext.Text = null;
StringBuilder text = new StringBuilder();
PdfReader pdfReader = new PdfReader(filename);
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);
text.Append(System.Environment.NewLine);
text.Append("\n Page Number:" + page);
text.Append(System.Environment.NewLine);
currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
text.Append(currentText);
progressBar1.Value++;
}
pdftext.Text += text.ToString();
pdfReader.Close();
but the output text is lines with ""??? ? ???????\n?? ??? ? " values;
seems that file is crypted or we have a encoding problem...
note that in the follow lines
var f = pdfReader.IsOpenedWithFullPermissions; -> FALSE
var f1 = pdfReader.IsEncrypted(); - > FALSE
var f2 = pdfReader.ComputeUserPassword(); - > NULL
var f3 = pdfReader.Is128Key(); - > FALSE
var f4 = pdfReader.HasUsageRights();
f, f1, f3, f4 return FALSE ...than seems that the document is not crypted,
...so I don't know if is a Encoding problem or question related to encrypet strings...
Someone can help me?
thanks in advance.
G.G.
Whenever you have trouble extracting text from a document using standard code, the first thing to do is try and copy&paste the text from it using Adobe Acrobat Reader. Adobe Reader copy&paste implements text extraction according to the recommendations of the PDF specification, and if this fails, this usually means that the necessary information required for text extraction in the document are either missing or broken (by accident or by design). To extract the text, one either needs to customize the code specifically to the specific PDF or resort to OCR.
In case of the document at hand, Adobe Reader copy&paste does result in garbage, too, just like when extracting with iText. Thus, there is something fishy in the document.
Inspecting the document one finds that the fonts contain ToUnicode mappings like this:
/CIDInit /ProcSet
findresource begin 12 dict begin begincmap /CIDSystemInfo<</Registry(Adobe)
/Ordering(Identity)
/Supplement 0
>>
def
/CMapName/F18 def
1 begincodespacerange <0000> <FFFF> endcodespacerange
44 beginbfrange
<20> <20> <0020>
<21> <21> <E0F9>
<22> <22> <E0F1>
<23> <23> <E0FA>
<24> <24> <E0F7>
<25> <25> <E0A3>
<26> <26> <E084>
<27> <27> <E097>
<28> <28> <E098>
<29> <29> <E09A>
<2A> <2A> <E08A>
<2B> <2B> <E099>
<2C> <2C> <E0A5>
<2D> <2D> <E086>
<2E> <2E> <E094>
<2F> <2F> <E0DE>
<30> <30> <E0A6>
<31> <31> <E096>
<32> <32> <E088>
<33> <33> <E082>
<34> <34> <E04C>
<35> <35> <E0A4>
<36> <36> <E0F6>
<37> <37> <E0F2>
<38> <38> <E0D8>
<39> <39> <E0AA>
<3A> <3A> <E06C>
<3B> <3B> <E087>
<3C> <3C> <E095>
<3D> <3D> <E0C4>
<3E> <3E> <E07E>
<3F> <3F> <E055>
<40> <40> <E089>
<41> <41> <E085>
<42> <42> <E083>
<43> <43> <E070>
<44> <44> <E0E6>
<45> <45> <E080>
<46> <46> <E0C8>
<47> <47> <E0F4>
<48> <48> <E062>
<49> <49> <E0F3>
<4A> <4A> <E04E>
<4B> <4B> <E05E>
endbfrange
endcmap CMapName currentdict /CMap defineresource pop end end
I.e., if you are not into this, the fonts claim that all their glyphs (with the exception of the space glyph at 0x20) represent characters U+E0xx from the Unicode private use area. As the name of that area indicates, there is no common meaning of characters with these values.
Thus, text extraction according to the PDF specification will return strings of characters with undefined meaning with results as you observed in iText or I saw in Adobe Reader.
Sometimes in such a situation one can still enforce proper text extraction by ignoring the ToUnicode map and using either the font Encoding or information inside the embedded font program.
Unfortunately it turns out that here the Encoding effectively contains the same information as does the ToUnicode map, e.g. for the same font as above
/Differences [ 32 /space /uniE0F9 /uniE0F1 /uniE0FA /uniE0F7 /uniE0A3 /uniE084 /uniE097 /uniE098
/uniE09A /uniE08A /uniE099 /uniE0A5 /uniE086 /uniE094 /uniE0DE /uniE0A6 /uniE096
/uniE088 /uniE082 /uniE04C /uniE0A4 /uniE0F6 /uniE0F2 /uniE0D8 /uniE0AA /uniE06C
/uniE087 /uniE095 /uniE0C4 /uniE07E /uniE055 /uniE089 /uniE085 /uniE083 /uniE070
/uniE0E6 /uniE080 /uniE0C8 /uniE0F4 /uniE062 /uniE0F3 /uniE04E /uniE05E ]
and the fonts turns out to be Type3 fonts, i.e. there is no embedded font program but each glyph is defined as an individual PDF canvas without further character information.
Thus, nothing to gain here either.
Actually these small PDF canvasses contain inlined bitmap graphics of the respective glyph which also is the cause of the poor graphical quality of the document (if you don't see that immediately, simply zoom in a bit and you'll see the ragged outlines of the glyphs).
By the way, such a construct usually means that the producer of the PDF explicitly wants to prevent text extraction.
If you happen to have to extract text from many such documents, you can try and determine a mapping from their U+E0xx characters to actually sensible Unicode characters and apply that mapping to your extracted text.
If all those fonts in all those documents happen to use the same U+E0xx codepoints for the same actual characters, you'll be able to do text extraction from those documents after investing a certain amount of initial work.
Otherwise do try OCR.
The following code adds pages to a document which map the ToUnicode values to the characters shown:
void AddFontsTo(PdfReader reader, PdfStamper stamper)
{
int documentPages = reader.NumberOfPages;
for (int page = 1; page <= documentPages; page++)
{
// ignore inherited resources for now
PdfDictionary pageResources = reader.GetPageResources(page);
if (pageResources == null)
continue;
PdfDictionary pageFonts = pageResources.GetAsDict(PdfName.FONT);
if (pageFonts == null || pageFonts.Size == 0)
continue;
List<BaseFont> fonts = new List<BaseFont>();
List<string> fontNames = new List<string>();
HashSet<char> chars = new HashSet<char>();
foreach (PdfName key in pageFonts.Keys)
{
PdfIndirectReference fontReference = pageFonts.GetAsIndirectObject(key);
if (fontReference == null)
continue;
DocumentFont font = (DocumentFont) BaseFont.CreateFont((PRIndirectReference)fontReference);
if (font == null)
continue;
PdfObject toUni = PdfReader.GetPdfObjectRelease(font.FontDictionary.Get(PdfName.TOUNICODE));
CMapToUnicode toUnicodeCmap = null;
if (toUni is PRStream)
{
try
{
byte[] touni = PdfReader.GetStreamBytes((PRStream)toUni);
CidLocationFromByte lb = new CidLocationFromByte(touni);
toUnicodeCmap = new CMapToUnicode();
CMapParserEx.ParseCid("", toUnicodeCmap, lb);
}
catch
{
toUnicodeCmap = null;
}
}
if (toUnicodeCmap == null)
continue;
ICollection<int> mapValues = toUnicodeCmap.CreateDirectMapping().Values;
if (mapValues.Count == 0)
continue;
fonts.Add(font);
fontNames.Add(key.ToString());
foreach (int value in mapValues)
chars.Add((char)value);
}
if (fonts.Count == 0 || chars.Count == 0)
continue;
Rectangle size = (fonts.Count > 10) ? PageSize.A4.Rotate() : PageSize.A4;
PdfPTable table = new PdfPTable(fonts.Count + 1);
table.AddCell("Page " + page);
foreach (String name in fontNames)
{
table.AddCell(name);
}
table.HeaderRows = 1;
float[] widths = new float[fonts.Count + 1];
widths[0] = 2;
for (int i = 1; i <= fonts.Count; i++)
widths[i] = 1;
table.SetWidths(widths);
table.WidthPercentage = 100;
List<char> charList = new List<char>(chars);
charList.Sort();
foreach (char character in charList)
{
table.AddCell(((int)character).ToString("X4"));
foreach (BaseFont font in fonts)
{
table.AddCell(new PdfPCell(new Phrase(character.ToString(), new Font(font))));
}
}
stamper.InsertPage(reader.NumberOfPages + 1, size);
ColumnText columnText = new ColumnText(stamper.GetUnderContent(reader.NumberOfPages));
columnText.AddElement(table);
columnText.SetSimpleColumn(size);
while ((ColumnText.NO_MORE_TEXT & columnText.Go(false)) == 0)
{
stamper.InsertPage(reader.NumberOfPages + 1, size);
columnText.Canvas = stamper.GetUnderContent(reader.NumberOfPages);
columnText.SetSimpleColumn(size);
}
}
}
I applied it to your document like this:
string input = #"4700198773.pdf";
string output = #"4700198773-fonts.pdf";
using (PdfReader reader = new PdfReader(input))
using (FileStream stream = new FileStream(output, FileMode.Create, FileAccess.Write))
using (PdfStamper stamper = new PdfStamper(reader, stream))
{
AddFontsTo(reader, stamper);
}
The additional pages look like this:
Now you have to compare the outputs for the different fonts and pages of this document with each other and with those of a representative selection of file. If you find good enough a pattern, you can try this replacement way.
I am having trouble with displaying the results in the search activity of my app. I wonder where it went wrong.
The aim of the function below is to search the input query of the user and find it in every files listed. But the results only matches one data eventhough the query is also present in the other files. Here is the code.
public void searchFiles(File[] filelist, String query, String querysearch, String[] namesOfFiles){
querysearch = "SELECT * FROM Data WHERE ObjectID = ? ";
int temp2 = filelist.length;
for (int i = (temp2-1); i >= 0; i--) {
if(!(filelist[i].getName().equals("DataObjectDB.db")) && !(filelist[i].getName().endsWith("-journal"))){
temp1 = filelist[i].getName();
namesOfFiles[i] = temp1.replaceAll(".db$", "");
Toast.makeText(getApplicationContext(),"Searching " + query + " in: " + namesOfFiles[i], Toast.LENGTH_SHORT).show();
DatabaseHelper db1 = new DatabaseHelper(getApplicationContext(),namesOfFiles[i]);
SQLiteDatabase sqldb = db1.getWritableDatabase();
cursor = sqldb.rawQuery(querysearch, new String[]{query});
Toast.makeText(getApplicationContext(),cursor.toString(), Toast.LENGTH_SHORT).show();
}
}
final ListView listView = (ListView) findViewById(R.id.results_listview);
SearchAdapter adapter = new SearchAdapter(this, R.layout.results_column, cursor,0 );
listView.setAdapter(adapter);
}
The searchFiles() function passes the filelist, query, querysearch and namesOfFiles where 1) filelist contains the list of files in the source folder 2) query is the user input he/she wants to search 3) querysearch is the select statement 3) namesofFiles is just an empty string.
I indicate a toast to see if the code traverses through all the folders. And yes it is. But I don't know why it is not displaying all the results.
Any help? Thanks!
Found an answer on different posts. Basically, you just have to use hashmap and arraylist first before setting up the adapter directly.
I have one drop down list in my pages that its source comes of below code. Now I like to put 1 text box adjusted on my drop down list and when I type on that, source of drop down list (DocumentNo) depend on what I type in the text box and when text box is null drop downs list shows all the (DocumentNo) , please help how I have to change my code,
protected void ddlProjectDocument_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var query = from p in _DataContext.tblDocuments
orderby p.DocumentNo
select p;
int maxs = 0;
foreach (tblDocument v in query)
{
if (v.DocumentNo.Length > maxs)
maxs = v.DocumentNo.Length;
}
foreach (tblDocument vv in query)
{
string doctitle = vv.DocumentNo;
for (int i = vv.DocumentNo.Length; i < maxs; i++)
{
doctitle += " ";
}
doctitle += " | ";
doctitle += vv.TITLE;
// Use HtmlDecode to correctly show the spaces
doctitle = HttpUtility.HtmlDecode(doctitle);
ddlProjectDocument.Items.Add(new ListItem(doctitle, vv.DocId.ToString()));
}
}
First, I would highly recommend storing the result of that query at the beginning of the method into something like a session variable so that you don't have to continually query the database every time you hit this page.
Second, you should use the OnTextChanged event in ASP.NET to solve this problem. Put in the OnTextChanged attribute to point to a method in your code behind that will grab the query result values (now found in your session variable) and will reset what is contained in ddlProjectDocument.Items to anything that matched what was being written by using String.StartsWith():
var newListOfThings = queryResults.Where(q => q.DocumentNo.StartsWith(MyTextBox.Value));
At this point all you need to do is do that same loop that you did at the end of the method above to introduce the correct formatting.
I've got a JS array which is writing to a text file on the server using StreamWriter. This is the line that does it:
sw.WriteLine(Request.Form["seatsArray"]);
At the moment one line is being written out with the entire contents of the array on it. I want a new line to be written after every 5 commas. Example array:
BN,ST,A1,303,601,BN,ST,A2,303,621,BN,WC,A3,303,641,
Should output:
BN,ST,A1,303,601,
BN,ST,A2,303,621,
BN,WC,A3,303,641,
I know I could use a string replace but I only know how to make this output a new line after every comma, and not after a specified amount of commas.
How can I get this to happen?
Thanks!
Well, here's the simplest answer I can think of:
string[] bits = Request.Form["seatsArray"].Split(',');
for (int i = 0; i < bits.Length; i++)
{
sw.Write(bits[i]);
sw.Write(",");
if (i % 5 == 4)
{
sw.WriteLine();
}
}
It's not terribly elegant, but it'll get the job done, I believe.
You may want this afterwards to finish off the current line, if necessary:
if (bits[i].Length % 5 != 0)
{
sw.WriteLine();
}
I'm sure there are cleverer ways... but this is simple.
One question: are the values always three characters long? Because if so, you're basically just breaking the string up every 20 characters...
Something like:
var input = "BN,ST,A1,303,601,BN,ST,A2,303,621,BN,WC,A3,303,641,";
var splitted = input.Split(',');
var cols = 5;
var rows = splitted.Length / cols;
var arr = new string[rows, cols];
for (int row = 0; row < rows; row++)
for (int col = 0; col < cols; col++)
arr[row, col] = splitted[row * cols + col];
I will try find a more elegant solution. Properly with some functional-style over it.
Update: Just find out it is not actually what you needs. With this you get a 2D array with 3 rows and 5 columns.
This however will give you 3 lines. They do not have a ending ','. Do you want that? Do you always want to print it out? Or do you want to have access to the different lines?:
var splitted = input.Split(new [] { ','}, StringSplitOptions.RemoveEmptyEntries);
var lines = from item in splitted.Select((part, i) => new { part, i })
group item by item.i / 5 into g
select string.Join(",", g.Select(a => a.part));
Or by this rather large code. But I have often needed a "Chunk" method so it may be reusable. I do not know whether there is a build-in "Chunk" method - couldn't find it.
public static class LinqExtensions
{
public static IEnumerable<IList<T>> Chunks<T>(this IEnumerable<T> xs, int size)
{
int i = 0;
var curr = new List<T>();
foreach (var x in xs)
{
curr.Add(x);
if (++i % size == 0)
{
yield return curr;
curr = new List<T>();
}
}
}
}
Usage:
var lines = input.Split(',').Chunks(5).Select(list => string.Join(",", list));