CreateRecord Update Method does not update table - peoplesoft
I have modified the below App Engine program to update a field on an existing row, using a File Layout. I have added code to update existing rows for items that have a new Vendor Item ID populated. While the program doesn’t error while running, it also does not actually update the table PS_ITM_VENDOR with the ITM_ID_VNDR field. The program reads the file layout appropriately, and I can display the variable for ITM_ID_VNDR. I'm not sure I am using the .Update method correctly for the CreateRecord class. The changes are notated by the '1/7/2020' comment at the bottom.
Local SQL &SQL, &SQL2;
Local string &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Oprid, &PriceStatus, &VendorId_check, &insert_cols, &insert_select, &insert_where, &insert_sql, &Error, &MaxEffdt, &ItmIdVndrNew;
Local date &Effdt;
Local Record &ITM_VNDR_UOM_PR, &REC, &REC1;
&Oprid = "'BATCH'";
&PriceStatus = "2";
&Error = "N";
MessageBox(0, "", 0, 0, "**** BEGINING OF VALIDATION ERRORS ****");
&SQL = CreateSQL("SELECT VENDOR_ID, INV_ITEM_ID, ITM_ID_VNDR, UNIT_OF_MEASURE, CONVERSION_RATE, PRICE_VNDR, %DateOut(EFFDT), ITM_ID_VNDR_NEW FROM PS_GH_ITM_PR_UPDT ORDER BY VENDOR_ID, INV_ITEM_ID, ITM_ID_VNDR", &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Effdt, &ItmIdVndrNew);
While &SQL.Fetch(&VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Effdt, &ItmIdVndrNew)
SQLExec("SELECT A.VENDOR_ID FROM PS_ITM_VENDOR A, PS_ITM_VNDR_UOM B WHERE A.SETID = B.SETID AND A.INV_ITEM_ID = B.INV_ITEM_ID AND A.VENDOR_SETID = B.VENDOR_SETID AND A.VENDOR_ID = B.VENDOR_ID AND A.VENDOR_ID = :1 AND A.INV_ITEM_ID = :2 AND A.ITM_ID_VNDR = :3 AND A.ITM_VNDR_PRIORITY = 1 AND B.UNIT_OF_MEASURE = :4 AND B.CONVERSION_RATE = :5", &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &VendorId_check);
If None(&VendorId_check) Then;
&Error = "Y";
MessageBox(0, "", 0, 0, &VendorId | " " | &InvItemId | " " | &ItmIdVndr | " " | &UOM | " " | &ConvRate | " " | &PriceVndr | " " | &Effdt | " " | &ItmIdVndrNew);
Else;
&CurrentDateTime = %Datetime;
&Oprid = %OperatorId;
&RECITEM = CreateRecord(Record.ITM_VNDR_UOM_PR);
/*8/8/2012 - CHC_PO_96588 - Begin */
/*SQLExec("SELECT TO_CHAR(C.EFFDT,'DD-MON-YYYY') FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.UNIT_OF_MEASURE = :3 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN) ", &InvItemId, &VendorId, &UOM, &MaxEffdt);*/
SQLExec("SELECT C.EFFDT FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.UNIT_OF_MEASURE = :3 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN) ", &InvItemId, &VendorId, &UOM, &MaxEffdt);
/*CHC_PO_96588 - End */
SQLExec("%SelectAll(:1) WHERE INV_ITEM_ID = :2 AND VENDOR_ID = :3 AND UNIT_OF_MEASURE = :4 AND (CONVERT(CHAR(10),EFFDT,121)) = :5", &RECITEM, &InvItemId, &VendorId, &UOM, &MaxEffdt, &RECITEM);
/*SQLExec("%SelectAll(:1) WHERE INV_ITEM_ID = :2 AND VENDOR_ID = :3 AND UNIT_OF_MEASURE = :4 AND EFFDT = :5", &RECITEM, &InvItemId, &VendorId, &UOM, &MaxEffdt, &RECITEM); */
&new_UNIT_OF_MEASURE = &RECITEM.UNIT_OF_MEASURE.Value;
&REC = CreateRecord(Record.ITM_VNDR_UOM_PR);
&REC.SETID.Value = &RECITEM.SETID.Value;
&REC.INV_ITEM_ID.Value = &RECITEM.INV_ITEM_ID.Value;
&REC.VENDOR_SETID.Value = &RECITEM.VENDOR_SETID.Value;
&REC.VENDOR_ID.Value = &RECITEM.VENDOR_ID.Value;
&REC.VNDR_LOC.Value = &RECITEM.VNDR_LOC.Value;
&REC.UNIT_OF_MEASURE.Value = &RECITEM.UNIT_OF_MEASURE.Value;
&REC.CURRENCY_CD.Value = &RECITEM.CURRENCY_CD.Value;
&REC.QTY_MIN.Value = &RECITEM.QTY_MIN.Value;
&REC.EFFDT.Value = &Effdt;
&REC.EFF_STATUS.Value = &RECITEM.EFF_STATUS.Value;
&REC.PRICE_VNDR.Value = &PriceVndr;
&REC.PCT_UNIT_PRC_TOL.Value = &RECITEM.PCT_UNIT_PRC_TOL.Value;
&REC.PCT_EXT_PRC_TOL.Value = &RECITEM.PCT_EXT_PRC_TOL.Value;
&REC.USE_STD_TOLERANCES.Value = &RECITEM.USE_STD_TOLERANCES.Value;
&REC.QTY_RECV_TOL_PCT.Value = &RECITEM.QTY_RECV_TOL_PCT.Value;
&REC.UNIT_PRC_TOL_L.Value = &RECITEM.UNIT_PRC_TOL_L.Value;
&REC.PCT_UNIT_PRC_TOL_L.Value = &RECITEM.PCT_UNIT_PRC_TOL_L.Value;
&REC.EXT_PRC_TOL_L.Value = &RECITEM.EXT_PRC_TOL_L.Value;
&REC.PCT_EXT_PRC_TOL_L.Value = &RECITEM.PCT_EXT_PRC_TOL_L.Value;
&REC.BU_PRICE_STATUS.Value = "2";
&REC.STD_PRICE_STATUS.Value = "2";
&REC.LEAD_TIME.Value = &RECITEM.LEAD_TIME.Value;
&REC.OPRID_MODIFIED_BY.Value = &Oprid;
&REC.LAST_DTTM_UPDATE.Value = &CurrentDateTime;
&REC.PRICE_CHANGE.Value = &RECITEM.PRICE_CHANGE.Value;
&REC.Insert();
/* 10/30/2014 - Writes line if good */
/*MessageBox(0, "", 0, 0, &VendorId | " " | &InvItemId | " " | &ItmIdVndr | " " | &UOM | " " | &ConvRate | " " | &PriceVndr | " " | &Effdt);*/
End-If;
End-While;
/* 1/7/2020 BEGIN Changes for ITEM_ID_VNDR */
&SQL2 = CreateSQL("SELECT VENDOR_ID, INV_ITEM_ID, ITM_ID_VNDR, UNIT_OF_MEASURE, CONVERSION_RATE, PRICE_VNDR, %DateOut(EFFDT), ITM_ID_VNDR_NEW FROM PS_GH_ITM_PR_UPDT ORDER BY VENDOR_ID, INV_ITEM_ID, ITM_ID_VNDR", &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Effdt, &ItmIdVndrNew);
While &SQL2.Fetch(&VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Effdt, &ItmIdVndrNew)
If None(&ItmIdVndrNew) Then;
&Error = "Y";
MessageBox(0, "", 0, 0, &VendorId | " " | &InvItemId | " " | &ItmIdVndr | " " | &UOM | " " | &ConvRate | " " | &PriceVndr | " " | &Effdt | " " | &ItmField | " " | &ItmIdVndrNew);
MessageBox(0, "", 0, 0, "**** INSIDE MAIN IF CONDITION ****");
Else;
MessageBox(0, "", 0, 0, "**** INSIDE ELSE CONDITION ****");
&REC1 = CreateRecord(Record.ITM_VENDOR);
&REC1.ITM_ID_VNDR.Value = &ItmIdVndrNew;
&REC1.Update();
End-If;
End-While;
/* 1/7/2020 END Changes for ITEM_ID_VNDR */
MessageBox(0, "", 0, 0, "**** END OF VALIDATION ERRORS ****");
MessageBox(0, "", 0, 0, " ");
UPDATE: I can see in the Trace file that I am not picking up the table's key fields while trying to update. I am thinking this is part of the problem...
8830 10:51:28.860 0.000000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 COM Stmt=UPDATE PS_ITM_VENDOR SET ITM_ID_VNDR=:1 WHERE SETID=:2 AND INV_ITEM_ID=:3 AND VENDOR_SETID=:4 AND VENDOR_ID=:5
8831 10:51:28.861 0.000000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 Bind-1 type=2 length=7 value=1234567
8832 10:51:28.861 0.001000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 Bind-2 type=2 length=1 value=
8833 10:51:28.862 0.000000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 Bind-3 type=2 length=1 value=
8834 10:51:28.862 0.001000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 Bind-4 type=2 length=1 value=
8835 10:51:28.863 0.000000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 Bind-5 type=2 length=1 value=
8836 10:51:28.864 0.001000 Cur#1.23796.FSDEV92C RC=0 Dur=0.001000 EXE
8837 10:51:28.865 0.000000 Cur#1.23796.FSDEV92C RC=0 Dur=0.000000 ROW #rows=0
8838 10:51:28.865 0.001000 Cur#5.23796.FSDEV92C RC=0 Dur=0.000000 Fetch
You are only setting &REC1.ITM_ID_VNDR.Value.
You need to set all the keys in &REC1 before calling the Update() method.
Think I have discovered the issue, I needed to bind &REC1 to &REC2 as follows:
&REC1 = CreateRecord(Record.ITM_VENDOR);
&REC2 = CreateRecord(Record.ITM_VENDOR);
.....
&REC2.Update(&REC1);
Related
Downloading a Nested DT table in Shiny
I've got a nested DT table in my Shiny app. The child table is a list that gets passed and rendered into the table. When I go to add a download button via DT's built in method, the output contains the parent table data and then a list of [Object][Object].. instead of the actual child data. Do I have to write my own downloadable button method instead of using DT's method or is there a original DT method that helps with this? Haven't found a solution yet. Data Parent structure(list(Market = c("ABILENE, TX", "AKRON, OH"), `SQAD CPP ($)` = c(10, 49), `SQAD CPM ($)` = c(22, 30), `Override CPP ($)` = c(0, 0), `Override CPM ($)` = c(0, 0)), .Names = c("Market", "SQAD CPP ($)", "SQAD CPM ($)", "Override CPP ($)", "Override CPM ($)"), row.names = c(NA, -2L), class = "data.frame") Child structure(list(Market = c("ABILENE, TX", "ABILENE, TX", "ABILENE, TX", "ABILENE, TX", "ABILENE, TX", "ABILENE, TX", "ABILENE, TX", "ABILENE, TX", "ABILENE, TX", "AKRON, OH", "AKRON, OH", "AKRON, OH", "AKRON, OH", "AKRON, OH", "AKRON, OH", "AKRON, OH", "AKRON, OH", "AKRON, OH" ), Daypart = c(" Podcast", " Streaming/Digital Audio", "Afternoon Drive", "Daytime", "Evening", "Mon-Fri Average", "Mon-Sun Average", "Morning Drive", "Weekend", " Podcast", " Streaming/Digital Audio", "Afternoon Drive", "Daytime", "Evening", "Mon-Fri Average", "Mon-Sun Average", "Morning Drive", "Weekend"), `Mix (%)` = c(10L, 10L, 10L, 10L, 10L, 10L, 5L, 15L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 5L, 15L, 10L), `Spot:60 (%)` = c(4, 4, 4, 4, 4, 4, 2, 6, 4, 4, 4, 4, 4, 4, 4, 2, 6, 4), `Spot:30 (%)` = c(6, 6, 6, 6, 6, 6, 3, 9, 6, 6, 6, 6, 6, 6, 6, 3, 9, 6), `SQAD CPP ($)` = c(10, 6, 27, 31, 44, 32, 31, 26, 26, 34, 21, 170, 156, 112, 151, 136, 177, 95), `SQAD CPM ($)` = c(21, 13, 57.6, 64.8, 93.6, 68.4, 64.8, 54, 54, 21, 13, 104.5, 96.1, 69, 93, 83.6, 108.7, 58.5), `Override CPP ($)` = c(10, 6, 27, 31, 44, 32, 31, 26, 26, 34, 21, 170, 156, 112, 151, 136, 177, 95), `Override CPM ($)` = c(21, 13, 57.63, 64.83, 93.64, 68.43, 64.83, 54.03, 54.03, 21, 13, 104.49, 96.13, 68.96, 92.99, 83.59, 108.67, 58.51), population = c(47200L, 47200L, 47200L, 47200L, 47200L, 47200L, 47200L, 47200L, 47200L, 162700L, 162700L, 162700L, 162700L, 162700L, 162700L, 162700L, 162700L, 162700L), slider_60s = c(0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4), slider_30s = c(0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6)), .Names = c("Market", "Daypart", "Mix (%)", "Spot:60 (%)", "Spot:30 (%)", "SQAD CPP ($)", "SQAD CPM ($)", "Override CPP ($)", "Override CPM ($)", "population", "slider_60s", "slider_30s"), class = "data.frame", row.names = c(NA, -18L)) Code # Bind the market level and mix breakout data together for the final table market_mix_table <- reactive({ # Take a dependency on input$goButton input$goButton isolate({ markets <- market_costings_gross_net() mix_breakout <- mix_breakout_digital_elements() # Make the dataframe # This must be met length(children) == nrow(dat) Dat <- NestedData( dat = markets, children = split(mix_breakout, mix_breakout$Market) ) return(Dat) }) }) # Render the table output$daypartTable <- DT::renderDataTable({ Server = FALSE # Whether to show row names (set TRUE or FALSE) rowNames <- FALSE colIdx <- as.integer(rowNames) # The data Dat <- market_mix_table() parentRows <- which(Dat[,1] != "") callback_js = JS( "var ok = true;", "function onUpdate(updatedCell, updatedRow, oldValue) {", " var column = updatedCell.index().column;", " if(column === 8){", " ok = false;", " }else if(column === 7){", " ok = true;", " }", "}", sprintf("var parentRows = [%s];", toString(parentRows-1)), sprintf("var j0 = %d;", colIdx), "var nrows = table.rows().count();", "for(var i=0; i < nrows; ++i){", " if(parentRows.indexOf(i) > -1){", " table.cell(i,j0).nodes().to$().css({cursor: 'pointer'});", " }else{", " table.cell(i,j0).nodes().to$().removeClass('details-control');", " }", "}", "", "// make the table header of the nested table", "var format = function(d, childId){", " if(d != null){", " var html = ", " '<table class=\"display compact hover\" ' + ", " 'style=\"padding-left: 30px;\" id=\"' + childId + '\"><thead><tr>';", " for(var key in d[d.length-1][0]){", " html += '<th>' + key + '</th>';", " }", " html += '</tr></thead><tfoot><tr>'", " for(var key in d[d.length-1][0]){", " html += '<th></th>';", " }", " return html + '</tr></tfoot></table>';", " } else {", " return '';", " }", "};", "", "// row callback to style the rows of the child tables", "var rowCallback = function(row, dat, displayNum, index){", " if($(row).hasClass('odd')){", " $(row).css('background-color', 'white');", " $(row).hover(function(){", " $(this).css('background-color', 'lightgreen');", " }, function() {", " $(this).css('background-color', 'white');", " });", " } else {", " $(row).css('background-color', 'white');", " $(row).hover(function(){", " $(this).css('background-color', 'lightblue');", " }, function() {", " $(this).css('background-color', 'white');", " });", " }", "};", "", "// header callback to style the header of the child tables", "var headerCallback = function(thead, data, start, end, display){", " $('th', thead).css({", " 'color': 'black',", " 'background-color': 'white'", " });", "};", "", "// make the datatable", "var format_datatable = function(d, childId, rowIdx){", " // footer callback to display the totals", " // and update the parent row", " var footerCallback = function(tfoot, data, start, end, display){", " $('th', tfoot).css('background-color', '#F5F2F2');", " var api = this.api();", "// update the Override CPM when the Override CPP is changed", " var col_override_cpp = api.column(7).data();", " var col_population = api.column(9).data();", " if(ok){", " for(var i = 0; i < col_override_cpp.length; i++){", " api.cell(i,8).data(((parseInt(col_override_cpp[i])*100)/(parseInt(col_population[i])/1000)).toFixed(0));", " }", " }", "// update the Override CPP when the Override CPM is changed", " var col_override_cpm = api.column(8).data();", " for(var i = 0; i < col_override_cpm.length; i++){", " api.cell(i,7).data(((parseInt(col_override_cpm[i])*parseInt(col_population[i])/1000)/(100)).toFixed(0));", " }", "// Update the spot mixes", " var col_mix_percentage = api.column(2).data();", " var col_mix60_mix30 = api.column(10).data();", " var col_mix30_mix15 = api.column(11).data();", " for(var i = 0; i < col_mix_percentage.length; i++){", " api.cell(i,3).data((parseFloat(col_mix_percentage[i])*parseFloat(col_mix60_mix30[i])).toFixed(1));", " api.cell(i,4).data((parseFloat(col_mix_percentage[i])*parseFloat(col_mix30_mix15[i])).toFixed(1));", " }", "// Make the footer sums", " api.columns().eq(0).each(function(index){", " if(index == 0) return $(api.column(index).footer()).html('Mix Total');", " var coldata = api.column(index).data();", " var total = coldata", " .reduce(function(a, b){return parseInt(a) + parseInt(b)}, 0);", " if(index == 3 || index == 4 ||index == 5 || index == 6 || index==7 || index==8) {", " $(api.column(index).footer()).html('');", " } else {", " $(api.column(index).footer()).html(total);", " }", " if(total == 100) {", " $(api.column(index).footer()).css({'color': 'green'});", " } else {", " $(api.column(index).footer()).css({'color': 'red'});", " }", " })", " // update the parent row", " var col_share = api.column(2).data();", " var col_CPP = api.column(5).data();", " var col_CPM = api.column(6).data();", " var col_Historical_CPP = api.column(7).data();", " var col_Historical_CPM = api.column(8).data();", " var CPP = 0, CPM = 0, Historical_CPP = 0, Historical_CPM = 0;", " for(var i = 0; i < col_share.length; i++){", " CPP += (parseInt(col_share[i])*parseInt(col_CPP[i]).toFixed(0));", " CPM += (parseInt(col_share[i])*parseInt(col_CPM[i]).toFixed(0));", " Historical_CPP += (parseInt(col_share[i])*parseInt(col_Historical_CPP[i]).toFixed(0));", " Historical_CPM += (parseInt(col_share[i])*parseInt(col_Historical_CPM[i]).toFixed(0));", " }", " table.cell(rowIdx, j0+2).data((CPP/100).toFixed(2));", " table.cell(rowIdx, j0+3).data((CPM/100).toFixed(2));", " table.cell(rowIdx, j0+4).data((Historical_CPP/100).toFixed(2));", " table.cell(rowIdx, j0+5).data((Historical_CPM/100).toFixed(2));", " }", " var dataset = [];", " var n = d.length - 1;", " for(var i = 0; i < d[n].length; i++){", " var datarow = $.map(d[n][i], function (value, index) {", " return [value];", " });", " dataset.push(datarow);", " }", " var id = 'table#' + childId;", " if (Object.keys(d[n][0]).indexOf('_details') === -1) {", " var subtable = $(id).DataTable({", " 'data': dataset,", " 'autoWidth': true,", " 'deferRender': true,", " 'info': false,", " 'lengthChange': false,", " 'ordering': d[n].length > 1,", " 'order': [],", " 'paging': true,", " 'scrollX': false,", " 'scrollY': false,", " 'searching': false,", " 'sortClasses': false,", " 'pageLength': 50,", " 'rowCallback': rowCallback,", " 'headerCallback': headerCallback,", " 'footerCallback': footerCallback,", " 'columnDefs': [", " {targets: [0, 9, 10, 11], visible: false},", " {targets: '_all', className: 'dt-center'}", " ]", " });", " } else {", " var subtable = $(id).DataTable({", " 'data': dataset,", " 'autoWidth': true,", " 'deferRender': true,", " 'info': false,", " 'lengthChange': false,", " 'ordering': d[n].length > 1,", " 'order': [],", " 'paging': true,", " 'scrollX': false,", " 'scrollY': false,", " 'searching': false,", " 'sortClasses': false,", " 'pageLength': 50,", " 'rowCallback': rowCallback,", " 'headerCallback': headerCallback,", " 'footerCallback': footerCallback,", " 'columnDefs': [", " {targets: [0, 9, 10, 11], visible: false},", " {targets: -1, visible: false},", " {targets: 0, orderable: false, className: 'details-control'},", " {targets: '_all', className: 'dt-center'}", " ]", " }).column(0).nodes().to$().css({cursor: 'pointer'});", " }", " subtable.MakeCellsEditable({", " onUpdate: onUpdate,", " inputCss: 'my-input-class',", " columns: [2, 7, 8],", " confirmationButton: {", " confirmCss: 'my-confirm-class',", " cancelCss: 'my-cancel-class'", " }", " });", "};", "", "// display the child table on click", "var children = [];", # array to store the id's of the already created child tables "table.on('click', 'td.details-control', function(){", " var tbl = $(this).closest('table'),", " tblId = tbl.attr('id'),", " td = $(this),", " row = $(tbl).DataTable().row(td.closest('tr')),", " rowIdx = row.index();", " if(row.child.isShown()){", " row.child.hide();", " td.html('<img src=\"https://raw.githubusercontent.com/DataTables/DataTables/master/examples/resources/details_open.png\"/>');", " } else {", " var childId = tblId + '-child-' + rowIdx;", " if(children.indexOf(childId) === -1){", # this child table has not been created yet " children.push(childId);", " row.child(format(row.data(), childId)).show();", " td.html('<img src=\"https://raw.githubusercontent.com/DataTables/DataTables/master/examples/resources/details_close.png\"/>');", " format_datatable(row.data(), childId, rowIdx);", " }else{", " row.child(true);", " td.html('<img src=\"https://raw.githubusercontent.com/DataTables/DataTables/master/examples/resources/details_close.png\"/>');", " }", " }", "});" ) # Table table <- DT::datatable( Dat, callback = callback_js, rownames = rowNames, escape = -colIdx-1, style = "bootstrap4", extensions = 'Buttons', options = list( dom = "Blfrtip", buttons = list("copy", list( extend = "collection", buttons = "csv", text = "Download" ) ), lengthMenu = list(c(-1, 10, 20), c("All", 10, 20)), columnDefs = list( list(width = '30px', targets = 0), list(width = '545px', targets = 1), list(visible = FALSE, targets = ncol(Dat)-1+colIdx), list(orderable = FALSE, className = 'details-control', targets = colIdx), list(className = "dt-center", targets = "_all") ) ) ) # Call the html tools deps (js & css files in this directory) cell_edit_dep <- htmltools::htmlDependency( "CellEdit", "1.0.19", src = 'www/', script = "dataTables.cellEdit.js", stylesheet = "dataTables.cellEdit.css" ) table$dependencies <- c(table$dependencies, list(cell_edit_dep)) table %>% formatStyle( c('Market', 'SQAD CPP ($)', 'SQAD CPM ($)', 'Override CPP ($)', 'Override CPM ($)'), target = 'row', backgroundColor = "#F5F2F2" ) })
Try this: js <- c( "function(xlsx) {", " var table = $('#daypartTable').find('table').DataTable();", " // Letters for Excel columns.", " var LETTERS = [", " 'A','B','C','D','E','F','G','H','I','J','K','L','M',", " 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'", " ];", " // Get sheet.", " var sheet = xlsx.xl.worksheets['sheet1.xml'];", " // Get a clone of the sheet data. ", " var sheetData = $('sheetData', sheet).clone();", " // Clear the current sheet data for appending rows.", " $('sheetData', sheet).empty();", " // Row count in Excel sheet.", " var rowCount = 1;", " // Iterate each row in the sheet data.", " $(sheetData).children().each(function (index) {", " // Used for DT row() API to get child data.", " var rowIndex = index - 2;", # " // Don't process row if its the header row.", sprintf(" if (index > 1 && index < %d) {", nrow(Dat)+2), # " // Get row", " var row = $(this.outerHTML);", " // Set the Excel row attr to the current Excel row count.", " row.attr('r', rowCount);", " // Iterate each cell in the row to change the row number.", " row.children().each(function (index) {", " var cell = $(this);", " // Set each cell's row value.", " var rc = cell.attr('r');", " rc = rc.replace(/\\d+$/, \"\") + rowCount;", " cell.attr('r', rc);", " });", " // Get the row HTML and append to sheetData.", " row = row[0].outerHTML;", " $('sheetData', sheet).append(row);", " rowCount++;", " // Get the child data - could be any data attached to the row.", sprintf(" var childData = table.row(':eq(' + rowIndex + ')').data()[%d];", ncol(Dat)-1), # " if (childData.length > 0) {", " var colNames = Object.keys(childData[0]);", " // Prepare Excel formatted row", " headerRow = '<row r=\"' + rowCount +", " '\"><c t=\"inlineStr\" r=\"A' + rowCount +", " '\"><is><t></t></is></c>';", " for(var i = 0; i < colNames.length; i++){", " headerRow = headerRow +", " '<c t=\"inlineStr\" r=\"' + LETTERS[i+1] + rowCount +", " '\" s=\"7\"><is><t>' + colNames[i] +", " '</t></is></c>';", " }", " headerRow = headerRow + '</row>';", " // Append header row to sheetData.", " $('sheetData', sheet).append(headerRow);", " rowCount++; // Inc excelt row counter.", " }", " // The child data is an array of rows", " for (c = 0; c < childData.length; c++) {", " // Get row data.", " child = childData[c];", " // Prepare Excel formatted row", " var colNames = Object.keys(child);", " childRow = '<row r=\"' + rowCount +", " '\"><c t=\"inlineStr\" r=\"A' + rowCount +", " '\"><is><t></t></is></c>';", " for(var i = 0; i < colNames.length; i++){", " childRow = childRow +", " '<c t=\"inlineStr\" r=\"' + LETTERS[i+1] + rowCount +", " '\" s=\"5\"><is><t>' + child[colNames[i]] +", " '</t></is></c>';", " }", " childRow = childRow + '</row>';", " // Append row to sheetData.", " $('sheetData', sheet).append(childRow);", " rowCount++; // Inc excel row counter.", " }", " // Just append the header row and increment the excel row counter.", " } else {", " $('sheetData', sheet).append(this.outerHTML);", " rowCount++;", " }", " });", "}" ) datatable( Dat, callback = callback, rownames = rowNames, escape = -colIdx-1, extensions = "Buttons", options = list( dom = "Bfrtip", columnDefs = list( list(visible = FALSE, targets = ncol(Dat)-1+colIdx), list(orderable = FALSE, className = 'details-control', targets = colIdx), list(className = "dt-center", targets = "_all") ), buttons = list( list( extend = "excel", exportOptions = list( orthogonal = "export", columns = 0:(ncol(Dat)-2) ), orientation = "landscape", customize = JS(js) ) ) ) ) Here is an example of the generated Excel file: EDIT Better: excelTitle <- NULL # set to NULL if you don't want a title js <- c( "function(xlsx) {", " var table = $('#daypartTable').find('table').DataTable();", " // Number of columns.", " var ncols = table.columns().count();", " // Is there a title?", sprintf(" var title = %s;", ifelse(is.null(excelTitle), "false", "true")), " // Integer to Excel column: 0 -> A, 1 -> B, ..., 25 -> Z, 26 -> AA, ...", " var XLcolumn = function(j){", # https://codegolf.stackexchange.com/a/163919 " return j < 0 ? '' : XLcolumn(j/26-1) + String.fromCharCode(j % 26 + 65);", " };", " // Get sheet.", " var sheet = xlsx.xl.worksheets['sheet1.xml'];", " // Get a clone of the sheet data. ", " var sheetData = $('sheetData', sheet).clone();", " // Clear the current sheet data for appending rows.", " $('sheetData', sheet).empty();", " // Row count in Excel sheet.", " var rowCount = 1;", " // Iterate each row in the sheet data.", " $(sheetData).children().each(function (index) {", " // Used for DT row() API to get child data.", " var rowIndex = title ? index - 2 : index - 1;", " // Don't process row if it's the title row or the header row.", " var i0 = title ? 1 : 0;", " if (index > i0) {", " // Get row", " var row = $(this.outerHTML);", " // Set the Excel row attr to the current Excel row count.", " row.attr('r', rowCount);", " // Iterate each cell in the row to change the row number.", " row.children().each(function (index) {", " var cell = $(this);", " // Set each cell's row value.", " var rc = cell.attr('r');", " rc = rc.replace(/\\d+$/, \"\") + rowCount;", " cell.attr('r', rc);", " });", " // Get the row HTML and append to sheetData.", " row = row[0].outerHTML;", " $('sheetData', sheet).append(row);", " rowCount++;", " // Get the child data - could be any data attached to the row.", " var childData = table.row(':eq(' + rowIndex + ')').data()[ncols-1];", " if (childData.length > 0) {", " var colNames = Object.keys(childData[0]);", " // Prepare Excel formatted row", " var headerRow = '<row r=\"' + rowCount +", " '\"><c t=\"inlineStr\" r=\"A' + rowCount +", " '\"><is><t></t></is></c>';", " for(let i = 0; i < colNames.length; i++){", " headerRow = headerRow +", " '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +", " '\" s=\"7\"><is><t>' + colNames[i] +", " '</t></is></c>';", " }", " headerRow = headerRow + '</row>';", " // Append header row to sheetData.", " $('sheetData', sheet).append(headerRow);", " rowCount++; // Inc excel row counter.", " }", " // The child data is an array of rows", " for(let c = 0; c < childData.length; c++){", " // Get row data.", " var child = childData[c];", " // Prepare Excel formatted row", " var childRow = '<row r=\"' + rowCount +", " '\"><c t=\"inlineStr\" r=\"A' + rowCount +", " '\"><is><t></t></is></c>';", " var i = 0;", " for(let colname in child){", " childRow = childRow +", " '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +", " '\" s=\"5\"><is><t>' + child[colname] +", " '</t></is></c>';", " i++;", " }", " childRow = childRow + '</row>';", " // Append row to sheetData.", " $('sheetData', sheet).append(childRow);", " rowCount++; // Inc excel row counter.", " }", " // Just append the header row and increment the excel row counter.", " } else {", " $('sheetData', sheet).append(this.outerHTML);", " rowCount++;", " }", " });", "}" ) datatable( Dat, callback = callback, rownames = rowNames, escape = -colIdx-1, extensions = "Buttons", options = list( dom = "Bfrtip", columnDefs = list( list(visible = FALSE, targets = ncol(Dat)-1+colIdx), list(orderable = FALSE, className = 'details-control', targets = colIdx), list(className = "dt-center", targets = "_all") ), buttons = list( list( extend = "excel", exportOptions = list( orthogonal = "export", columns = 0:(ncol(Dat)-2) ), title = excelTitle, orientation = "landscape", customize = JS(js) ) ) ) ) EDIT 2 In callback_js, replace " var dataset = [];", " var n = d.length - 1;", " for(var i = 0; i < d[n].length; i++){", " var datarow = $.map(d[n][i], function (value, index) {", " return [value];", " });", " dataset.push(datarow);", " }", " var id = 'table#' + childId;", " if (Object.keys(d[n][0]).indexOf('_details') === -1) {", " var subtable = $(id).DataTable({", " 'data': dataset,", " 'autoWidth': true,", " 'deferRender': true,", " 'info': false,", " 'lengthChange': false,", " 'ordering': d[n].length > 1,", " 'order': [],", " 'paging': true,", " 'scrollX': false,", " 'scrollY': false,", " 'searching': false,", " 'sortClasses': false,", " 'pageLength': 50,", " 'rowCallback': rowCallback,", " 'headerCallback': headerCallback,", " 'footerCallback': footerCallback,", " 'columnDefs': [", " {targets: [0, 9, 10, 11], visible: false},", " {targets: '_all', className: 'dt-center'}", " ]", " });", " } else {", " var subtable = $(id).DataTable({", " 'data': dataset,", " 'autoWidth': true,", " 'deferRender': true,", " 'info': false,", " 'lengthChange': false,", " 'ordering': d[n].length > 1,", " 'order': [],", " 'paging': true,", " 'scrollX': false,", " 'scrollY': false,", " 'searching': false,", " 'sortClasses': false,", " 'pageLength': 50,", " 'rowCallback': rowCallback,", " 'headerCallback': headerCallback,", " 'footerCallback': footerCallback,", " 'columnDefs': [", " {targets: [0, 9, 10, 11], visible: false},", " {targets: -1, visible: false},", " {targets: 0, orderable: false, className: 'details-control'},", " {targets: '_all', className: 'dt-center'}", " ]", " }).column(0).nodes().to$().css({cursor: 'pointer'});", " }", with " var n = d.length - 1;", " var id = 'table#' + childId;", " var columns = Object.keys(d[n][0]).map(function(x){", " return {data: x, title: x};", " });", " if (Object.keys(d[n][0]).indexOf('_details') === -1) {", " var subtable = $(id).DataTable({", " 'data': d[n],", " 'columns': columns,", " 'autoWidth': true,", " 'deferRender': true,", " 'info': false,", " 'lengthChange': false,", " 'ordering': d[n].length > 1,", " 'order': [],", " 'paging': true,", " 'scrollX': false,", " 'scrollY': false,", " 'searching': false,", " 'sortClasses': false,", " 'pageLength': 50,", " 'rowCallback': rowCallback,", " 'headerCallback': headerCallback,", " 'footerCallback': footerCallback,", " 'columnDefs': [", " {targets: [0, 9, 10, 11], visible: false},", " {targets: '_all', className: 'dt-center'}", " ]", " });", " } else {", " var subtable = $(id).DataTable({", " 'data': d[n],", " 'columns': columns,", " 'autoWidth': true,", " 'deferRender': true,", " 'info': false,", " 'lengthChange': false,", " 'ordering': d[n].length > 1,", " 'order': [],", " 'paging': true,", " 'scrollX': false,", " 'scrollY': false,", " 'searching': false,", " 'sortClasses': false,", " 'pageLength': 50,", " 'rowCallback': rowCallback,", " 'headerCallback': headerCallback,", " 'footerCallback': footerCallback,", " 'columnDefs': [", " {targets: [0, 9, 10, 11], visible: false},", " {targets: -1, visible: false},", " {targets: 0, orderable: false, className: 'details-control'},", " {targets: '_all', className: 'dt-center'}", " ]", " }).column(0).nodes().to$().css({cursor: 'pointer'});", " }", Moreover, you probably don't want the hidden columns in the Excel file. So replace this code: " if (childData.length > 0) {", " var colNames = Object.keys(childData[0]);", " // Prepare Excel formatted row", ...... " // Append row to sheetData.", " $('sheetData', sheet).append(childRow);", " rowCount++; // Inc excel row counter.", " }", with " if (childData.length > 0) {", " var colNames = Object.keys(childData[0]).slice(1,9);", " // Prepare Excel formatted row", " var headerRow = '<row r=\"' + rowCount +", " '\"><c t=\"inlineStr\" r=\"A' + rowCount +", " '\"><is><t></t></is></c>';", " for(let i = 0; i < colNames.length; i++){", " headerRow = headerRow +", " '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +", " '\" s=\"7\"><is><t>' + colNames[i] +", " '</t></is></c>';", " }", " headerRow = headerRow + '</row>';", " // Append header row to sheetData.", " $('sheetData', sheet).append(headerRow);", " rowCount++; // Inc excel row counter.", " }", " // The child data is an array of rows", " for(let c = 0; c < childData.length; c++){", " // Get row data.", " var child = childData[c];", " // Prepare Excel formatted row", " var childRow = '<row r=\"' + rowCount +", " '\"><c t=\"inlineStr\" r=\"A' + rowCount +", " '\"><is><t></t></is></c>';", " for(let i = 0; i < colNames.length; i++){", " childRow = childRow +", " '<c t=\"inlineStr\" r=\"' + XLcolumn(i+1) + rowCount +", " '\" s=\"5\"><is><t>' + child[colNames[i]] +", " '</t></is></c>';", " }", " childRow = childRow + '</row>';", " // Append row to sheetData.", " $('sheetData', sheet).append(childRow);", " rowCount++; // Inc excel row counter.", " }", EDIT 3 This doesn't work if there are some periods in the column names of a child table. Here is the fix: " var columns = Object.keys(d[n][0]).map(function(x){", " return {data: x.replace('.', '\\\\\\.'), title: x};", " });",
How to store multiple SQLExec values in variable(s)
I am wondering whether in an Application Engine PeopleCode I can run a SQLExec command and if multiple rows are returned how they are stored in the variable? For example - I am working on adding the following code: SQLExec("SELECT C.UNIT_OF_MEASURE FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN)" , &InvItemId, &VendorID, &UOMResult In certain cases more than one row (value) may be passed back into the &UOMResult variable from the SQL query and I am not sure how PeopleCode will handle this, but ultimately I want to compare the value(s) from the &UOMResult variable to another variable called &UOM and if they are different (don't have a match) then do certain "stuff", else do "other stuff". Does the variable get transformed into an array if there is more than 1 value returned from the SQL? Just wondering what this would look like... Thanks for any feedback you have. 10/17/18 EDIT: Local SQL &SQL; Local string &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Oprid, &PriceStatus, &VendorId_check, &insert_cols, &insert_select, &insert_where, &insert_sql, &Error, &MaxEffdt, &ItmField; Local date &Effdt; Local Record &ITM_VNDR_UOM_PR, &REC, &MASTER_ITEM_TBL; &Oprid = "'BATCH'"; &PriceStatus = "2"; &Error = "N"; MessageBox(0, "", 0, 0, "**** BEGINING OF VALIDATION ERRORS ****"); &SQL = CreateSQL("SELECT VENDOR_ID, INV_ITEM_ID, ITM_ID_VNDR, UNIT_OF_MEASURE, CONVERSION_RATE, PRICE_VNDR, %DateOut(EFFDT), ITEM_FIELD_C10_B FROM PS_GH_ITM_PR_UPDT ORDER BY VENDOR_ID, INV_ITEM_ID, ITM_ID_VNDR", &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Effdt, &ItmField); MessageBox(0, "", 0, 0, &VendorId | " " | &InvItemId | " " | &ItmIdVndr | " " | &UOM | " " | &ConvRate | " " | &PriceVndr | " " | &Effdt | " " | &ItmField | " " | &Error); While &SQL.Fetch(&VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &PriceVndr, &Effdt, &ItmField) SQLExec("SELECT A.VENDOR_ID FROM PS_ITM_VENDOR A, PS_ITM_VNDR_UOM B WHERE A.SETID = B.SETID AND A.INV_ITEM_ID = B.INV_ITEM_ID AND A.VENDOR_SETID = B.VENDOR_SETID AND A.VENDOR_ID = B.VENDOR_ID AND A.VENDOR_ID = :1 AND A.INV_ITEM_ID = :2 AND A.ITM_ID_VNDR = :3 AND A.ITM_VNDR_PRIORITY = 1 AND B.UNIT_OF_MEASURE = :4 AND B.CONVERSION_RATE = :5", &VendorId, &InvItemId, &ItmIdVndr, &UOM, &ConvRate, &VendorId_check); If None(&VendorId_check) Then; &Error = "Y"; MessageBox(0, "", 0, 0, &VendorId | " " | &InvItemId | " " | &ItmIdVndr | " " | &UOM | " " | &ConvRate | " " | &PriceVndr | " " | &Effdt | " " | &ItmField | " " | &Error); Else; &CurrentDateTime = %Datetime; &Oprid = %OperatorId; &RECITEM = CreateRecord(Record.ITM_VNDR_UOM_PR); /*CHC Modification - Denise Smith - 8/8/2012 - CHC_PO_96588 - Begin */ /*SQLExec("SELECT TO_CHAR(C.EFFDT,'DD-MON-YYYY') FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.UNIT_OF_MEASURE = :3 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN) ", &InvItemId, &VendorId, &UOM, &MaxEffdt);*/ /*GETTING MAX EFFECTIVE DATED ROW TO COPY EXISTING ROW VALUES FROM INTO NEW ROW */ SQLExec("SELECT C.EFFDT FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.UNIT_OF_MEASURE = :3 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN) ", &InvItemId, &VendorId, &UOM, &MaxEffdt); &SQL2 = CreateSQL("SELECT C.UNIT_OF_MEASURE FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN) ", &InvItemId, &VendorId); /* This is where I am afraid the While loop will create extra inserts if the SQL above contains more than 1 Row. That is why I only want to evaluate only once if possible. For example if I am wanting to add a new price with a new UOM -'TP' that does not already exist for this item I want to look at the output value(s) from above &SQL2 and compare to my &UOM variable. If I keep this logic in a While loop I'm afraid it will end up creating more insert's then necessary */ While &SQL2.Fetch(&UOMResult) If &UOM = &UOMResult Then; SQLExec("%SelectAll(:1) WHERE INV_ITEM_ID = :2 AND VENDOR_ID = :3 AND UNIT_OF_MEASURE = :4 AND (CONVERT(CHAR(10),EFFDT,121)) = :5", &RECITEM, &InvItemId, &VendorId, &UOM, &MaxEffdt, &RECITEM); /*SQLExec("%SelectAll(:1) WHERE INV_ITEM_ID = :2 AND VENDOR_ID = :3 AND UNIT_OF_MEASURE = :4 AND EFFDT = :5", &RECITEM, &InvItemId, &VendorId, &UOM, &MaxEffdt, &RECITEM); */ &new_UNIT_OF_MEASURE = &RECITEM.UNIT_OF_MEASURE.Value; &REC = CreateRecord(Record.ITM_VNDR_UOM_PR); &REC.SETID.Value = &RECITEM.SETID.Value; &REC.INV_ITEM_ID.Value = &RECITEM.INV_ITEM_ID.Value; &REC.VENDOR_SETID.Value = &RECITEM.VENDOR_SETID.Value; &REC.VENDOR_ID.Value = &RECITEM.VENDOR_ID.Value; &REC.VNDR_LOC.Value = &RECITEM.VNDR_LOC.Value; &REC.UNIT_OF_MEASURE.Value = &RECITEM.UNIT_OF_MEASURE.Value; &REC.CURRENCY_CD.Value = &RECITEM.CURRENCY_CD.Value; &REC.QTY_MIN.Value = &RECITEM.QTY_MIN.Value; &REC.EFFDT.Value = &Effdt; &REC.EFF_STATUS.Value = &RECITEM.EFF_STATUS.Value; &REC.PRICE_VNDR.Value = &PriceVndr; &REC.UNIT_PRC_TOL.Value = &RECITEM.UNIT_PRC_TOL.Value; &REC.EXT_PRC_TOL.Value = &RECITEM.EXT_PRC_TOL.Value; &REC.PCT_UNIT_PRC_TOL.Value = &RECITEM.PCT_UNIT_PRC_TOL.Value; &REC.PCT_EXT_PRC_TOL.Value = &RECITEM.PCT_EXT_PRC_TOL.Value; &REC.USE_STD_TOLERANCES.Value = &RECITEM.USE_STD_TOLERANCES.Value; &REC.QTY_RECV_TOL_PCT.Value = &RECITEM.QTY_RECV_TOL_PCT.Value; &REC.UNIT_PRC_TOL_L.Value = &RECITEM.UNIT_PRC_TOL_L.Value; &REC.PCT_UNIT_PRC_TOL_L.Value = &RECITEM.PCT_UNIT_PRC_TOL_L.Value; &REC.EXT_PRC_TOL_L.Value = &RECITEM.EXT_PRC_TOL_L.Value; &REC.PCT_EXT_PRC_TOL_L.Value = &RECITEM.PCT_EXT_PRC_TOL_L.Value; &REC.BU_PRICE_STATUS.Value = "2"; &REC.STD_PRICE_STATUS.Value = "2"; &REC.LEAD_TIME.Value = &RECITEM.LEAD_TIME.Value; &REC.OPRID_MODIFIED_BY.Value = &Oprid; &REC.LAST_DTTM_UPDATE.Value = &CurrentDateTime; &REC.PRICE_CHANGE.Value = &RECITEM.PRICE_CHANGE.Value; &REC.Insert(); Else; SQLExec("%SelectAll(:1) WHERE INV_ITEM_ID = :2 AND VENDOR_ID = :3 AND UNIT_OF_MEASURE = :4 AND (CONVERT(CHAR(10),EFFDT,121)) = :5", &RECITEM, &InvItemId, &VendorId, &UOMResult, &MaxEffdt, &RECITEM); /*SQLExec("%SelectAll(:1) WHERE INV_ITEM_ID = :2 AND VENDOR_ID = :3 AND UNIT_OF_MEASURE = :4 AND EFFDT = :5", &RECITEM, &InvItemId, &VendorId, &UOMResult, &MaxEffdt, &RECITEM); */ &new_UNIT_OF_MEASURE = &RECITEM.UNIT_OF_MEASURE.Value; &REC = CreateRecord(Record.ITM_VNDR_UOM_PR); &REC.SETID.Value = &RECITEM.SETID.Value; &REC.INV_ITEM_ID.Value = &RECITEM.INV_ITEM_ID.Value; &REC.VENDOR_SETID.Value = &RECITEM.VENDOR_SETID.Value; &REC.VENDOR_ID.Value = &RECITEM.VENDOR_ID.Value; &REC.VNDR_LOC.Value = &RECITEM.VNDR_LOC.Value; &REC.UNIT_OF_MEASURE.Value = &RECITEM.UNIT_OF_MEASURE.Value; &REC.CURRENCY_CD.Value = &RECITEM.CURRENCY_CD.Value; &REC.QTY_MIN.Value = &RECITEM.QTY_MIN.Value; &REC.EFFDT.Value = &Effdt; &REC.EFF_STATUS.Value = &RECITEM.EFF_STATUS.Value; &REC.PRICE_VNDR.Value = &PriceVndr; &REC.UNIT_PRC_TOL.Value = &RECITEM.UNIT_PRC_TOL.Value; &REC.EXT_PRC_TOL.Value = &RECITEM.EXT_PRC_TOL.Value; &REC.PCT_UNIT_PRC_TOL.Value = &RECITEM.PCT_UNIT_PRC_TOL.Value; &REC.PCT_EXT_PRC_TOL.Value = &RECITEM.PCT_EXT_PRC_TOL.Value; &REC.USE_STD_TOLERANCES.Value = &RECITEM.USE_STD_TOLERANCES.Value; &REC.QTY_RECV_TOL_PCT.Value = &RECITEM.QTY_RECV_TOL_PCT.Value; &REC.UNIT_PRC_TOL_L.Value = &RECITEM.UNIT_PRC_TOL_L.Value; &REC.PCT_UNIT_PRC_TOL_L.Value = &RECITEM.PCT_UNIT_PRC_TOL_L.Value; &REC.EXT_PRC_TOL_L.Value = &RECITEM.EXT_PRC_TOL_L.Value; &REC.PCT_EXT_PRC_TOL_L.Value = &RECITEM.PCT_EXT_PRC_TOL_L.Value; &REC.BU_PRICE_STATUS.Value = "2"; &REC.STD_PRICE_STATUS.Value = "2"; &REC.LEAD_TIME.Value = &RECITEM.LEAD_TIME.Value; &REC.OPRID_MODIFIED_BY.Value = &Oprid; &REC.LAST_DTTM_UPDATE.Value = &CurrentDateTime; &REC.PRICE_CHANGE.Value = &RECITEM.PRICE_CHANGE.Value; &REC.Insert(); End-If; End-While; End-If; /* KDR - 10/11/2018 - Added field ITEM_FIELD_C10_B (&ItmField) to CSV file layout and insert into PS_MASTER_ITEM_TBL (&MASTER_ITEM_TBL) */ If None(&ItmField) Then; &Error = "Y"; MessageBox(0, "", 0, 0, &VendorId | " " | &InvItemId | " " | &ItmIdVndr | " " | &UOM | " " | &ConvRate | " " | &PriceVndr | " " | &Effdt | " " | &ItmField); Else; SQLExec("UPDATE PS_MASTER_ITEM_TBL SET ITEM_FIELD_C10_B = :1 WHERE INV_ITEM_ID = :2 AND SETID = 'SHARE' ", &ItmField, &InvItemId); /* Else; &REC1 = CreateRecord(Record.MASTER_ITEM_TBL); &REC1.ITEM_FIELD_C10_B.Value = &ItmField; &REC1.SETID.Value = "SHARE"; &REC1.INV_ITEM_ID.Value = &InvItemId; &REC1.Update(); End-If; */ End-If; End-While; MessageBox(0, "", 0, 0, "**** END OF VALIDATION ERRORS ****"); MessageBox(0, "", 0, 0, " ");`
SQLExec only ever stores the results of 1 row. If you want to be able to loop through multiple rows returned you need to use a SQL object. Further documentation can be found in the Enterprise PeopleTools PeopleBook: PeopleCode API Reference > SQL Class Local SQL &sql; &sql = createsql("SELECT C.UNIT_OF_MEASURE FROM PS_ITM_VNDR_UOM_PR C WHERE C.INV_ITEM_ID = :1 AND C.VENDOR_ID = :2 AND C.EFFDT = (SELECT MAX(C1.EFFDT) FROM PS_ITM_VNDR_UOM_PR C1 WHERE C.SETID = C1.SETID AND C.INV_ITEM_ID = C1.INV_ITEM_ID AND C.VENDOR_SETID = C1.VENDOR_SETID AND C.VENDOR_ID = C1.VENDOR_ID AND C.VNDR_LOC = C1.VNDR_LOC AND C.UNIT_OF_MEASURE = C1.UNIT_OF_MEASURE AND C.CURRENCY_CD = C1.CURRENCY_CD AND C.QTY_MIN = C1.QTY_MIN)",&InvItemId, &VendorID); while &sql.fetch(&UOMResult) /* Do you logic here */ end-while; &sql.close;
When I use App Engine and I have to create 2 or more result sets based on a differing set of criteria, I take 2 approaches: if can I use case statements in the field select clause to achieve my objective, then this is the preferred method. write SQLs in multiple steps that are mutually exclusive (from source table perspective) and populate the same target table. If possible, I will avoid manipulating SQL with PeopleCode because then you have to deal with PeopleCode quirks as well as the database itself.
Convert Cheat Engine base address
I found a memory address and used Cheat Engine's pointer scan to get referring pointers. To use it in a script I need a base address, which is [game.exe+009274]. How to convert this to an address for use in AutoIt script? I use NomadMemory.au3 UDF.
I have written 2 function some time ago. One to load all the modules loaded with the process and one to get the base address of the module you need. Both might be handy here. Local $iPID = WinGetProcess("app.exe") Local $sLoadedModules = _ProcessGetLoadedModules($iPID) Local $My_dll = _MemoryModuleGetBaseAddress($iPID, "My.dll") For $i = 0 To UBound($sLoadedModules) - 1 ConsoleWrite($sLoadedModules[$i] & #LF) ; find your process here Next ConsoleWrite($My_dll & #LF) Func _ProcessGetLoadedModules($iPID) Local Const $PROCESS_QUERY_INFORMATION = 0x0400 Local Const $PROCESS_VM_READ = 0x0010 Local $aCall, $hPsapi = DllOpen("Psapi.dll") Local $hProcess, $tModulesStruct $tModulesStruct = DllStructCreate("hwnd [200]") Local $SIZEOFHWND = DllStructGetSize($tModulesStruct) / 200 $hProcess = _WinAPI_OpenProcess(BitOR($PROCESS_QUERY_INFORMATION, $PROCESS_VM_READ), False, $iPID) If Not $hProcess Then Return SetError(1, 0, -1) $aCall = DllCall($hPsapi, "int", "EnumProcessModules", "ptr", $hProcess, "ptr", DllStructGetPtr($tModulesStruct), "dword", DllStructGetSize($tModulesStruct), "dword*", "") If $aCall[4] > DllStructGetSize($tModulesStruct) Then $tModulesStruct = DllStructCreate("hwnd [" & $aCall[4] / $SIZEOFHWND & "]") $aCall = DllCall($hPsapi, "int", "EnumProcessModules", "ptr", $hProcess, "ptr", DllStructGetPtr($tModulesStruct), "dword", $aCall[4], "dword*", "") EndIf Local $aReturn[$aCall[4] / $SIZEOFHWND] For $i = 0 To UBound($aReturn) - 1 $aCall = DllCall($hPsapi, "dword", "GetModuleFileNameExW", "ptr", $hProcess, "ptr", DllStructGetData($tModulesStruct, 1, $i + 1), "wstr", "", "dword", 65536) $aReturn[$i] = $aCall[3] Next _WinAPI_CloseHandle($hProcess) DllClose($hPsapi) Return $aReturn EndFunc ;==>_ProcessGetLoadedModules Func _MemoryModuleGetBaseAddress($iPID, $sModule) If Not ProcessExists($iPID) Then Return SetError(1, 0, 0) If Not IsString($sModule) Then Return SetError(2, 0, 0) Local $PSAPI = DllOpen("psapi.dll") Local $hProcess Local $PERMISSION = BitOR(0x0002, 0x0400, 0x0008, 0x0010, 0x0020) If $iPID > 0 Then Local $hProcess = DllCall("kernel32.dll", "ptr", "OpenProcess", "dword", $PERMISSION, "int", 0, "dword", $iPID) If $hProcess[0] Then $hProcess = $hProcess[0] EndIf EndIf Local $Modules = DllStructCreate("ptr[1024]") Local $aCall = DllCall($PSAPI, "int", "EnumProcessModules", "ptr", $hProcess, "ptr", DllStructGetPtr($Modules), "dword", DllStructGetSize($Modules), "dword*", 0) If $aCall[4] > 0 Then Local $iModnum = $aCall[4] / 4 Local $aTemp For $i = 1 To $iModnum $aTemp = DllCall($PSAPI, "dword", "GetModuleBaseNameW", "ptr", $hProcess, "ptr", Ptr(DllStructGetData($Modules, 1, $i)), "wstr", "", "dword", 260) If $aTemp[3] = $sModule Then DllClose($PSAPI) Return Ptr(DllStructGetData($Modules, 1, $i)) EndIf Next EndIf DllClose($PSAPI) Return SetError(-1, 0, 0) EndFunc ;==>_MemoryModuleGetBaseAddress
Creating a PDF with itextsharp works fine in development but fails when deployed to IIS 7
I am deploying and testing an application using IIS 7. It creates a PDF using ITextSharp, which works fine when running from VS2010. When running from IIS, I get an error: The document has no pages. Using the same data with the VS2010 development server, the PDF is printed OK. The error has nothing to do with a lack of pages. The itextsharp.dll is included in the bin folder under the IIS Web Site. What am I missing? Here is my code (though I do not tjhink it is relevant); protected void TextSharpMethod() { // get order details #region getOrdersData var ordersData = DataAccessLayer.OrdersDataHelpers.getOrderDataByOrderId(_intOrderId); #endregion if (ordersData != null) { #region getSupplierDetails // get supplier details var rowSupplier = (from s in _dataContextOrders.FMSSuppliers where s.ID == ordersData.SupplierID select new { s.ID, s.CommonShortName, s.ExternalRef, s.Name, s.Address, s.SupplierDetail.Telephone, s.SupplierDetail.WebAddress, s.SupplierDetail.Email, s.SupplierDetail.Fax }).FirstOrDefault(); #endregion #region getOrderLineData var orderLineData = (from ol in _dataContextOrders.OrderLines join o in _dataContextOrders.Orders on ol.OrderID equals o.ID join ec in _dataContextOrders.FMSExpenseCodes on ol.OrderLineExpenseCodeID equals ec.ID into group1 from g1 in group1.DefaultIfEmpty() join cc in _dataContextOrders.FMSCostCentres on ol.OrderLineCostCentreID equals cc.ID into group2 from g2 in group2.DefaultIfEmpty() select new { ol.ID, ol.OrderID, ol.OrderLineNumber, ol.OrderLineQty, ol.OrderLineDescription, ol.OrderLineUnitCost, ol.OrderLineUnitTax, ol.OrderLineTotal, ol.OrderLineExpenseCodeID, ol.GoodsReceivedQty, ol.InvoicedQty, ol.OrderLineCostCentreID, ol.OrderLineVatRate, ol.OrderLineUnitGross, ExpenseCode = g1.ExternalRef == null ? "" : g1.ExternalRef, CostCodeRef = g2.ExternalRef == null ? "" : g2.ExternalRef }).Where(ol => ol.OrderID == _intOrderId).OrderBy(ol => ol.OrderLineNumber); #endregion using (MemoryStream ms = new MemoryStream()) using (Document document = new Document(PageSize.A4, 25, 25, 30, 30)) using (PdfWriter writer = PdfWriter.GetInstance(document, ms)) { document.AddCreator("SVSIT"); document.AddTitle("PURCHASE ORDER"); document.Open(); #region setupPdfDoc // LOGO string path = Server.MapPath("/"); string imageLocation = path + "/Images/southView_integration_logo_applications.jpg"; imageLocation = imageLocation.Replace("\\", "/"); iTextSharp.text.Image bmp = iTextSharp.text.Image.GetInstance(imageLocation); // caution - image may not work if app is moved bmp.Alignment = Element.ALIGN_LEFT; bmp.ScalePercent(50f); document.Add(bmp); // COMPANY ADDRESS PdfPTable table = new PdfPTable(2); PdfPCell cell; //actual width of table in points (A4=595points) table.TotalWidth = 550f; table.LockedWidth = true; float[] widths = new float[] {2.75f, 2.75f}; table.SetWidths(widths); // 0=no border, 1=border table.DefaultCell.BorderWidth = 0; PdfBlankCell(table); PdfAddTableCell(table, "PURCHASE ORDER", _bold); PdfBlankCell(table); float flXPos = 842; // 842 - height of A4 in points table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent); // CONTACT PERSON table = new PdfPTable(4); //actual width of table in points (A4=595points) table.TotalWidth = 550f; table.LockedWidth = true; widths = new float[] {1f, 1.75f, 1.35f, 1.35f}; table.SetWidths(widths); // 0=no border, 1=border table.DefaultCell.BorderWidth = 0; PdfAddTableCell(table, "Contact Person", _norm); PdfAddTableCell(table, ordersData.OrderContactName, _norm); PdfAddTableCell(table, "Tel: " + ordersData.OrderContactTel, _norm); PdfAddTableCell(table, "Fax: " + ordersData.OrderContactFax, _norm); flXPos = 715; table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent); // SUPPLIER DETAILS table = new PdfPTable(1); table.TotalWidth = 270f; table.LockedWidth = true; table.DefaultCell.BorderWidth = 1; // has border PdfAddTableCell(table, "To (Supplier)", _bold); table.AddCell(ordersData.SupplierName); if (rowSupplier != null) { table.AddCell(rowSupplier.Address); // might want to break this up by line breaks } else { table.AddCell(" "); } flXPos = 695; table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent); // ORDER NO table = new PdfPTable(1); table.TotalWidth = 275f; table.LockedWidth = true; table.DefaultCell.BorderWidth = 0; table.DefaultCell.BorderWidthTop = 1; table.DefaultCell.BorderWidthLeft = 1; table.DefaultCell.BorderWidthRight = 1; PdfAddTableCell(table, "Order No: " + ordersData.PORef + " / 100630", _bold); table.DefaultCell.BorderWidthTop = 0; table.DefaultCell.BorderWidthLeft = 1; table.DefaultCell.BorderWidthRight = 1; PdfAddTableCell(table, " ", _bold); PdfBlankCell(table); PdfAddTableCell(table, "Date: " + ordersData.CreatedDate.ToShortDateString (), _bold); PdfAddTableCell(table, "Your ref: " + ordersData.OtherRef, _bold); PdfAddTableCell(table, " ", _bold); PdfAddTableCell(table, "PURCHASE ORDER NUMBER MUST BE", _bold); table.DefaultCell.BorderWidthTop = 0; table.DefaultCell.BorderWidthLeft = 1; table.DefaultCell.BorderWidthRight = 1; table.DefaultCell.BorderWidthBottom = 1; PdfAddTableCell(table, "QUOTED ON INVOICE TO ENSURE PAYMENT", _bold); table.WriteSelectedRows(0, -1, document.Left + 275, flXPos, writer.DirectContent); flXPos = 595; // DELIVERY ADDRESS table = new PdfPTable(1); table.TotalWidth = 270f; table.LockedWidth = true; table.DefaultCell.BorderWidth = 1; // has border PdfAddTableCell(table, "Delivery Address:", _bold); table.AddCell(ordersData.DeliveryContactName); table.AddCell(ordersData.DeliveryAddress); table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent); // INVOICE ADDRESS table = new PdfPTable(1); table.TotalWidth = 275f; table.LockedWidth = true; table.DefaultCell.BorderWidth = 0; table.DefaultCell.BorderWidthTop = 1; table.DefaultCell.BorderWidthLeft = 1; table.DefaultCell.BorderWidthRight = 1; PdfAddTableCell(table, "Invoice Address:", _bold); table.DefaultCell.BorderWidthTop = 0; table.DefaultCell.BorderWidthLeft = 1; table.DefaultCell.BorderWidthRight = 1; PdfAddTableCell(table, " CVCHA", _norm); PdfAddTableCell(table, " 11 High Street", _norm); PdfAddTableCell(table, " Castle Vale", _norm); PdfAddTableCell(table, " Birmingham", _norm); table.DefaultCell.BorderWidthTop = 0; table.DefaultCell.BorderWidthLeft = 1; table.DefaultCell.BorderWidthRight = 1; table.DefaultCell.BorderWidthBottom = 1; PdfAddTableCell(table, " B35 7PR", _norm); table.WriteSelectedRows(0, -1, document.Left + 275, flXPos, writer.DirectContent); // ORDER LINES table = new PdfPTable(5); table.TotalWidth = 550f; table.LockedWidth = true; widths = new float[] {2.70f, .7f, .7f, .7f, .7f}; table.SetWidths(widths); table.DefaultCell.BorderWidth = 1; PdfAddTableCell(table, "Description", _bold); PdfAddTableCell(table, "Code", _bold); PdfAddTableCell(table, "Quantity", _bold); PdfAddTableCell(table, "Unit Cost", _bold); PdfAddTableCell(table, "Total Cost", _bold); // 13 rows // get order lines data int i1 = 0; foreach (var orderLine in orderLineData) { if (orderLine != null) { PdfAddTableCell(table, orderLine.OrderLineDescription, _norm); PdfAddTableCell(table, orderLine .CostCodeRef +", " + orderLine.ExpenseCode , _norm); // code - to do PdfAlignRightTableCell(table, orderLine.OrderLineQty.ToString(), _norm); PdfAlignRightTableCell (table, orderLine.OrderLineUnitCost.ToString(), _norm); PdfAlignRightTableCell(table, orderLine.OrderLineTotal.ToString(), _norm); i1++; } } // fill remaining grid for (int i = i1; i <= 13; i++) { PdfAddTableCell(table, " ", _norm); PdfAddTableCell(table, " ", _norm); PdfAddTableCell(table, " ", _norm); PdfAddTableCell(table, " ", _norm); PdfAddTableCell(table, " ", _norm); } // DELIVERY DATE / TOTAL LINE PdfAddTableCell(table, "Required Delivery Date: " + ordersData.ExpectedDeliveryDate, _bold); _chunk = new Chunk("Total: £", _bold ); cell = new PdfPCell(new Phrase(_chunk)); cell.Colspan = 3; table.DefaultCell.BorderWidth = 1; table.AddCell(cell); _chunk = new Chunk(ordersData.TotalAmount.ToString("0.00"), _bold); cell = new PdfPCell(new Phrase(_chunk)); cell.Colspan = 1; table.DefaultCell.VerticalAlignment = Element.ALIGN_RIGHT; table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT; table.AddCell(cell); flXPos = 490; table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent); // PREPARED BY / AUTHORISED BY table = new PdfPTable(3); table.TotalWidth = 550f; table.LockedWidth = true; widths = new float[] {1.83f, 1.83f, 1.83f}; table.SetWidths(widths); table.DefaultCell.BorderWidth = 1; PdfAddTableCell(table, "Prepared By:" + "", _bold); PdfAddTableCell(table, "Signature:" + "", _bold); PdfAddTableCell(table, "Date:" + "", _bold); PdfAddTableCell(table, "Authorised By:" + "", _bold); // ApproverPersonID PdfAddTableCell(table, "Signature:" + "", _bold); PdfAddTableCell(table, "Date:" + "", _bold); flXPos = 195; table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent); // FOOTER table = new PdfPTable(1); table.TotalWidth = 550f; table.LockedWidth = true; table.DefaultCell.BorderWidth = 0; PdfAddTableCell(table, "Distibution of Copies", _norm); PdfAddTableCell(table, "1. White - Supplier 2. Yellow - Finance Section 3. Pink - Originator (Budget Holder)", _norm); PdfAddTableCell(table, "Industrial & Provident Society No. 28414R Housing Corporation No. L4118", _norm); flXPos = 95; table.WriteSelectedRows(0, -1, document.Left, flXPos, writer.DirectContent); #endregion document.Close(); writer.Close(); #region writeToDatabase MemoryStream ms2 = new MemoryStream(ms.ToArray()); WritePdfToDatabase(ms2); #endregion Response.ContentType = "pdf/application"; Response.AddHeader("content-disposition", "attachment;filename=PurchaseOrder.pdf"); Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length); } } } protected void WritePdfToDatabase(MemoryStream ms2) { BinaryReader br = new BinaryReader(ms2); Byte[] bytes = br.ReadBytes((Int32)ms2.Length); br.Close(); DocumentsDataHelper.UpdateDocument(bytes, "pdf/application", "Purchase Order",_intOrderId ,1); } protected void PdfBlankCell(PdfPTable table) { _chunk = new Chunk("", _norm); _phrase = new Phrase(_chunk); table.AddCell(_phrase); } protected void PdfAddTableCell(PdfPTable table, string s, Font f) { _chunk = new Chunk(s, f); _phrase = new Phrase(_chunk); table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT; table.AddCell(_phrase); } protected void PdfAlignRightTableCell(PdfPTable table, string s, Font f) { _chunk = new Chunk(s, f); _phrase = new Phrase(_chunk); table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT; table.AddCell(_phrase); } protected void PdfTableFieldAndHeader(string heading, string value, PdfPTable table) { PdfAddTableCell(table, heading, _bold); PdfAddTableCell(table, value, _norm); } protected void PdfBoldAndNormLine(string text1, string text2, Document document) { Chunk c1 = new Chunk(text1, FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.BOLD)); Chunk c2 = new Chunk(text2, FontFactory.GetFont(FontFactory.TIMES_ROMAN, 12.0f, iTextSharp.text.Font.NORMAL)); Phrase p1 = new Phrase(); p1.Add(c1); p1.Add(c2); Paragraph p = new Paragraph(); p.Add(p1); p.Alignment = Element.ALIGN_LEFT; document.Add(p); }
My website only shows user profiles with the first 2 ID numbers. How can I display all user profiles correctly?
I´m doing a website in VB.NET that allows users to create and view profiles. For the first two users, the profile shows perfectly, but for any user with an ID number equal or higher than three it doesn't work. What could be the reason for that and how can I fix it? This is the code that loads the profile in a webform: Public Sub cargarPerfil(cnn As SqlConnection, cmd As SqlCommand) Dim perfil, nombre, nick, pais, ciudad, codigo, telefono, nacimiento, nivel, tipo1, tipo2 As String Dim social, artistico, comercial, rango, titulo1, titulo2, titulo3, foto, credito As String Dim da As New SqlDataAdapter Dim dt As DataTable perfil = "SELECT USUARIONOMBREREAL, USUARIONICK, PAISNOMBRE AS PAIS, CIUDADNOMBRE AS CIUDAD, USUARIOCODIGO, USUARIOTELEFONO, USUARIONACIMIENTO, " & _ "TIPONOMBRE AS TIPO1, NIVELNOMBRE AS NIVEL, USUARIOSOCIAL, USUARIOARTISTICO, USUARIOCOMERCIAL, USUARIOFOTO, USUARIOCREDITO, " & _ "RANGONOMBRE AS RANGO, TITULONOMBRE AS TITULO1 FROM USUARIO " & _ "INNER JOIN PAIS ON USUARIO.USUARIOPAIS = PAIS.PAISID " & _ "INNER JOIN CIUDAD ON USUARIO.USUARIOCIUDAD = CIUDADID " & _ "INNER JOIN TIPO ON USUARIO.USUARIOTIPO1 = TIPO.TIPOID " & _ "INNER JOIN NIVEL ON USUARIO.USUARIONIVEL = NIVEL.NIVELID " & _ "INNER JOIN RANGO ON USUARIO.USUARIORANGO = RANGO.RANGOID " & _ "INNER JOIN TITULO ON USUARIO.USUARIOTITULO1 = TITULO.TITULOID " & _ "WHERE USUARIOID = '" & Session(Principal.User.UserID) & "' AND USUARIONICK = '" & Session(Principal.User.UserName) & "'" With cmd .CommandType = CommandType.Text .CommandText = perfil .Connection = cnn End With da.SelectCommand = cmd dt = New DataTable da.Fill(dt) nombre = dt.Rows.Item(0).Item("USUARIONOMBREREAL") nick = dt.Rows.Item(0).Item("USUARIONICK") pais = dt.Rows.Item(0).Item("PAIS") ciudad = dt.Rows.Item(0).Item("CIUDAD") codigo = dt.Rows.Item(0).Item("USUARIOCODIGO") telefono = dt.Rows.Item(0).Item("USUARIOTELEFONO") nacimiento = dt.Rows.Item(0).Item("USUARIONACIMIENTO") tipo1 = dt.Rows.Item(0).Item("TIPO1") nivel = dt.Rows.Item(0).Item("NIVEL") social = dt.Rows.Item(0).Item("USUARIOSOCIAL") artistico = dt.Rows.Item(0).Item("USUARIOARTISTICO") comercial = dt.Rows.Item(0).Item("USUARIOCOMERCIAL") rango = dt.Rows.Item(0).Item("RANGO") titulo1 = dt.Rows.Item(0).Item("TITULO1") foto = "~/0/" + nombre + ".jpg" credito = dt.Rows.Item(0).Item("USUARIOCREDITO") dt = Nothing perfil = "SELECT TIPONOMBRE AS TIPO2, TITULONOMBRE AS TITULO2 FROM USUARIO " & _ "INNER JOIN TIPO ON USUARIO.USUARIOTIPO2 = TIPO.TIPOID " & _ "INNER JOIN TITULO ON USUARIO.USUARIOTITULO2 = TITULO.TITULOID " & _ "WHERE USUARIOID = '" & Session(Principal.User.UserID) & "' AND USUARIONICK = '" & Session(Principal.User.UserName) & "'" With cmd .CommandType = CommandType.Text .CommandText = perfil .Connection = cnn End With da.SelectCommand = cmd dt = New DataTable da.Fill(dt) tipo2 = dt.Rows.Item(0).Item("TIPO2") titulo2 = dt.Rows.Item(0).Item("TITULO2") dt = Nothing perfil = "SELECT TITULONOMBRE AS TITULO3 FROM USUARIO INNER JOIN TITULO ON USUARIO.USUARIOTITULO3 = TITULO.TITULOID " & _ "WHERE USUARIOID = '" & Session(Principal.User.UserID) & "' AND USUARIONICK = '" & Session(Principal.User.UserName) & "'" With cmd .CommandType = CommandType.Text .CommandText = perfil .Connection = cnn End With da.SelectCommand = cmd dt = New DataTable da.Fill(dt) titulo3 = dt.Rows.Item(0).Item("TITULO3") dt = Nothing lblNombre.Text = nombre lblNick.Text = nick lblPais.Text = pais lblCiudad.Text = ciudad lblCodigo.Text = codigo lblTelefono.Text = telefono lblNacimiento.Text = nacimiento lblTipo1.Text = tipo1 lblTipo2.Text = tipo2 lblNivel.Text = nivel lblSocial.Text = social lblArtistico.Text = artistico lblComercial.Text = comercial lblRango.Text = rango lblTitulo1.Text = titulo1 lblTitulo2.Text = titulo2 lblTitulo3.Text = titulo3 imgPerfil.ImageUrl = foto lblCredito.Text = credito End Sub This is the code that creates profiles in a different webform: Private Sub registro(cnn As SqlConnection, cmd As SqlCommand) Dim nuevo, nombre, nick, pass, mail, pais, ciudad, codigo, telefono, nacimiento, nivel, tipo1, tipo2 As String Dim social, artistico, comercial, rango, titulo1, titulo2, titulo3, foto, contrato As String Dim savePathF As String = "F:\ComparteME\ComparteME\0\" Dim savePathC As String = "F:\ComparteME\ComparteME\Reconocimientos\" Dim fileNameF As String = txtNombreReal.Text + ".jpg" Dim fileNameC As String = "Reconocimiento - " + txtNombreReal.Text + ".jpg" Dim pathToCheckF As String = savePathF + fileNameF Dim pathToCheckC As String = savePathC + fileNameC Dim tempfileNameF As String = "" Dim tempfileNameC As String = "" nuevo = "" nombre = txtNombreReal.Text nick = txtNick.Text pass = txtPassword.Text mail = txtMail.Text pais = ddlPais.SelectedValue ciudad = ddlCiudad.SelectedValue codigo = txtCodigo.Text telefono = txtTelefono.Text nacimiento = txtNacimiento.Text nivel = ddlNivel.SelectedValue tipo1 = ddlTipo1.SelectedValue tipo2 = ddlTipo2.SelectedValue foto = "" contrato = "" social = 0 artistico = 0 comercial = 0 rango = 1 titulo1 = 0 titulo2 = 0 titulo3 = 0 If (uplFoto.HasFile) Then If (System.IO.File.Exists(pathToCheckF)) Then Dim counter As Integer = 0 While (System.IO.File.Exists(pathToCheckF)) tempfileNameF = counter.ToString() + fileNameF pathToCheckF = savePathF + tempfileNameF counter = counter + 1 End While If counter > 0 Then fileNameF = tempfileNameF End If End If savePathF += fileNameF uplFoto.SaveAs(savePathF) foto = savePathF End If If (uplReconocimiento.HasFile) Then If (System.IO.File.Exists(pathToCheckC)) Then Dim counter As Integer = 0 While (System.IO.File.Exists(pathToCheckC)) tempfileNameC = counter.ToString() + fileNameC pathToCheckC = savePathC + tempfileNameC counter = counter + 1 End While If counter > 0 Then fileNameC = tempfileNameC End If End If savePathC += fileNameC uplReconocimiento.SaveAs(savePathC) contrato = savePathC End If nuevo = "INSERT INTO USUARIO (USUARIOID, USUARIONOMBREREAL, USUARIONICK, USUARIOPASSWORD, USUARIOENCRIPTADO, USUARIOCORREO, USUARIOPAIS, USUARIOCIUDAD, USUARIOCODIGO, USUARIOTELEFONO, " & _ "USUARIONACIMIENTO, USUARIOTIPO1, USUARIOTIPO2, USUARIONIVEL, USUARIOSOCIAL, USUARIOARTISTICO, USUARIOCOMERCIAL, USUARIORANGO, USUARIOTITULO1, USUARIOTITULO2, " & _ "USUARIOTITULO3, USUARIOFOTO, USUARIOCONTRATO) " & _ "SELECT (ISNULL(MAX(USUARIOID), 0)+1), '" & nombre & "', '" & nick & "', '" & pass & "', PWDENCRYPT('" & pass & "'), '" & mail & "', " & pais & ", " & ciudad & ", " & codigo & ", " & _ "" & telefono & ", '" & nacimiento & "', " & tipo1 & ", " & tipo2 & ", " & nivel & ", " & social & ", " & artistico & ", " & comercial & ", " & rango & ", " & _ "" & titulo1 & ", " & titulo2 & ", " & titulo3 & ", '" & foto & "', '" & contrato & "' FROM USUARIO " cnn.Open() cmd.CommandText = nuevo cmd.Connection = cnn cmd.ExecuteNonQuery() cnn.Close() lblSuccess.Text = "¡Bienvenido a ComparteME! En un momento se comprobarán tus datos y tu cuenta será activada. Intenta iniciar sesión." tblRegistro.Visible = False tblSuccess.Visible = True End Sub Even when I do the query directly in SQLServer, it only loads the data when ID < 3, not any higher. SQL is like this: SELECT USUARIONOMBREREAL, USUARIONICK, PAISNOMBRE AS PAIS, CIUDADNOMBRE AS CIUDAD, USUARIOCODIGO, USUARIOTELEFONO, USUARIONACIMIENTO, TIPONOMBRE AS TIPO1, NIVELNOMBRE AS NIVEL, USUARIOSOCIAL, USUARIOARTISTICO, USUARIOCOMERCIAL, USUARIOFOTO, USUARIOCREDITO, RANGONOMBRE AS RANGO, TITULONOMBRE AS TITULO1 FROM USUARIO INNER JOIN PAIS ON USUARIO.USUARIOPAIS = PAIS.PAISID INNER JOIN CIUDAD ON USUARIO.USUARIOCIUDAD = CIUDADID INNER JOIN TIPO ON USUARIO.USUARIOTIPO1 = TIPO.TIPOID INNER JOIN NIVEL ON USUARIO.USUARIONIVEL = NIVEL.NIVELID INNER JOIN RANGO ON USUARIO.USUARIORANGO = RANGO.RANGOID INNER JOIN TITULO ON USUARIO.USUARIOTITULO1 = TITULO.TITULOID WHERE USUARIOID = '1' AND USUARIONICK = 'SpuntikPPV'
Since a lot of information is missing, I'm going to guess. I think one of the tables you are joining to has just two records that join to your first two users. The other users do not have matching records in the other tables so they are omitted.