Friday, November 20, 2015

SAP HANA- $.hdb stored procedure result set reading

The following example of usage of the SAP HANA XS $.hdb API shows how to connect to the SAP HANA DB and how to read values of the output declaed as table in  HANA Stored procedure.


The example stored procedure already deployed into hana db and it will return OUTPUT_TABLE as a result set


CREATE PROCEDURE "<<SCHEMA_NAME>>"."PROCEDURE_SALES_REPORT"(
            IN DISCOUNT INTEGER,
            OUT OUTPUT_TABLE "<<SCHEMA_NAME>>"."TT_SALES" )
LANGUAGE SQLSCRIPT SQL SECURITY INVOKER 
AS

BEGIN

var1 = SELECT T1.REGION_NAME, T1.SUB_REGION_NAME, T2.PRODUCT_ID, T2.SALES_AMOUNT
            FROM SCHEMA_NAME.REGION AS T1
            INNER JOIN
            SCHEMA_NAME.SALES AS T2
            ON T1.REGION_ID = T2.REGION_ID;

var2 = SELECT T1.REGION_NAME, T1.SUB_REGION_NAME, T1.PRODUCT_ID, T1.SALES_AMOUNT,                   T2.PRODUCT_NAME
            FROM :var1 AS T1
            INNER JOIN
            SCHEMA_NAME.PRODUCT AS T2
            ON T1.PRODUCT_ID = T2.PRODUCT_ID;

OUTPUT_TABLE = SELECT SUM(SALES_AMOUNT) AS SALES_AMOUNT, SUM( SALES_AMOUNT - 
            (SALES_AMOUNT * :DISCOUNT/ 100)) AS NET_AMOUNT,                 
            PRODUCT_NAME, REGION_NAME, SUB_REGION_NAME
            FROM :var2 
            GROUP BY PRODUCT_NAME, REGION_NAME, SUB_REGION_NAME;

END;



Syntax for Calling Stored procedure and reading data from the result set 


      var body = $.request.body.asString();
      var reqObj = JSON.parse(body);
      var action = reqObj.action;
      var discount = $.request.parameters.get('discount');
      var data=[];
      var rs;
   
                 var conn=$.hdb.getConnection({"sqlcc": "PROC_TEST::cred"});
    var pstm= conn.loadProcedure('<< scheme name >>', '<< procedure name >>');
    rs = pstm(discount);
    var rslength =   (rs["OUTPUT_TABLE"]).length;
       
            for(var i = 0 ; i<rslength-1;i++)
            {
      data.push
      ({
           "SALES_AMOUNT":rs["OUTPUT_TABLE"][i]["SALES_AMOUNT"],
           "NET_AMOUNT":rs["OUTPUT_TABLE"][i]["NET_AMOUNT"],
           "PRODUCT_NAME":rs["OUTPUT_TABLE"][i]["PRODUCT_NAME"]
         
       
      });
            }
conn.commit();
   
   
            $.response.setBody(JSON.stringify(data));
    

Wednesday, November 18, 2015

SAP HANA XS API for reading data


The following example shows how to use $.db interface to connect to SAP Hana Db and how to read data from db and how to response as json object.

The example values assumes that we have country data in DB .

COUNTRYID
COUNTRYNAME
1
India
2
USA
3
UK




/////if you have sqlcc configuration please use in the get Connection method.

      var conn = $.db.getConnection();

       var query = "SELECT COUNTRYID, COUNTRYNAME "SCHEMA"."table name";
       var pstmt = conn.prepareStatement(query);
       var rs = pstmt.executeQuery();
       while(rs.next())
   {        
       data.push
       ({
            "COUNTRYID":rs.getString(1),
            "COUNTRYNAME":rs.getString(2),
                     
       });
     
   }


Batch Insert example in SAP HANA


The following example of usage of the SAP HANA XS database API shows how to establish a connection with SAP HANA and how to use batch insert for loading bulk data into hana DB.

The example values assumes that we have to insert data into DB as a batch insert instead by record by record.

COUNTRYID
COUNTRYNAME
1
India
2
USA
3
UK


Syntax

HANA 

/////if you have sqlcc file please mentioned in the getConnection method
  
     var conn = $.db.getConnection();
     var st = conn.prepareStatement("insert into tablename(col1,col2) VALUES(?,?)");
     var BACTHSIZE = number of records which you want insert;

   ///////we can use batch only number of records are more than 1

     if(BACTHSIZE>1)
     {
     st.setBatchSize(BACTHSIZE);
     var i;
     for(i=0;i<BACTHSIZE;i++) 
     {
     st.setString(1,input[i].COUNTRYID);
     st.setString(2,input[i].COUNTRYNAME]);
    
     st.addBatch();
     }
     st.executeBatch();
     }

////if number of records are less than 1, we can assume only one record need to insert into db and i ////value should be zero
     else
     {
     st.setString(1,input[0].COUNTRYID);
     st.setString(2,input[0].COUNTRYNAME);
    
     }
     st.close();
     
     conn.commit(); 
     data.push({
        "data": "Record Inserted Successfully..!"
      });
       
      
  }

Calling procedure by using $.hdb




The following example of usage of the SAP HANA XS database API shows how to establish a connection withSAP HANA and return a result set from the specified procedure call.
The example code assumes that a procedure exists with the following signature:

CREATE PROCEDURE "DRACE".USP_TBLUSERS_INSERT(
     IN flavor VARCHAR, 
     IN quantity INTEGER,    
     OUT change DECIMAL)


Syntax: 

var data=[];

//if you don't have sqlcc file for your package, make sure getConnection method properties are empty
//ex:    var conn=$.hdb.getConnection();

 var conn=$.hdb.getConnection({ "sqlcc": "packagename::sqlccfilename"});

var pstm= conn.loadProcedure('Schemaname', 'Procedure Name'); 
var result = pstm(input1, input2);

   data.push({
         
           "status": result[output variable name]
        })
        conn.commit();
      

Thursday, November 27, 2014

Use SAML to enable SSO For SAP HANA

This blog will demonstrate you about how to configure SAML based login for your HANA xs based applications in SAP HANA.

1A). Pre-requisites:

  • Need Winscp software or any other s/w to copy files from local desktop to HANA Server.
  • Putty software to run the commands in Linux Environment.
  • HANA adm credentials for creating trust store files.
  • You need the IDP metadata URL of your company. example for SAP company metadata url as following,
  • https://accounts.sap.com/saml2/metadata/accounts.sap.com
   Note: You have to take proper metadata URL of your company, either it is QA system or             Production system.

1B). Files Need to be download from Service Market Place:


SAP Cryptographic libraries (libsapcrypto.so and sapgenpse):

SAP Crypto libraries includes both sapgenpse and libsapcrypto.so
Browse to http://service.sap.com/swdc, expand ‘Support Packages and Patches’ and select ‘Browse
our Download Catalog, choose ‘SAP Cryptographic Software and linux on x86 64 64bit.

Once download is complete into your local system, by using SAPCAR Archiving tool you can De-archive the sap Crypto libs into your local folder of your systems. or can you do everything in server location also.

We will get libsapcrypto.so and sapgenpse files from De-archive process, please copy this files and  paste into HANA server location /usr/sap/<SID>/SYS/global/security/lib/ by using WinScp software.

we are done with setup pre requisites, please follow the below steps and complete this integration.

Step1: Create Trust Store

Type the following commands from a Linux command prompt, logged in as <sid>adm (e.g. hdbadm where your instance name is HDB):


  •  cd  /usr/sap/<INSTANCE>/SYS/global/security/lib
  • mkdir /usr/sap/<INSTANCE>/HDB<InstNo>/<host>/sec
  • ./sapgenpse gen_pse -p /usr/sap/<INSTANCE>/HDB<InstNo>/<host>/sec/sapsrv.pse
Leave PIN empty (2x enter), and as "Distinguished name of PSE owner:" enter CN=<yourhostname>

Step2:Setup the trust relation with the IDP



1).Open your company metadata url(as mentioned in pre requisite step), go to view page source and copy the certificate string (which is DER encoded) from the ds:X509Certificate tag.

Sample  URL of SAP metadata service is 

2).Open the above metadata URL and copy the string in between the X509 tags, we need to use this string for creating sapid.cer file.


Just follow the steps for creating sapid.cer file.

Open your favorite editor and enter text as follows and save file as sapid.cer.
 

-----BEGIN CERTIFICATE-----

Paste the string which you copied from the above step.

-----END CERTIFICATE-----

Note:

Surround the certificate string with the tags below (there are 5 hyphens before and after the CERTIFICATE tags)

3). And move this newly created file(sapid.cer) file into server directory
/usr/sap/<INSTANCE>/SYS/global/security/lib

Step3: Import this certificate into sapsrv.pse

./sapgenpse maintain_pk -p /usr/sap/<INSTANCE>/HDB<InstNo>/<host>/sec/sapsrv.pse -a sapid.cer



Step4 :Restart the XS Engine


From HANA Studio, double-click on the SYSTEM you are configuring from the Systems view.
From the landscape tab, right-click on the xsengine row and select “kill”.
Alternatively you can type HDB stop and then HDB start from a Linux prompt to restart the whole HANA server.







Monday, November 7, 2011

FInding Duplicate Records In Database

Table Name: tblMasterUsers
Column Name: uname

here i wrote a query for finding duplicate records for uname column in tblMasterUsers

QUERY:
select * from tblMasterUsers where uname in
(select uname from tblMasterUsers group by uname having count(uname)>1)



Above query returns all dupicate values in a table. duplicate count must be greater then one. It Doesn't count any spelling mistake values.

example: erp is a duplicate record for erp
erps is a spelling mistake record for erp not a duplicate.

Wednesday, August 17, 2011

MAC ID Generating In C#.NET

Step 1:

Go to the solution Explorer--> Right Click --> Add Refrence --> System.Management

Step 2:

Add 2 NameSpaces :
1).using System.Management;
2).using System.Management.Instrumentation;

Step 3:

//Create object for management class
ManagementClass mc=newManagementClass("Win32_NetworkAdapterConfiguration");

Step 4:
//management object collection represent all collections from managemnet class                                               
ManagementObjectCollection moc = mc.GetInstances();
string MACAddress = String.Empty;
foreach (ManagementObject mo in moc)
 {
if(MACAddress == String.Empty) 
// only return MAC Address from first card            
 {
if ((bool)mo["IPEnabled"] == true)
 MACAddress = mo["MacAddress"].ToString(); 
 }
mo.Dispose();     
}         
//after every 2 digits it returns ":"      
 MACAddress = MACAddress.Replace(":", "");                       MessageBox.Show(MACAddress);