Showing posts with label pl/sql. Show all posts
Showing posts with label pl/sql. Show all posts

Sunday, 10 September 2017

Download line wise(record) csv using Oracle Application express

We are going to discuss about how we can download the CSV file for line wise records in oracle apex.

Let's Create a interactive(IR)/classical report on our page(based on emp table).

Region Query :



SELECT  empno,
ename,
job,
sal,
'<a class="btn btn-large btn-primary logout" href="#"> <span class="pi_barcode fa fa-download"  onclick="download_csv('||empno||','''||empno||''')"  style="align-items: center"></a>' AS "Dwnd_Csv"
FROM emp

What's this ?
<a class="btn btn-large btn-primary logout" href="#"> <span class="pi_barcode fa fa-download"  onclick="download_csv('||empno||','''||empno||''')"  style="align-items: center"></a>


Here we are defing what class we want and what should it look like. Oracle application express have inbuilt classes define so we just need to refernce them to get the desire output.
Onclick: It's an event will fire whenever user clicks on Icon.(Our function download_csv(param1,prama2);

So far so good but where is our actual function !

We need to create a function in Function and Global Variable Declaration and call it using onclick event.

function  download_csv(eno,eno) { // here you can specify you're params for demo purpose i'd pass more params
apex.server.process ("download_csv",{ x01:eno, x02:eno},
                                     {
                                        type: 'GET',
                                        dataType: 'json',
                                        success: function(l_json_str)
{
// first we make sure it's a object or not then deal with it accordingly.
var arrData = typeof l_json_str != 'object' ? JSON.parse(l_json_str) : l_json_str;
var CSV = '';
var row = "";
for (var index in arrData[0]) {
row += index + ',';
}
row = row.slice(0, -1);
CSV += row + '\r\n';

for (var i = 0; i< arrData.length; i++) {
var row = "";
for (var index in arrData[i]) {
var arrValue = arrData[i][index] == null ? "" : arrData[i][index] ;
row += arrValue + ',';
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}
var fileName = "EmployeeDetails"; // This will be our CSV file name.
/*if(msieversion()){
var IEwindow = window.open();
IEwindow.document.write('sep=,\r\n' + CSV);
IEwindow.document.close();
IEwindow.document.execCommand('SaveAs', true, fileName"barcode.csv");
IEwindow.close();
} else {*/
var uri = 'data:application/csv;charset=utf-8,' + escape(CSV);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download = fileName + ".csv";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
//}
}
});
}


Javascript function is calling our ajax server process which is...

Create Ajax callback with the name: download_csv

DECLARE
l_json_str VARCHAR2(1000); -- based on data we are fetching we need to change this
L_eno VARCHAR2(50):= apex_application.g_x02;
BEGIN

l_json_str:='[';
for x in (SELECT * FROM emp
WHERE empno = L_eno )
LOOP
l_json_str:=l_json_str||'{"EmpNo":"'||x.empno||'","EmpName":"'||x.ename||'","Job":"'||x.Job||'","Salary":"'||x.sal||'"},';
END LOOP;
l_json_str:=substr(l_json_str,1,length(l_json_str)-1);
l_json_str:=l_json_str||']';
sys.htp.p(l_json_str);              
END;

Assuming we know how ajax server process works with-in oracle application express.


Demo : Download_csv
Twitter : Follow
Linked-In : Connect

Monday, 28 August 2017

Known Issues - Application Express 5.1(know bugs oracle 5.1)

  • 25373158 - COOKIE NOT SET IN APEX 5.1
    This bug can cause unsent cookies and Location redirect headers during login processing. It affects applications with customized login processes that write headers (e.g. a "Remember Me" cookie) or calls to LOGIN/POST_LOGIN in custom authentication sentry functions that stop the APEX engine.
    Solution: There is a patchset exception for this available on My Oracle Support - search by bug number.
  • 25430809 - INVALID BUILD OPTION MAPPINGS AFTER APP IMPORT
    The default export option for "Exports with Original IDs" was set to "Yes" in APEX 5.1. This bug fix resets the default back to "No". The bug fix also corrects issues with build options, where export/import caused broken references.
    Solution: There is a patchset exception for this available on My Oracle Support - search by bug number.
  • 25303884 - CLIENT SIDE MESSAGING FAILS TO SUBSTITUTE #IMAGE_PREFIX# IN PAGE-LEVEL ERRORS, CAN AFFECT OLD OR CUSTOM THEMES
    If you have a page with page attribute Reload on Submit = 'Only for Success’ then page-level error notifications will be displayed using client side messaging. In old or custom themes it fails to substitute the #IMAGE_PREFIX# substitution string, which can lead to incorrect image references and therefore users perceiving missing images. This does not affect the Universal Theme, because no such images references exist for page-level error messages.
    Workaround: You can set the page attribute ‘Reload on Submit’ back to ‘Always’, however, this will preclude you from being able to use an Interactive Grid on that page.
  • 25303970 - INLINE ITEM ERRORS FOR OLDER THEMES ARE NOT ALWAYS CLEARED WHEN A PAGE HAS ‘RELOAD ON SUBMIT’ SET TO ‘ONLY FOR SUCCESS’
    If an application uses an older theme (not the Universal Theme) and has a page that uses the ‘Reload on Submit’ attribute setting of ‘Only for Success’, then Application Express will use the new client-side messaging to display error messages without a full page reload. However, the label templates in older themes are not compliant with the new client-side messaging logic, which in turn results in some fallback logic being used to display the inline item errors, causing issues with clearing the message. The issue occurs if a page has more than one item error displayed, and then subsequently if only one of those errors is rectified before the next attempt to save, the inline item error message for the rectified error will not be removed as it should be. It is removed from the page error notification, but not from the inline item notification.
    Note: Applications using older themes, generally have the page attribute ‘Reload on Submit' set to ‘Always’ so will not face this issue. However, new pages added to existing applications will have the page attribute set to 'Reload on Submit' by default.
    Workaround: You can set the page attribute ‘Reload on Submit’ back to ‘Always’, however, this will preclude you from being able to use an Interactive Grid on that page.
  • 25305292 - CLIENT SIDE INLINE ERROR MESSAGE FOR RICH TEXT ITEM GIVES JAVASCRIPT ERROR
    If you have a Rich Text Editor item that has validations on a page with page attribute Reload on Submit = 'Only for Success' then if there are validation errors to report there will be a JavaScript error that keeps the inline validation message from displaying. This may also affect reporting other errors on the page, and will keep the page from being submitted again.
    Workaround: You can set the page attribute ‘Reload on Submit’ back to ‘Always’, however, this will preclude you from being able to use an Interactive Grid on that page.
  • N/A - THE TIMEZONE APIS AND CONSTANTS AVAILABLE IN APEX_JSON SHOULD NOT BE USED
    APEX_JSON contains new, undocumented APIs and constants for reading and writing TIMESTAMP, TIMESTAMP WITH TIME ZONE and TIMESTAMP WITH LOCAL TIME ZONE values. These APIs and constants are subject to change in later releases, which will likely break any code that utilizes them at this point in time.
    Workaround: Do not use the undocumented timezone APIs and constants until they have been documented.
Changed Behavior:
  • 25291599 - REGIONS ON GLOBAL PAGES CAN NOW PARTICIPATE IN PAGE-LEVEL REGION DISPLAY SELECTORS
    Prior to 5.1, the 'Region Display Selector' attribute of regions on global pages was effectively ignored. In 5.1, this attribute is now used to determine if the region from the global page is displayed in region display selector regions on other pages for the same user interface. The default setting for 'Region DIsplay Selector' is 'Yes', therefore, exisiting pages that include a Region Display Selector are very likely to display additional regions defined on the global page after upgrading. If the global page region can not be visually displayed, for example if it is purely CSS code, then the application will appear broken to end users as clicking on this new selection will result in a blank display.
    Workaround: Set the 'Region Display Selector' attribute to 'No' for all regions on the global page that you do not want displayed in region display selectors on other pages.
  • N/A - CLIENT-SIDE MESSAGING ISSUES IN APPS USING OLD, OR CUSTOM THEMES
    If you create a new application using an old, or custom theme, or add new pages to an existing application which is not using the Universal Theme, then you may encounter minor differences in how inline errors are displayed. This can affect you if either:
       1. The page attribute 'Reload on Submit' is set to 'Only for Success' (the default for new pages) and an item validation occurs.
       2. The application 'Compatibility Mode' is set to '5.1' and the submit button is set to 'Execute Validations' = 'Yes', and any items have client-side validation such as 'Value Required' = 'Yes', which fail
     
    An inline error is shown but it may not look exactly the same as on other existing pages because it isn't using the templates from the theme. 
    Workaround: These differences can be a avoided by setting 'Reload on Submit' to 'Always', (Note: Interactive Grid requires this to be set to 'Only for Success') and not using client-side validation by either setting application compatibility mode < '5.1' or Setting Execute Validations = No. The differences can also be avoided by updating the old theme to use the new style of error templates, or by updating the application to use Universal Theme. For further details please review the APEX 5.1 - Client side messaging and apps not using Universal Theme blog post.
  • 25247070 - TIE SWITCH TO ASYNCHRONOUS DYNAMIC ACTIONS TO COMPATIBILITY MODE 5.1
    In Application Express 5.1 the compatibility mode controls how Ajax-based Dynamic Actions operate, specifically a setting of '5.1' will make all Ajax calls asynchronous. Prior to 5.1, Ajax-based Dynamic Actions that also had the ‘Wait for Result’ attribute set to 'Yes' would issue synchronous Ajax calls. Synchronous calls can have a negative impact by blocking all page interactions until the call has been completed. Dynamic Actions with 'Wait for Result' set to 'No' previously performed asynchronous Ajax calls, therefore, there is no change in behavior for these actions.
     
    This change has been tied to compatibility mode to protect against possible regressions in existing applications, where applications may have relied upon the synchronous Dynamic Actions nature for certain functionality. 
    Workaround: Remove the reliance on synchronous-based Ajax calls before upgrading the compatibility mode for the application. For more information please see Sync or Async? Dynamic Actions in APEX 5.1.
  • You may Find the Original Soure here : know bugs oracle 5.1

Tuesday, 25 April 2017

Barcode lable printing using jquery with oracle apex

So lets say we wanted to print barcode layouts in our Oracle Application Express  which will print small,simple and elegant labels with information we wanted to print, First let me tell you barcode  label printing needs some define paper layout on which we can print barcode data Paper Size Information

After selecting the proper layout its time for start coding in  HTML, JAVASCRIPT and PL/SQL this part is very interresting here i have share the neccessary js file which needs to be included on page you can add this Javascript - For Barcode Layout file in workspace.

Create report in your application which will be pl/sql based so we can write some htp.p methods in that report.

As of now we have selected page layout and added js as per our need now it's time to build a page in oracle which will work with js and layout.

So we gonna add report with below code.

DECLARE

page_cnt number := 1;
row_count number := 3;
page_elements number := 24;
l_cnt number:=0;

cursor c1 is
select a.lvl,
null DUMMY_COLS,
null DUMMY_COLS2,
null DUMMY_COLS3,
null DUMMY_COLS4,
null DUMMY_COLS5,
null DUMMY_COLS6,
null DUMMY_COLS7
from
(SELECT LEVEL as lvl FROM dual CONNECT BY LEVEL <= 24) a
join
(
SELECT  LVL
FROM MY_TABLE t
and rownum < 2
) b on a.lvl < b.lvl
union all
 ( SELECT    (rownum+p_begin_no) - 1 as lvl
    FROM MY_TABLE2
    )
order by 1;

                               
BEGIN
                                                       

htp.p('<table class="mainTable">');
htp.p('<tr class="singleRow">');

-- max l_cnt will be
-- page_elements = 24 -- number of elements on a single page
-- row_count = 3 -- max number of elements in a single row
-- page_cnt -- running total of pages created, init at 1
-- l_cnt -- running total of elements printed .. init at 0
                                                       
FOR A IN c1 LOOP
 
-- increment the counter to get the current element number
l_cnt:=l_cnt+1;

-- open a new table if required
IF  ((mod(l_cnt, page_elements) = 1) AND (l_cnt > 1))  THEN
 htp.p('<table class="mainTable">');
END IF;

-- open a new row if required
IF  ((mod(l_cnt,row_count) = 1) AND (l_cnt > 1))  THEN
 htp.p('<tr class="singleRow">');
END IF;


-- add the element under an existing row...
        if a.item_id is null then
            htp.p('<td class="singleColumn"></td>');                                                
        else                                          
            htp.p('<td class="singleColumn">
                <div  name="barcode">'||A.COL1||'</div>
                <div class="singleDiv">'|| A.COL2||'</div>
                </td>');
        end if;

-- based on the l_cnt determine, if we need to close a row or not
        IF (mod(l_cnt,row_count) = 0 AND l_cnt > 1) then
            htp.p('</tr>');
        END IF;

-- based on the l_cnt determine, if we need to close a table or not
        IF (mod(l_cnt,page_elements) = 0 AND l_cnt > 1) then
          htp.p('</table>');
        END IF;
END LOOP;
     
-- Add elements to complete a row
IF mod(l_cnt, row_count) <> 0 then
    FOR i in 1..(row_count - mod(l_cnt, row_count)) loop
        htp.p('<td class="singleColumn"></td>');
    end loop;
end if;
 
    IF mod(l_cnt, row_count) <> 0 then
        htp.p('</tr>');
        htp.p('</table>');
    end if;
END;


How actually everything works ?? 
  
what i did for my task is user will select some data from lov and based on lov data Tabular result will get reflected (so far so good) i have report  on page so if user checks the checkbox and submit it will save into the database with beginning number of barcode to be printed and then after it will open a new page with barcode in it.

In pl/sql we are using what, where and how many records of  barcode we wanted to print.
So the logic is if user selects he wants to start printing from label no 3 then according to our pl/sql logic as shown above it will print data from #3.

How many formats can we print??

Different formats(on a single page): 24 label, 28 label, 30 label etc...
It will print every format no matter what layout you are working on just change the sql according to you're need and you are good to go.

Declaimer 
Oracle Application Express version 5.0
Report
Javascript











Monday, 11 April 2016

Printing with jasper soft ireport version 5.1 - Part 2

In part i had shown you how to install and make database connection with local database.

Now, i'll show you how to actually work with this tool.

Run Jasper and click on file from menu bar click on new that will open up a below screen.



Select which ever report want to create and click Launch Report Wizard in my case i have created Blank A4. Give your report a name and location where you want to store it click next.



Now you need to write your query or you can load your query if you have saved on local machine.
Make sure you have chosen a correct data source else it will give an error.Report will be created now.

You can check in Report Inspector(left Side) your fields will be appeared.(Columns of query you have selected at creation of report).

(If you can not see Report Inspector then click on Windows from Menu bar and at bottom you will see reset windows click on it restart your tool)

It will look something like below.



Click on Windows from menu bar click on palette where by you can select report elements to use in page.



On next part we will discuss how to actually use this Elements.


if you have any query you can comment below.

Twitter : pranav

Thank you.








Wednesday, 17 February 2016

v('') Vs. apex_application.globalvariable

As i describe in Previous post their are list of global variable which we can use in pl/sql aslo.
Now, Problem is v(' '); is not fix oracle apex may change it in future as they have done it in past so better approach will be use it as apex_application.globalvariable for that i have created a Function as shown below(change it as per need).

Function :

CREATE OR REPLACE FUNCTION GET_CUSTOMERNAME(custid Number) RETURN VARCHAR2 IS
tmpVar VARCHAR2(200);

BEGIN
 
     SELECT FIRST_NAMEINTO tmpVar FROM CUSTOMER WHERE CUST_ID = custid
   and cmp_id = apex_application.g_user;
   RETURN tmpVar;
   EXCEPTION
     WHEN NO_DATA_FOUND THEN
       NULL;
     WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
       RAISE;
END GET_CUSTOMERNAME;
/

Tuesday, 16 February 2016

Oracle Database Version

Run Below Query in Sql Developer or Toad or any tool you are using.
SELECT * FROM V$VERSION
or
SELECT version FROM V$INSTANCE
or
BEGIN DBMS_OUTPUT.PUT_LINE(DBMS_DB_VERSION.VERSION || '.' || DBMS_DB_VERSION.RELEASE); END;
Result:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production
PL/SQL Release 11.2.0.3.0 - Production
CORE 11.2.0.3.0 Production
TNS for Linux: Version 11.2.0.3.0 - Production
NLSRTL Version 11.2.0.3.0 - Production

Monday, 31 August 2015

Find out Missing Numbers in a sequence

Find out Missing Numbers in a sequence


Example:
We have a table ORDH, which is having a field ORDERNO which starts from 300000. currently there are around 100 thousand records exists in this table.
The ORDERNO value is generated from a sequence.
We want to find out the missing (hole in the sequence) ORDERNO from the ORDH table. 
(Ex: 300654 is missing and there are lot of other order numbers were also missing)
Is there a way to find out all the missing order numbers from this table?

And We Said....

WITH     got_next_orderno     AS
(
     SELECT     orderno
     ,     LEAD (orderno) OVER (ORDER BY orderno)     AS next_orderno
     FROM     ordh
)
SELECT     ordrno + 1          AS from_no
,     next_orderno - 1     AS to_no
FROM     got_next_orderno
WHERE     orderno     + 1     != next_orderno
;


OR you can use this code as well:

select min_a - 1 + level
      from ( select min(id) min_a
                  , max(id) max_a
               from d3
           )
    connect by level <= max_a - min_a + 1
     minus
     select id
       from d3

Show values in right side of shuttle

While working with select list and shuttle, when we want to display values into right side of shuttle depending upon selection from select ...