Monday, January 13, 2020

Salesforce JWT Flow with Python to retrieve and insert data into SQL.

We can use below code to fetch the data from SF via JWT flow from python and insert it into 
Database.In case if you want to schedule your python program to retrieve the data from SF to
take the backup of your data you can refer this link 
"https://datatofish.com/python-script-windows-scheduler/" to learn how to schedule 
any python program from Windows. 

Note: You need to tweak your code according to your Salesforce connected app settings like 
consumerkey and certificates and username of your SF.



import flask
import requests
import tkinter as tk
import json
from json2html import *
import mysql.connector
from flask import request, jsonify
from base64 import urlsafe_b64encode
from datetime import datetime, timedelta
from mysql.connector import Error
from mysql.connector import errorcode
import Crypto
from flask import (
    Flask,
    render_template,
    jsonify,
)

import os
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5

app = flask.Flask(__name__)
app = Flask(__name__)
app.config["DEBUG"] = TrueJWT_HEADER = '{"alg":"RS256"}'JWT_CLAIM_ISS = "3MVG9d8..z.hDcPKuO0qkcUX0IncIWJdRX90Yc5BHsYUmbsHh8eeRweKXys8392v5gcuiK1_WHF3_zSS9rfoX"JWT_CLAIM_SUB = "david@abc.com"JWT_CLAIM_AUD = "https://login.salesforce.com"JWT_AUTH_EP = "https://login.salesforce.com/services/oauth2/token"
@app.route('/', methods=["GET"])
def home():
    return "<h1> This blog is a great place to learn advanced concepts </h1>"

@app.route('/sfconnect', methods=["GET"])
def sfconnect():
    # return "     allflows = "<div style='background-color: #fad0c4;background-image: linear-gradient(315deg, #fad0c4 0%, #f1a7f1 74%);height:570px;width:1260px' ><div style='padding: 1em;position: absolute;'><ul style='list-style-type:disc;color: green;'>" + \
   "<li style='color: green;font-size: 150%'>" + "<a href='http://127.0.0.1:5000/jwtflow'>JWT Bearer flow</a>" + "</li>" + "</ul></div></div>"     return allflows

############re usable method #########################
def getdata(acctkn):
    END_POINT = "https://light601dep-dev-ed.my.salesforce.com/services/apexrest/contactsfordatabase/";

    data = {"Authorization": "Bearer " + acctkn,
            "Content-Type": "application/json"            }

    r = requests.get(END_POINT, headers=data)
    r2= json.loads(r.content)
    print("###test#### get typeof from salesforce:%s", type(r2))
    sf_data = r.content
    data=r2
    print("###test123####contacts data from salesforce:%s",data)
    mydb = mysql.connector.connect(
        host="127.0.0.1",
        user="root",
        passwd="password",
        database="salesforcedata",auth_plugin='mysql_native_password')
    mycursor = mydb.cursor()
    for x in data:
        sql = "INSERT INTO Contactsf (FirstName, LastName) VALUES (%s, %s)"        val = (x['FirstName'], x['LastName'])
        mycursor.execute(sql, tuple(val))
        mydb.commit()
        continue
    mycursor.close()  ## here all loops done    mydb.close()  ## close db connection
    return json2html.convert(json=json.loads(r.content))


def jwt_claim():
    '''    Function to package JWT Claim data in a base64 encoded string    :return:    base64 encoded jwt claims data    '''
    claim_template = '{{"iss": "{0}", "sub": "{1}", "aud": "{2}", "exp": {3}}}'    claim = urlsafe_b64encode(JWT_HEADER.encode()).decode()
    claim += "."
    # expiration_ts = (datetime.now(tz=timezone.utc) + timedelta(minutes=5)).timestamp()    expiration_ts = int((datetime.now() + timedelta(seconds=300)).timestamp())
    payload = claim_template.format(JWT_CLAIM_ISS, JWT_CLAIM_SUB, JWT_CLAIM_AUD, expiration_ts)
    print(payload)

    claim += urlsafe_b64encode(payload.encode()).decode()
    return claim


def sign_data(data):
    f = open('pykey.pem', 'r')
    print('$$$$$$$file$$$$$$$$', f)
    rsa1key = RSA.importKey(f.read())
    signer = PKCS1_v1_5.new(rsa1key)
    digest = SHA256.new()
    digest.update(data.encode())
    sign = signer.sign(digest)
    return urlsafe_b64encode(sign).decode()


def do_auth(endpoint, data):
    '''    Function to POST JWT claim to SFDC /oauth/token endpoint and receive an access_token    :return:    access token    '''
    r = requests.post(endpoint, data=data)
    return r


@app.route('/jwtflow', methods=["GET"])
def jwtflow():
    # Keeping with JWS spec, we need to remove the padding "=" characters from base64 encoded string    claim = jwt_claim().replace("=", "")

    # Keeping with JWS spec, we need to remove the padding "=" characters from base64 encoded string    signed_claim = sign_data(claim).replace("=", "")

    target_payload = claim + "." + signed_claim

    auth_payload = {"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", "assertion": target_payload}
    response = do_auth(JWT_AUTH_EP, data=auth_payload)

    #  convert the text dictionary to data structure so it can be rendered as a json properly    response_text = eval(response.text)

    response_headers = eval(str(response.headers))

    return_dict = {"claim": claim, "signed_claim": signed_claim, "target_payload": target_payload,
                   "response_text": response_text, "response_headers": response_headers}
    # return jsonify(return_dict)    sfdcres = response.text
    print("The SFDC response:%s" % sfdcres)

    dicdata = json.loads(sfdcres)

    # print('#############',jsondata,'$$$$$$$$$$',dicdata);
    acctkn = dicdata["access_token"]

    print('parsed access token', acctkn)


    return getdata(acctkn)

if __name__ == "__main__":
    port = int(os.getenv("PORT", 8001))
    # Run the app, listening on all IPs with our chosen port number    app.run(host="0.0.0.0", port=port, debug=True, use_reloader=True)

app.run()

Friday, December 27, 2019

Get current release of the Salesforce with the Rest API

>> Some times when integrating with salesforce, we are unsure what is the current release of the org which we are trying to integrate.

>> Even after logging into the salesforce, we can only see the image of the current release and version number but in none of the places, we can see whether it is winter, spring or summer release.

>> To get the information, login into the workbench and execute the below URL to get the releases data, the last record is the current version/release of your instance. From the below picture, you can identify the current release of my org is Winter 20

/services/data/
















If you wish to get the same information in the any other integration system to check if there is any release that took place recently, use the below URL after getting access token/session Id.


It also provides the latest version/release of the organization which you are trying to hit.

Note: Salesforce runs on multiple server instances. The examples in this guide use yourInstance in place of a specific instance. Replace that text with the instance for your org


Thursday, July 25, 2019

Remove Lightning web components Play ground footer for better Playing.

When I'm accessing the Play ground to test few things on the lightning web components on the component library documentation,  I have found the practice is quite annoying because of  the existing large footer on the page which always compels me to scroll down the page unnecessarily which in turn consuming the time.  I thought of removing certain parts of the page so that I can focus on what matters the most and test the code accordingly.  Eventually came up with the below code to skip the long footer and some part of the header to create proper platform for your testing and reading the lightning web component guide.

Open your browser console and execute below code to skip the long footer and some part of the header to create proper platform for your testing and reading the web component guide with ease.


var footer = document.querySelector('footer'); footer.parentNode.removeChild(footer);

var compoheader = document.querySelector('.bottom'); compoheader.parentNode.removeChild(compoheader);

Before executing code, your page looks like below.


After executing code in the console, your page looks like below.




Note: Even while reading the lightning web component library, paste above code and read the whole document with luxury until you refresh your url completely.




Wednesday, May 15, 2019

Override or append to the existing SLDS Classes.

You might wonder is there any way to override or append something to the existing SLDS classes generated by the salesforce. Yes there is a way to do it, that is what we are discussing here.

When ever you use lightning prefix components, behind the scene's there would be lot of internal slds classes generated.
We can extend these generated classes functionality by appending/overriding our custom css to the existing classes.

------------
component code
------------

<aura:component description="search form">
    <aura:attribute name="searchterm" type="string" default="dave"/>
 
      <lightning:input value="{!v.searchterm}" name="search term" label="Search term(s)" class="myclass"/>

</aura:component>

Out put as follows.




Now we want different border color for the input field. To do that, follow the below steps

inspect the code generated by the framework as below.

And then create your own css class append to the auto generated slds class.

-----------
Css code
------------
.THIS.myclass .slds-input {
    border-color:purple;
    border-width :8px;
}

Now you will see the expected  border with different color and border width.


Overall, we were able to append our own css to the existing lightning:input element.

Note: you cannot override standard styling of slds classes in LWC due to the Shadow DOM and the way that CSS works in LWC. Currently developers do not have a way to override/customize CSS that is derived from Base Components. Salesforce team is working on giving developers more options, but at this point of time they can't commit to a timeline.

help link : https://success.salesforce.com/answers?id=9063A000000ePZSQA2

Saturday, December 22, 2018

Overlay Library for modals and popovers

Messages can be displayed in modals and popovers. Modals display a dialog in the foreground of the app, interrupting a user’s workflow and drawing attention to the message. Popovers display relevant information when you hover over a reference element.
Include one <lightning:overlayLibrary aura:id="overlayLib"/> tag in the component that triggers the messages, where aura:id is a unique local ID. Only one tag is needed for multiple messages.

Modals

A modal blocks everything else on the page until it’s dismissed. A modal must be acknowledged before a user regains control over the app again. A modal is triggered by user interaction, which can be a click of a button or link. The modal header, body, and footer are customizable. Pressing the Escape key or clicking the close button closes the modal.
Modals inherit styling from modals in the Lightning Design System.
Here’s an example that contains a button. When clicked, the button displays a modal with a custom body.

<aura:component>
    <lightning:overlayLibrary aura:id="overlayLib"/>
    <lightning:button name="modal" label="Show Modal" onclick="{!c.handleShowModal}"/>
</aura:component>

This client-side controller displays the modal. To create and display a modal, pass in the modal attributes using component.find('overlayLib').showCustomModal(), where overlayLib matches the aura:id on the lightning:overlayLibrary instance.

({
    handleShowModal: function(component, evt, helper) {
        var modalBody;
        $A.createComponent("lightning:button",
              {
                "aura:id": "findableAuraId",
                "label": "Press Me",
                "onclick": cmp.getReference("c.handlePress")
}, function(content, status) { if (status === "SUCCESS") { modalBody = content; component.find('overlayLib').showCustomModal({ header: "Application Confirmation", body: modalBody, showCloseButton: true, cssClass: "mymodal", closeCallback: function() { alert('You closed the alert!'); } }) } }); } })
================

Popovers

Popovers display contextual information on a reference element and don’t interrupt like modals. A popover can be displayed when you hover over or click the reference element. Pressing the Escape key closes the popover. The default positioning of the popover is on the right of the reference element.
Popovers inherit styling from popovers in the Lightning Design System.
Here’s an example that contains a button and a reference div element. When clicked, the button displays a popover. The popover also displays when you hover over the div element.

<aura:component>
    <lightning:overlayLibrary aura:id="overlayLib"/>
    <lightning:button name="popover" label="Show Popover" onclick="{!c.handleShowPopover}"/>
    <div class="mypopover" onmouseover="{!c.handleShowPopover}">Popover should display if you hover over here.</div>
</aura:component>
This client-side controller displays the popover. Although this example passes in a string to the popover body, you can also pass in a custom component like in the previous modal example. Any custom CSS class you add must be accompanied by the cMyCmp class, where c is your namespace and MyCmp is the name of the component that creates the popover. Adding this class ensures that the custom styling is properly scoped.

({
    handleShowPopover : function(component, event, helper) {
        component.find('overlayLib').showCustomPopover({
            body: "Popovers are positioned relative to a reference element",
            referenceSelector: ".mypopover",
            cssClass: "popoverclass, cMyCmp"
        }).then(function (overlay) {
            setTimeout(function(){ 
                //close the popover after 3 seconds
                overlay.close(); 
            }, 3000);
        });
    }
})

Notifications Library powers to create Toast and Notices

We have been using window.alert, window.confirm, window.prompt for various reasons, all these screens runs in synchronous mode and pauses your execution logic until clicks on a button.

Below are the offerings of the Lightning frame work in the for of Notifications Library which runs in asynchronous mode

Messages can be displayed in notices and toasts. Notices alert users to system-related issues and updates. Toasts enable you to provide feedback and serve as a confirmation mechanism after the user takes an action.
Include one <lightning:notificationsLibrary aura:id="notifLib"/> tag in the component that triggers the notifications, where aura:id is a unique local ID. Only one tag is needed for multiple notifications.

Notices

Notices interrupt the user's workflow and block everything else on the page. Notices must be acknowledged before a user regains control over the app again. As such, use notices sparingly. They are not suitable for confirming a user’s action, such as before deleting a record. To dismiss the notice, only the OK button is currently supported.
Notices inherit styling from prompts in the Lightning Design System.
Here’s an example that contains a button. When clicked, the button displays a notice with the error variant.
==================================================================================
<aura:component implements="flexipage:availableForAllPageTypes" access="global" >
  <lightning:notificationsLibrary aura:id="notifLib"/>
    <lightning:button name="notice" label="Show Notice" onclick="{!c.handleShowNotice}"/>
    
    <lightning:button name="toast" label="Show Toast" onclick="{!c.handleShowToast}"/>
</aura:component>
===================================================================================

({    
    handleShowNotice : function(component, event, helper) {
        component.find('notifLib').showNotice({
            "variant": "error",
            "header": "Something has gone wrong!",
            "message": "Unfortunately, there was a problem updating the record.",
            closeCallback: function() {
                alert('You closed the show notice!');
            }
        });
    },
      handleShowToast : function(component, event, helper) {
        component.find('notifLib').showToast({
            "title": "Notif library Success!",
            "message": "The record has been updated successfully.",
            "variant": "success"
        });
    }
})
===============================================================================
Show toast Example:



Show Modal Example:






Tuesday, October 16, 2018

Another advanced way of Parent to child component communication

We have been using below two techniques to communicate from parent to child. In addition to the below techniques, introducing advance way of communication with the component body technique.




Component Body

The root-level tag of every component is <aura:component>Every component inherits the body attribute from <aura:component>. We dont need to create a separate attribute to handle the v.body.
 Any free markup that is not enclosed in one of the tags allowed in a component is assumed to be part of the body and is set in the body attribute.
The body attribute has type Aura.Component[]. It can be an array of one component, or an empty array, but it's always an array.
In a component, use “v” to access the collection of attributes. For example, {!v.body} outputs the body of the component.

Below is the perfect example for body communication technique. Follow the step by step process to see the end result. Its gonna be very advanced level of communication technique.

===========
Step 1:  Markup : Coldata   (below component just acts like a programmatic abstraction, it wont display any data). Sole purpose of the below component is to pass the data to the Childcmp.
=========
<aura:component >
     <aura:attribute name="Firstname" type="string" />
     <aura:attribute name="LastName" type="string" />
     <aura:attribute name="age" type="Integer" />
</aura:component>

==========
Step 2:  Markup :Coldata2 (Again below component also just acts like a programmatic abstraction, it wont display any data). Sole purpose of the below component is to pass the data to the Childcmp.
=========

<aura:component >
     <aura:attribute name="att1" type="string" />
     <aura:attribute name="att2" type="string" />
</aura:component>

=========
Step 3:  Markup :Childcmp 
=========

<aura:component >
    <aura:attribute name="subtagsdata" type="object[]" />
     <aura:attribute name="subtagsdata2" type="object[]" />
    <aura:handler name="init" value="{!this}"  action="{!c.doinit}" />
    
    {!v.body}  <!---without this attribute you would not be able to access the body placed in the below parent component(see step 5) -->
    <table border="1">
        <tr>
        <th>FirstName</th>
             <th>LastName</th>
             <th>Age</th>
        </tr>
     <aura:iteration items="{!v.subtagsdata}" var="item">
          <tr>
        <td> {!item.Fname} </td>
         <td>  {!item.Lname}  </td>
         <td>  {!item.age} </td>
                </tr>
    </aura:iteration>
    </table>
</aura:component>

========
Step 4:  JavaScript controller:Childcmp 
========

({
doinit : function(component, event, helper) {
        var body=component.get("v.body");
        var coldata=[];
         var coldata2=[];
        
        for(var i=0; i<body.length;i++){
            /* below code differentiates two different components instances */
            if(body[i].isInstanceOf("c:Coldata")){
            coldata.push(
                {
                 Fname:body[i].get('v.Firstname'),
                 Lname:body[i].get('v.LastName'),
                 age:body[i].get('v.age')
                
                }
            
            );} else{
                
                 coldata2.push(
                {
                 att1:body[i].get('v.att1'),
                 att2:body[i].get('v.att2')
                
                }
           
            );
            }
        }
        
        component.set('v.subtagsdata',coldata);
         component.set('v.subtagsdata2',coldata2);
        console.log('%%%%Col data 1%%%%'+JSON.stringify(component.get('v.subtagsdata')));
         console.log('%%%%Col data 2%%%%'+JSON.stringify(component.get('v.subtagsdata2')));
}
})
=============
Step 5:  Markup : Parentcmp 
=============
<aura:component >
    <aura:attribute name="fn" type="string" default="Oliva trainings"/>
    <c:Childcmp >
        <c:Coldata Firstname="Dave" LastName="Oliva" age="28" />
        
          <c:Coldata Firstname="Dave1" LastName="Oliva1" age="29" />
        
          <c:Coldata Firstname="Dave2" LastName="Oliva2" age="30" />
        
          <c:Coldata Firstname="Dave3" LastName="Oliva3" age="31" />
        
        <c:Coldata2 att1="col2dataatt1" att2="col2dataatt2" />
        
          <c:Coldata2 att1="col2dataatt1" att2="col2dataatt2" />
               
    </c:Childcmp>  
</aura:component>

=========
Step 6:  Markup :Bodycommunication 
=========

<aura:application >
    <c:Parentcmp />
</aura:application>

Final output looks as below.