#jsforce
Explore tagged Tumblr posts
Text
NodeJs Salesforce Integration using JSForce: A quick guide to look out in 2021 and beyond
Heya, welcome to the Salesforce community. The journey would be fantastic for sure. If you are new to the community, you may initially face some troubles, but the Salesforce community stands by its people to assist them in growing more robust and better.
Salesforce has already done wonderful things in a very short time. It has expanded its powerful presence in almost every sector. Every 3 out of 5 organizations are now adopting this excellent CRM for better customer experience and business operations.
Not only in the industries, but Salesforce is also doing wonders with frameworks. Node js salesforce integration is the current buzzword in the development market. Yes, Salesforce Nodejs is a real-time integration. If you are wondering, how? Let us explain to you with this blog.
This blog will guide you through the detailed salesforce integration with Node.js, explaining the concept, prerequisites, and workflows. Before starting our blog in detail, let’s look at how Salesforce with Node.js is practical.
We all know that JavaScript is the language of the web. Every major browser supports this language as primary for building client-side web apps. If you are even working with Typescript or another language, it is later compiled into JavaScript to run smoothly on the browser.
Even salesforce developers use JS to build applications; Javascript powers the components like Lightning web and AURA. Server-side applications like Salesforce CLI are also created using JavaScript.
And when it comes to Node.js, it is an open-source JS runtime powered by V8. But why should you go for node.js with Salesforce? Let us tell you why?
By using nodejs with Salesforce, you can-
Build applications faster
Improvement in the development process
Build and compile lightning web components using Node.js
With Node.js, you can deploy beautiful, pixel-perfect web applications built with modern technologies and deploy highly scalable web services.
It lets you create pro-code applications on the Salesforce Platform.
We hope these reasons are enough for you to understand how tremendous and beneficial nodejs salesforce integration is for your business. So let’s not waste any seconds and start learning Salesforce integration with Nodejs.
Nodejs with Salesforce can be integrated mainly with two mediums, including endpoint and JSForce. In this post, we discuss how to integrate Salesforce with nodejs using JSForce.
Without any further ado, let’s get started with what JSforce is.
What is JSforce and what makes it so popular?
JSforce (f.k.a. Node Salesforce) is an isomorphic JavaScript Library using Salesforce’s API: It works both in the program and with Node.js. It encapsulates the admittance to different APIs given by Salesforce in offbeat JavaScript work calls.
Dissimilar to other Salesforce API libraries, it is planned to provide a coordinated interface for both server-side and customer-side applications, so you don’t need to rework comparative rationales with various libraries just for running in multiple climates.
Furthermore, it has a helpful control line interface (CLI) which gives an intelligent control center (REPL), so you can gain proficiency with the utilization without issue.
In short words, with the assistance of JSforce, We can get admittance to different APIs given by Salesforce in nonconcurrent JavaScript work calls.
Prerequisites to use JSforce with Salesforce
When talking about adopting the new technology, there are a few prerequisites that one needs to take care of. With some basic information working on anything new becomes quite exciting and engaging.
For JSforce, all you need to take care of-
Install Node Js: Since the functionality would use the java library, installing Node JS in your system is necessary.
Install JSforce: When talking about development for Salesforce using JavaScript then, JSforce comes into the picture. It makes the development process here easier and comprehensive.
Install Express Js: With express JS, things become easier; all you need to do is focus on working both platforms together.
A Salesforce org.: Since we are talking here about the integration of Salesforce with the Jsforce, you would need a Salesforce org.
These are the essential requisites before you move forward with node js salesforce integration.
Read More: Node js Salesforce Integration workflow?
#Salesforce#nodejs#jsforce#Integration#CRM#remotelearning#technology#programming#framework#agile#development#devops
1 note
·
View note
Text
NodeJs Salesforce Integration using JSForce: A quick guide to look out in 2021 and beyond
Quick Summary:
This post will help you understand how to integrate Salesforce with node.js using JSForce.
Introduction
Heya, welcome to the Salesforce community. The journey would be fantastic for sure. If you are new to the community, you may initially face some troubles, but the Salesforce community stands by its people to assist them in growing more robust and better.
Salesforce has already done wonderful things in a very short time. It has expanded its powerful presence in almost every sector. Every 3 out of 5 organizations are now adopting this excellent CRM for better customer experience and business operations.
Not only in the industries, but Salesforce is also doing wonders with frameworks. Node js salesforce integration is the current buzzword in the development market. Yes, Salesforce Nodejs is a real-time integration. If you are wondering, how? Let us explain to you with this blog.
This blog will guide you through the detailed salesforce integration with Node.js, explaining the concept, prerequisites, and workflows. Before starting our blog in detail, let’s look at how Salesforce with Node.js is practical.
We all know that JavaScript is the language of the web. Every major browser supports this language as primary for building client-side web apps. If you are even working with Typescript or another language, it is later compiled into JavaScript to run smoothly on the browser.
Even salesforce developers use JS to build applications; Javascript powers the components like Lightning web and AURA. Server-side applications like Salesforce CLI are also created using JavaScript.
And when it comes to Node.js, it is an open-source JS runtime powered by V8. But why should you go for node.js with Salesforce? Let us tell you why?
By using nodejs with Salesforce, you can-
Build applications faster
Improvement in the development process
Build and compile lightning web components using Node.js
With Node.js, you can deploy beautiful, pixel-perfect web applications built with modern technologies and deploy highly scalable web services.
It lets you create pro-code applications on the Salesforce Platform.
We hope these reasons are enough for you to understand how tremendous and beneficial nodejs salesforce integration is for your business. So let’s not waste any seconds and start learning Salesforce integration with Nodejs.
Nodejs with Salesforce can be integrated mainly with two mediums, including endpoint and JSForce. In this post, we discuss how to integrate Salesforce with nodejs using JSForce.
Without any further ado, let’s get started with what JSforce is.
What is JSforce and what makes it so popular?
JSforce (f.k.a. Node Salesforce) is an isomorphic JavaScript Library using Salesforce’s API: It works both in the program and with Node.js. It encapsulates the admittance to different APIs given by Salesforce in offbeat JavaScript work calls.
Dissimilar to other Salesforce API libraries, it is planned to provide a coordinated interface for both server-side and customer-side applications, so you don’t need to rework comparative rationales with various libraries just for running in multiple climates.
Furthermore, it has a helpful control line interface (CLI) which gives an intelligent control center (REPL), so you can gain proficiency with the utilization without issue.
In short words, with the assistance of JSforce, We can get admittance to different APIs given by Salesforce in nonconcurrent JavaScript work calls.
Read more for Prerequisites to use JSforce with Salesforce
0 notes
Link
Work can be stressful and we all need a break from time to time. What if you could take that break while having loads of fun and learn a few things at the same time? Well, here’s your chance: we’re excited to release the first multiplayer quiz app built entirely on Salesforce technology! In this blog post, we introduce the Quiz App and share highlights about the app architecture and its deployment. Introducing the Quiz App The quiz app is inspired by the popular Kahoot game. Here’s how it works: First, a game host presents questions from a shared screen or a video projector. Then, players compete by answering those questions in real-time using a mobile web app. The fastest player to give the correct answer scores the most points. As the game progresses, leaderboards are displayed so that players can keep track of scores and ranks. The quiz app was initially launched during Developer Game Night at Dreamforce 2019 with close to a hundred players. Now it’s open source and we’re promoting it during Dreamforce Global Gatherings. That’s right, you can install it for free, inspect the code, and customize it to your liking! Architecture Overview The quiz is divided in two applications: a host app and a player app. The host app is a Lightning Web Component (LWC) app running on a Salesforce Org. The org holds all of the quiz data in custom objects (players, questions, answers…). This means that you can easily import extra questions and customize them. It’s as simple as editing records—zero code change required! The player app is a mobile app built with Lightning Web Components Open Source (LWC OSS). It runs on Node.js deployed on Heroku. There are a few reasons to have the player app on Heroku for our specific use case. First, the Heroku app scales well and can accommodate a large number of users as Heroku limits are based on processing power (dynos) rather than strict governor limits. Secondly, we can easily provide unauthenticated access to our custom app. Unlike Salesforce orgs, there are no user license considerations on Heroku. These advantages do come at a cost: it’s up to us to build the app from the ground up. We use that to our advantage in the quiz player by implementing a lightweight mobile app. Cross-App Communication The two applications communicate with bidirectional REST calls. The player app uses the JSforce library (a JavaScript Salesforce client) to authenticates on the Salesforce org with a username/password flow. The client calls the standard REST APIs as well as a couple of custom Apex REST endpoints. The host app also sends REST requests to the Node.js server of the player app to signal game phase changes (eg: a question becomes available or game results are being displayed). These calls are secured with a shared secret API key that is configured on the two apps during setup. This technique ensures a lightweight and minimal level of security by preventing third parties from accessing the player app REST endpoints. Client-Server Communication on the Player App The player app consists of a client (the LWC OSS app running on a mobile device) and a server (the Node.js backend). The client calls REST APIs on the server to retrieve information like the player’s score. We also establish a WebSocket connection between the client and the server. This allows us to push real-time updates like game phase changes to the mobile app. For example, when a new question can be answered, the Node.js backend broadcasts an WebSocket message to all mobile clients. With that, all players can see game updates at the same time on their mobile devices. While powerful, WebSockets have an important limitation when working on mobile. WebSockets rely on a lasting network connection between the client and the server. On mobile, this connection can easily be broken when the device screen is locked or when the user switches to another app. This means that we must implement some non trivial code to handle reconnection on the client side and a keep alive mechanism to detect and eliminate broken connections on the server side. App Deployment One of the most challenging parts of this project is making sure that the quiz app can be easily deployed by a large number of users with different degrees of technical skill. Given the complexity of the environment (two different technology stacks), we needed to ensure that the deployment is as automated as possible. We rely on two things to achieve that: an org deployment script for the host app and a Heroku deploy button for the player app. Note: the app setup is extensively documented and we even provide a video guide (see link at the end of this post). Org Deployment Script The quiz host app is deployed on a Scratch org with Salesforce DX. This allows us to create a temporary Salesforce org with a lifespan of up to 30 days with a set of commands. These commands are grouped and chained together in a deployment script that you can run with a single command in a terminal. The deployment scripts automates the following tasks: Creating a scratch org Pushing sources to the org Assigning permissions Importing question data Generating a user password Automating the setup process greatly reduces the risk of configuration errors and saves a lot of time. Here’s a simplified version of the deployment script running on MacOs (there’s also an equivalent script for Windows): 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 echo "1. Creating scratch org..." && \ sfdx force:org:create -s -f config/project-scratch-def.json -a $ORG_ALIAS -d 30 && \ echo "" && \ echo "2. Pushing source..." && \ sfdx force:source:push -f -u $ORG_ALIAS && \ echo "" && \ echo "3. Assigning permissions..." && \ sfdx force:user:permset:assign -n Quiz_Host -u $ORG_ALIAS && \ echo "" && \ echo "4. Importing data..." && \ sfdx force:data:tree:import -p data/$DATA/plan.json -u $ORG_ALIAS && \ echo "" && \ echo "5. Generating user password..." && \ sfdx force:user:password:generate -u $ORG_ALIAS && \ echo "" EXIT_CODE="$?" # Check exit code echo "" if [ "$EXIT_CODE" -eq 0 ]; then echo "Installation completed." echo "" sfdx force:org:open -p /lightning/setup/SecurityRemoteProxy/home -u $ORG_ALIAS else echo "Installation failed." fi exit $EXIT_CODE Notice how commands are chained together with the && operator. This executes them one after the other as long as there are no errors. The \ character at the end of the line lets us introduce line breaks for readability. At the end of the script we’re checking for the last command’s exit code with EXIT_CODE="$?". This lets us report the deployment status with a message and open the org if everything went well. Heroku Deploy Button The player app is even easier to install with a Heroku deploy button. The deploy button is an image with a link that the user can click to deploy a Heroku app without leaving the browser. The link URL holds a reference to the GitHub repository that contains the app source code and a deployment configuration file. With the deploy button the user only has to enter a few configuration variables before confirming the deployment. Summary Now that you’ve learned about the Quiz App features and architecture, how about giving it a try? Sign up for a Dreamforce Global Gathering near you to find worthy opponents. Or, explore the code, install the apps, and customize questions by simply editing records. Don’t hesitate to let us know how much fun you had on social media! Resources Quiz app installation instructions
0 notes
Link
Lightning Web Components is our open source UI framework to build enterprise-scale apps that run on Salesforce, Heroku, Google Cloud Platform, or anywhere else. When running these apps on these different platforms, you can choose your own backend stack and data source, or you may want surface data from Salesforce in them. In this blog post, we will explore some options and considerations when using Salesforce as the data source. Authentication Salesforce provides a comprehensive set of REST and SOAP APIs that can be used to access its data and services from a client or server. The first step before accessing the APIs, is to establish a session with Salesforce. You can either use a username and password, or any of the OAuth flows listed here. Depending on your use case, these flows can be executed by client-side or server-side JavaScript. You can either build this logic from scratch or use external libraries like JSforce. Here are some considerations when deciding on an Authentication Flow for your app. Client Side Authentication You can use the OAuth User-Agent Flow to execute the handshake process using client side JavaScript alone. It involves a simple redirection to the /oauth2/authorize endpoint and takes in the Consumer Key of a Connected App as a parameter. Once the authorization is successful, the access token is encoded in the redirection URL. When you run client-side JavaScript, all the code is executed on the user’s device, so sensitive data like passwords and client secrets are accessible and exploitable. For this reason, this flow doesn’t use the client secret. However, the access token is encoded into the redirection URL which is exposed to the user and other apps on the device. Hence, care must be taken to remove callbacks from browser history. You can call window.location.replace(); to remove the callback from the browser��s history. It is best to use this type of Auth flow when building Lightning Web Components for desktop or mobile apps that have an embedded browser. Once you have the access token, you can pass it in the header of any HTTP requests to access Salesforce APIs. Building and sending a request from client-side JavaScript poses a risk, because the access token becomes available to the client and can be exploited. Therefore, sensitive business logic involving access tokens, usernames and passwords must never be written in client side JavaScript, because they are inadvertently exposed. To increase security and provide a better level of abstraction between your custom application and the APIs, you should use a middleware like Express, MuleSoft or any other ESB of your choice. Server Side Authentication You can use the Web server flow or the JWT Bearer flow to execute the handshake process using server side JavaScript like Node JS or any other stack of your choice. In case of Lightning Web Components, the create-lwc-app tool provides an option to create and use an Express server as a backend. You can choose an OAuth flow that suits your requirements. For instance, you can use the JWT Bearer flow when you want to use a single integration user to access data on behalf of all users. Use cases include showing read-only data (e.g. product catalog) to unauthenticated users. The web-server flow on the other hand can be used for per-user authorization. Use cases include websites where data relevant to the logged in user is shown (e.g. cart, order history etc.). You can also refer to this Trailhead Module that talks in detail about the use cases for different OAuth flows. When running authentication flows on a server, it is expected that the server protects and securely stores all the secrets. In the case of Web Server flow, the client secret that prevents a spoofing server must be stored securely. In the case of JWT Bearer flow, an X509 Certificate that corresponds to the private key of the app must be created and stored in a keystore. These secrets and certificate aliases also have to be configurable (generally using Environment Variables) and should never be hardcoded into your codebase. This also allows you to change them without rebuilding the app and to deploy instances of your app in different environments with ease. When developing locally, for example with Node.js, these are stored in a .env file, which can then be accessed in your code by using libraries like dotenv, saving you the trouble of setting them manually every time. You should exclude sensitive configuration files like .env from version control by referencing them in specific files like .gitignore for git. Data Residency Securing access to Salesforce data doesn’t stop with authentication. Data must be stored and transmitted securely as well. Data on the Salesforce Platform is secured with its core security capabilities like Sharing Model, Object and Field Level Security and optionally Salesforce Shield for encryption and high compliance. Using Salesforce APIs allows you real time access to data without making a copy of it. The data returned by the API is bound by the permissions of the user accessing the API. Depending on your use case, you might want to replicate Salesforce data into a local/managed database. Since you can deploy Lightning Web Components Open Source (LWC OSS) apps on any platform, there are different options that each platform provides for data storage and replication. For example, Heroku Connect is an add-on by Heroku that provides a data synchronization service between Salesforce and Heroku Postgres databases. Add-Ons/Connectors like these are built to securely store tokens, and establish a session with Salesforce when needed. It is important to remember that once data is replicated locally, it is not bound by the same Sharing Model that is present in Salesforce. It is therefore necessary to implement your own access control mechanism. Also, never write the logic that queries for data or filters data based on access controls on the client side, because it can be easily tampered with. In the screenshot below, an if condition is being used by the component to only show the data relevant to the logged in user. This statement can be easily removed using browser tools which would then give the logged in user access to all the data that is being returned by the server. As a best practice, you should always use a middleware to abstract sensitive logic from the client-side and make sure that the middleware returns only the data that’s relevant to the user and nothing more. Summary In this blog post, you’ve learned about different approaches to authenticate to Salesforce from an app built with LWC OSS and what factors determine the approach you take. You’ve seen drawbacks of accessing data from the client side, and how a server can help you secure your implementation. You’ve also seen how the responsibility of data security varies with choice of data residency. However, it is also important to note that this blog post doesn’t exhaustively list all of the options available for secure Salesforce data access, but instead provides general indication patterns and principles that are used. Now it’s time to get hands-on! Below are a few resources to help you get started. Sample Code Lightning Web Components OSS foundation and documentation Trailhead Project: Access Salesforce Data with Lightning Web Components Open Source Trailhead Module: Connected App Basics About the Author Aditya Naag Topalli is a 13x Certified Senior Developer Evangelist at Salesforce. He focuses on Lightning Web Components, Einstein Platform Services, and integrations. He writes technical content and speaks frequently at webinars and conferences around the world. Follow him on Twitter @adityanaag.
0 notes
Link
Work can be stressful and we all need a break from time to time. What if you could take that break while having loads of fun and learn a few things at the same time? Well, here’s your chance: we’re excited to release the first multiplayer quiz app built entirely on Salesforce technology! In this blog post, we introduce the Quiz App and share highlights about the app architecture and its deployment. Introducing the Quiz App The quiz app is inspired by the popular Kahoot game. Here’s how it works: First, a game host presents questions from a shared screen or a video projector. Then, players compete by answering those questions in real-time using a mobile web app. The fastest player to give the correct answer scores the most points. As the game progresses, leaderboards are displayed so that players can keep track of scores and ranks. The quiz app was initially launched during Developer Game Night at Dreamforce 2019 with close to a hundred players. Now it’s open source and we’re promoting it during Dreamforce Global Gatherings. That’s right, you can install it for free, inspect the code, and customize it to your liking! Architecture Overview The quiz is divided in two applications: a host app and a player app. The host app is a Lightning Web Component (LWC) app running on a Salesforce Org. The org holds all of the quiz data in custom objects (players, questions, answers…). This means that you can easily import extra questions and customize them. It’s as simple as editing records—zero code change required! The player app is a mobile app built with Lightning Web Components Open Source (LWC OSS). It runs on Node.js deployed on Heroku. There are a few reasons to have the player app on Heroku for our specific use case. First, the Heroku app scales well and can accommodate a large number of users as Heroku limits are based on processing power (dynos) rather than strict governor limits. Secondly, we can easily provide unauthenticated access to our custom app. Unlike Salesforce orgs, there are no user license considerations on Heroku. These advantages do come at a cost: it’s up to us to build the app from the ground up. We use that to our advantage in the quiz player by implementing a lightweight mobile app. Cross-App Communication The two applications communicate with bidirectional REST calls. The player app uses the JSforce library (a JavaScript Salesforce client) to authenticates on the Salesforce org with a username/password flow. The client calls the standard REST APIs as well as a couple of custom Apex REST endpoints. The host app also sends REST requests to the Node.js server of the player app to signal game phase changes (eg: a question becomes available or game results are being displayed). These calls are secured with a shared secret API key that is configured on the two apps during setup. This technique ensures a lightweight and minimal level of security by preventing third parties from accessing the player app REST endpoints. Client-Server Communication on the Player App The player app consists of a client (the LWC OSS app running on a mobile device) and a server (the Node.js backend). The client calls REST APIs on the server to retrieve information like the player’s score. We also establish a WebSocket connection between the client and the server. This allows us to push real-time updates like game phase changes to the mobile app. For example, when a new question can be answered, the Node.js backend broadcasts an WebSocket message to all mobile clients. With that, all players can see game updates at the same time on their mobile devices. While powerful, WebSockets have an important limitation when working on mobile. WebSockets rely on a lasting network connection between the client and the server. On mobile, this connection can easily be broken when the device screen is locked or when the user switches to another app. This means that we must implement some non trivial code to handle reconnection on the client side and a keep alive mechanism to detect and eliminate broken connections on the server side. App Deployment One of the most challenging parts of this project is making sure that the quiz app can be easily deployed by a large number of users with different degrees of technical skill. Given the complexity of the environment (two different technology stacks), we needed to ensure that the deployment is as automated as possible. We rely on two things to achieve that: an org deployment script for the host app and a Heroku deploy button for the player app. Note: the app setup is extensively documented and we even provide a video guide (see link at the end of this post). Org Deployment Script The quiz host app is deployed on a Scratch org with Salesforce DX. This allows us to create a temporary Salesforce org with a lifespan of up to 30 days with a set of commands. These commands are grouped and chained together in a deployment script that you can run with a single command in a terminal. The deployment scripts automates the following tasks: Creating a scratch org Pushing sources to the org Assigning permissions Importing question data Generating a user password Automating the setup process greatly reduces the risk of configuration errors and saves a lot of time. Here’s a simplified version of the deployment script running on MacOs (there’s also an equivalent script for Windows): echo "1. Creating scratch org..." && \ sfdx force:org:create -s -f config/project-scratch-def.json -a $ORG_ALIAS -d 30 && \ echo "" && \ echo "2. Pushing source..." && \ sfdx force:source:push -f -u $ORG_ALIAS && \ echo "" && \ echo "3. Assigning permissions..." && \ sfdx force:user:permset:assign -n Quiz_Host -u $ORG_ALIAS && \ echo "" && \ echo "4. Importing data..." && \ sfdx force:data:tree:import -p data/$DATA/plan.json -u $ORG_ALIAS && \ echo "" && \ echo "5. Generating user password..." && \ sfdx force:user:password:generate -u $ORG_ALIAS && \ echo "" EXIT_CODE="$?" # Check exit code echo "" if [ "$EXIT_CODE" -eq 0 ]; then echo "Installation completed." echo "" sfdx force:org:open -p /lightning/setup/SecurityRemoteProxy/home -u $ORG_ALIAS else echo "Installation failed." fi exit $EXIT_CODE Notice how commands are chained together with the && operator. This executes them one after the other as long as there are no errors. The \ character at the end of the line lets us introduce line breaks for readability. At the end of the script we’re checking for the last command’s exit code with EXIT_CODE="$?". This lets us report the deployment status with a message and open the org if everything went well. Heroku Deploy Button The player app is even easier to install with a Heroku deploy button. The deploy button is an image with a link that the user can click to deploy a Heroku app without leaving the browser. The link URL holds a reference to the GitHub repository that contains the app source code and a deployment configuration file. With the deploy button the user only has to enter a few configuration variables before confirming the deployment. Summary Now that you’ve learned about the Quiz App features and architecture, how about giving it a try? Sign up for a Dreamforce Global Gathering near you to find worthy opponents. Or, explore the code, install the apps, and customize questions by simply editing records. Don���t hesitate to let us know how much fun you had on social media! Resources Quiz app installation instructions
0 notes
Link
This blog post is Part 2 of the blog post series on Building Real-Time TV Dashboards with Salesforce Data, Platform Events & a Raspberry Pi. Part 1 – The Intro Part 2 – Salesforce Setup Part 3 – Raspberry Pi Setup Let’s get started with the Raspberry Pi setup. The idea is to have the Dashboard running on the Pi. This can be done in various different ways but for the sake for this project we will be hosting and running the dashboard on the Raspberry Pi. We will be building the Dashboard using the LWC OSS (Lightning Web Components Open Source) Framework. Pro Tip (Optional but totally worth trying out): Setup SSH and VNC on the Pi for super easy remote development and remote control. Step 0: Install the OS (Skip this step if you already have the OS installed) I am using Raspbian OS on my Pi and I set it up using NOOBS – New Out Of the Box Software and it makes the installation very easy. Here is a comprehensive step by step guid on installing the OS using NOOBS – https://www.raspberrypi.org/help/noobs-setup/2/ Step 1: Disable the Screensaver This is an important step because by default the PI’s screen keeps blanking out every 15 mins. As we will be having a standalone realtime dashboard running on the PI, we need to have our screensaver disabled. Easiest way to get this done is by installing xscreensaver. In the Terminal, run the following command to install it. This might take a few minutes $ sudo apt-get install xscreensaver Once installed, go to Preferences option in the main desktop menu. You should find the screen saver application. Launch it and search for the option to disable it completely. Step 2: Install Node.js Run the following commands in the Terminal Update your system package list sudo apt-get update Upgrade all your installed packages to their latest version sudo apt-get dist-upgrade Download the latest version of Node.js curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - Install it sudo apt-get install -y nodejs To check if the installation was successful, run the following command and it should return the version number of Node.js node -v Step 3: Create LWC App The Dashboard Interface is an LWC App. So, the goal is to have an LWC App running on the Raspberry Pi and it is totally up to you on how and where you build the LWC app. As long as there is an LWC App to be run on the Pi, you can either develop it on the Pi or develop it somewhere else(like your local machine) and migrate it to the Pi. For example, I developed it on my local machine and pushed it to the Pi via version control(bitbucket) so that I could maintain a backup and also sync code changes between my system and the pi. Feel free choose which ever way you are comfortable with and make sure you have Node.js installed as it is required to develop and run LWC Apps. 3.1 Create tv-dashboard LWC App On the command line/terminal, run command: npx create-lwc-app tv-dashboard When prompted about the application details, fill in the details as following Package name for npm: Press Enter to accept the default Description: Type the app description or press Enter to accept the default Author: Type your name or press Enter to accept the default Version: Press Enter to accept the default License: Press Enter to accept the default Who is the GitHub owner of the repository ( https://github.com/OWNER/repo): Type in your GitHub owner name or leave it blank and press Enter What is the GitHub name of the repository ( https://github.com/owner/REPO): Type in your GitHub repo name or Press Enter to accept the default Select a package manager: Use your arrow keys to select npm press Enter Use TypeScript or JavaScript: Use your arrow keys to select JavaScript press Enter Use custom Express server configuration: Enter y to install the server and press Enter Once the application is created, you will see the following message: Created conference-app in /YOUR/FILE/STRUCTURE/tv-dashboard. Checkout the `scripts` section of your `package.json` to get started. 3.2 Install A Few Packages Open command line/terminal Navigate to the directory containing the tv-dashboard application cd tv-dashboard Run the following command: npm install jsforce dotenv socket.io chart.js @salesforce-ux/design-system But, what are these applications and why do we need them? jsforce – JavaScript library to interact with Salesforce Orgs and APIs dotenv – To store our Salesforce credentials as environment variables in a .env file and reference them in or app socket.io – JavaScript library that enables real-time bidirectional event-based communication. We are using this to communicate our platform events from the LWC Server to LWC Frontend(charts). Works in a pub-sub model. chart.js – JavaScript library to create simple and beautiful HTML5 charts using canvas elements @salesforce-ux/design-system – Salesforce Lightning Design System (SLDS) – CSS framework to make our app beautiful 3.3 Create the .env file and declare our salesforce credentials as environment variables Open the tv-dashboard application folder Create a file with .env (with a leading period) as file name. Make sure that you are creating this folder in the root folder i.e., tv-dashboard Add the following the content into the .env file .env SF_LOGIN_URL=https://login.salesforce.com SF_USERNAME=YOUR_USERNAME SF_PASSWORD=YOUR_PASSWORD SF_TOKEN=YOUR_SECURITY_TOKEN Make sure to update the above placeholder values with your data SF_USERNAME: Your Salesforce Org’s username. SF_PASSWORD: Your Salesforce Org’s password. SF_TOKEN: Your Salesforce Org’s security token. 3.4 Update lwc-services.config.js to use the Lightning Design System SLDS In the tv-dashboard application folder, open the scr folder Open the file lwc-services.config.js Add the following in the resources section of your config { from: 'node_modules/@salesforce-ux/design-system/assets', to: 'dist/resources/assets' } 3.5 Add LWC Express Server Code In the tv-dashboard application folder, open folder server Open the file index.js Add the following code at the beginning of the file (before the line module.exports) src/server/index.js console.log(`Running server on port ${PORT}`)); // Start backend server server.listen(PORT, openDashboard); function openDashboard() { console.log(`Running socket server on port ${PORT}`); if (npm_lifecycle_event === 'serve') { console.log('Launching Dashboard!!'); exec( 'chromium-browser --noerrdialogs --kiosk http://0.0.0.0:3002 --incognito --disable-translate' ); } } 3.6 EDIT Client INDEX.html to add SLDS Stylesheet In the tv-dashboard application folder, open folder client Open the file index.html Replace the file content with the following code /src/client/index.html 3.7 Edit Client INDEX.js to use Synthetic Shadow DOM for the app and components to be able to use SLDS In the tv-dashboard application folder, open folder client Open the file index.js Add the following code at the beginning of the file content import '@lwc/synthetic-shadow'; 3.8 Create LWC Chart Component for visualising Opportunity Count By their Stage In the tv-dashboard application folder, open the folder my Create a folder named opportunitiesByStage Inside opportunitiesByStage folder, create a file opportunitiesByStage.html with the following content /src/client/modules/my/opportunitiesByStage.html Inside opportunitiesByStage folder, create a file opportunitiesByStage.js with the following content /src/client/modules/my/opportunitiesByStage.js import { LightningElement, api, track } from 'lwc'; export default class opportunitiesByStage extends LightningElement { @api sobject = ''; @api socket; @track socketInitialized = false; @track chartInitialized = false; chart; //object to keep track of the number of opportunities per stage chartData = {}; chartConfig = { type: 'doughnut', data: { datasets: [ { data: [], backgroundColor: [ '#3296ED', '#9D53F2', '#E287B2', '#26ABA4', '#77B9F2', '#C398F5', '#4ED4CD' ] } ], labels: [] }, options: { responsive: true, elements: { arc: { borderWidth: 0 } }, legend: { position: 'right', labels: { usePointStyle: true } }, animation: { animateScale: true, animateRotate: true } } }; async renderedCallback() { if (!this.socketInitialized && this.socket) { this.initializeSocket(); } if (!this.chartInitialized && this.socketInitialized) { await this.initializeChart(); } } initializeSocket() { //bind the onSocketEvent method to the 'cdc' socket event to update the chart with new incoming data this.socket.on('cdc', this.onSocketEvent.bind(this)); this.socketInitialized = true; } //initialize chart with chart.js async initializeChart() { await require('chart.js'); const ctx = this.template .querySelector('canvas.chart') .getContext('2d'); this.chart = new window.Chart(ctx, this.chartConfig); this.chartInitialized = true; } onSocketEvent(data) { const { changeType, entityName } = data.ChangeEventHeader; // check to make sure the change event is for the configured sobject and the record event is CREATE if ( this.sobject.toLowerCase() !== entityName.toLowerCase() || changeType !== 'CREATE' ) { return; } //update the chartData to increment the corresponding opportunity stage counter this.chartData[data.StageName] = this.chartData[data.StageName] + 1 || 1; //sort chartData in descending order let sortable = Object.entries(this.chartData); sortable.sort(function(a, b) { return b[1] - a[1]; }); //update chartData with sorted data this.chartData = Object.fromEntries(sortable); //add the updated data to the chart object this.chart.data.labels = Object.keys(this.chartData); this.chart.data.datasets[0].data = Object.values(this.chartData); //update the chart to reflect latest data this.chart.update(); } } 3.9 Create an LWC Component to view Chatter Announcements In the tv-dashboard application folder, open the folder my Create a folder named chatterAnnouncement Inside chatterAnnouncement folder, create a file chatterAnnouncement.html with the following content /src/client/modules/my/chatterAnnouncement.html Inside chatterAnnouncement folder, create a file chatterAnnouncement.html with the following content /src/client/modules/my/chatterAnnouncement.js 12 ? hour - 12 : hour; hour = this.formatNumber(hour); min = this.formatNumber(min); sec = this.formatNumber(sec); this.time = `${hour}:${min} ${ap}`; const months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; const days = [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' ]; const curWeekDay = days[today.getDay()]; const curDay = today.getDate(); const curMonth = months[today.getMonth()]; const curYear = today.getFullYear(); this.date = `${curWeekDay}, ${curDay} ${curMonth}, ${curYear}`; this.dateTime = `${this.date} • ${this.time}`; } formatNumber(num) { return num < 10 ? '0' + num : num; } } 3.10 Edit the App Component to add the Chart and the Chatter Announcements Components and also subscribe to our Socket.io server In the tv-dashboard application folder, open the folder app Open the file app.html and replace its content with the following /src/client/modules/my/app.html Open the file app.js and replace its content with the following code to initialise and subscribe to the backend socket server /src/client/modules/my/app.js { console.log('socket connected!'); this.socketReady = true; }); } async closeSocket() { this.socket.close(); this.socket = null; } } Step 4: Run The Dashboard We run the dashboard on chromium in kiosk mode, this helps show the in dashboard full screen. You can run the dashboard using the following command npm run build && npm run serve If you are developing, making code changes and would like for them to reflecting in real time, use the command npm run watch Note: Only the npm run serve command launches the Dashboard automatically. When using the npm run watch command, you would need manually view the app in the browser. Once you run the dashboard, start creating some Opportunities and Chatter Announcements in your org and you will see the Dashboard update in real-time! Step 5 (Optional): Auto Launch the Dashboard on Raspberry Pi Startup 5.1 Change the LWC Dashboard App Folder Permissions This wouldn’t be necessary if you are created everything on the pi. But when I used Git to sync code, I came across a the EACCESS Permission error and this following terminal command took care of the error. sudo chown -R pi:pi ABSOLUTE_PATH_TO_LWC_APP_FOLDER Make sure to replace the ABSOLUTE_PATH_TO_LWC_APP_FOLDER with the actual absolute path of your Dashboard LWC App folder. To get the absolute path, right click your Dashboard LWC App folder and Select Copy Path(s) 5.2 Create a executable shell script file Open the tv-dashboard folder Create a file with name run.sh and add the below as its content run.sh #!/bin/bash cd ABSOLUTE_PATH_TO_LWC_APP_FOLDER npm run build && npm run serve Make sure to replace the ABSOLUTE_PATH_TO_LWC_APP_FOLDER with the actual absolute path of your Dashboard LWC App folder. To get the absolute path, right click your Dashboard LWC App and Select Copy Path(s) 5.3 Edit the Raspberry Pi Autostart Script Open Terminal Run the following command sudo nano /etc/xdg/lxsession/LXDE-pi/autostart Add the following line to the file @lxterminal --command "ABSOLUTE_PATH_TO_SHELL_SCRIPT_FILE" Make sure to replace the ABSOLUTE_PATH_TO_SHELL_SCRIPT_FILE with the actual absolute path of the shell script created(in the previous step) inside the Dashboard LWC App folder. To get the absolute path, right click the shell script file that you created(in the pervious step) inside the Dashboard LWC App and Select Copy Path(s) Hit Control+S to Save Then Control+X to Exit the editor And… that is it! We learnt how to go about Build Real-Time TV Dashboards with Salesforce Data, Platform Events & a Raspberry Pi. We’ve scratched the surface with just 2 components and here is the tv-dashforce GitHub Project that not only contains the components created in this blog post but also different chart components along with Twitter Live Stream, Clock, Weather and Holidays. Make sure to check it out! GitHub Project- https://github.com/Minerva18/tv-dashforce This can also be done in another way where, we can host the Dashboard LWC App on the cloud like Heroku/AWS/Google etc. and use the URL to show the Dashboard LWC app via chromium kiosk mode on the Raspberry Pi. Raspberry Pi Resources https://www.raspberrypi.org/ What is a Raspberry Pi? https://www.raspberrypi.org/help/what-%20is-a-raspberry-pi/ Raspberry Pi Documentation and Setup Guides https://www.raspberrypi.org/documentation/ Installing OS https://www.raspberrypi.org/documentation/installation/noobs.md SSH Setup Guide https://www.raspberrypi.org/documentation/remote-access/ssh/ VNC Setup Guide https://www.raspberrypi.org/documentation/remote-access/vnc/ Screensaver https://www.raspberrypi.org/documentation/configuration/screensaver.md Securing your Raspberry Pi https://www.raspberrypi.org/documentation/configuration/security.md LED warning flash codes https://www.raspberrypi.org/documentation/configuration/led_blink_warnings.md The post Build Real-Time TV Dashboards with Salesforce Data, Platform Events & a Raspberry Pi – Part 3 – Raspberry Pi Setup appeared first on Minerva18.
0 notes
Link
こんにちは、倉谷(id:a-kura)で���。 今さらな感じですが、Salesforce Webinar にゲスト登壇しました。そこで、前編では発表内容、後編ではその後に取り組んだDevHub移行の課題について紹介します。 はじめに 2019年8月30日に開催されたセールスフォース・ドットコム社主催の Webinar にゲスト出演しました。この Webinar では、Salesforce DX の活用事例を2社、co-meeting 木村さんとチームスピリット倉谷から話しました。こちらから資料と動画を見ることができますので、よろしければご覧ください。 developer.salesforce.com Salesforce DX の始め方とパートナー様成功事例 私から Salesforce DX の活用事例として、CI環境構築における活用事例を話しました。 まず、背景として CI 環境が必要となる理由についてです。 チームスピリット社では、AppExchangeのOEMアプリケーションを開発・提供しています。 このB2Bサービスである TeamSpirit は1100社、17万IDに利用されています。 これだけのお客様に継続して利用していただくために開発に関わるメンバーも増えてきています。 そこで、サービスの品質を高いレベルで保ちつつ、チームで開発を進めるための基盤の一つが継続的インテグレーション (CI : Continuous Integration) です。 Salesforce World Tour Tokyo 2017 ふりかえり 実は、Salesforce World Tour Tokyo 2017 で当時の CI 環境と Salesforce DX を使ってどういったことを実現したいか、について発表しました。 まずは、その当時のことをふりかえりをさせてもらいます。 2017年当時の開発環境 2017年当時は、下記のような開発環境で開発していました。 開発者は各自で Developer Edition 組織を利用して開発しており、エディタは Eclipse / SublimeText など、デプロイは Migration Tools や gulp / jsforce などを利用していました。 CI としては Jenkins を使って Migration Tools で自動テストなどを実行していました。 2017年当時の継続的インテグレーション環境 CI 環境について、もう少し詳しく説明します。 CI 環境は Jenkins を Amazon EC2 上で動かしており、Apex テスト、E2E (End to End) 自動テスト、静的解析、ドキュメント生成などを実行していました。 実は、2017年当時の段階でも CI に必要なものはほぼ揃っていました。 Salesforce DX Upgrade History Salseforce World Tour Tokyo 2017 で発表してからこれまで2年間ありましたので、Salesforce DX のアップグレードの2年間の歩みをまとめてみました。 Winter'18 が2017年秋頃で SalesforceDX CLI、スクラッチ組織、VS Code 向け開発ツールが正式リリースされています。 DevHub が Developer Edition 組織で利用できるようになったのが Winter'19 です。このあたりから徐々に開発者も試しやすくなってきました。 次に、管理パッケージ周りの機能が強化され始め、Spring'19 でロック解除済みパッケージ、Winter'20 で第2世代管理パッケージがリリースされていきます。 加えて、Summer'19 で任意組織に対する開発機能が強化されています。ここでは、任意の組織に対してソースコードを retrieve / deploy する機能が正式リリースされました。これによって、スクラッチ組織をベースとした新しい開発スタイルだけではなく、従来どおり組織のソースコードを retrieve / deploy する開発スタイルも問題なくできるようになりました。 このことは、単にSalesforce DX を利用して従来の開発スタイルで開発できるようになった以上の意味があります。これまでは一気にスクラッチ組織を使った開発に移行しなければいけないイメージがありましたが、この機能の登場で段階的に Salesforce DX の新しい開発スタイルに移行できるようになりました。 弊社はこれに先立って、2019年3月から Salesforce DX への移行開始しました。これは、一部の開発メンバーが利用していた Mavensmate のサポートが終了することを受けて、開発環境の見直しの中で移行することを決断しました。 チームスピリットにおける Salesforce DX 活用状況 現在のチームスピリット社の Salesforce DX の活用状況です。 開発者はエディタとして VS Code を 利用し、Developer Edition 組織に SalesforceDX CLI でデプロイしています。 スクラッチ組織では、組織が有効期限切れでなくなってしまう、データを別のスクラッチ組織に移行する方法が確立しておらずテストデータを入力し直す手間がかかってしまう、ことからスクラッチ組織はまだ利用せず Developer Edition 組織を利用しています。 CI 環境はこれまで Jenkins を利用していましたが、現在 CircleCI に移行中です。 CircleCI に移行している動機は、開発チームが大きくなり開発基盤としての継続的インテグレーションの重要性が高まってきており、自分たちでマネージする必要がある Jenkins が重荷になってきているためです。 CircleCI はマネージドなサービスであり、インフラの保守などの手間がかからないため、自分たちで運用するよりも安定的で手間をかけずに利用できます。 チームスピリットにおける Salesforce DX 活用状況(継続的インテグレーション) 続いて、CI 環境について説明します。 現時点では、JavaScript Unit Test、Flow による型チェック、Prettier による Code Formatter といった JavaScript に関する処理を主に移行しています。 Apex テストも master ブランチの自動テストは移行していますが、もう少し高度化していく必要があります。 Salesforce DX CLI の活用例 ここで少し SalesforceDX CLI で利用しているコマンドについて紹介します。 JWT 認証、スクラッチ組織作成、ソースコードのプッシュ、ユーザー追加、パーミッション付与はワークブックなどにも出てきます。 その後、スクラッチ組織にデータをインポートしています。 弊社のプロダクトでは履歴管理を行うマスタがある、などデータ構造が複雑になっています。 そのため、インポートだけではデータを作りきれなかったり、繰り返し処理で作成���たほうが保守性に優れていたりすることから、Apex コードによるデータ作成も行なっています。 force:apex:execute を利用すると Apex コードを直接実行することができるため、データ作成以外にもいろいろな活用ができます。 Salesforce DX 活用度 Salesforce DX 活用度を独自に3段階に分けてまとめてみました。 評価項目としては、SalesforceDX CLI、Scratch Org、管理パッケージ、静的解析、コードフォーマットを用意しました。 自社の活用度としては、背景がオレンジのところまで進んでいます。 Salesforce DX CLI については活用度が高くなっていますが、Scratch Orgや管理パッケージについては活用度が低く今後の課題となっています。 Salesforce DX の所管 SalesforceDX の所感として、私の感じたことをまとめておきます。 まず、良い点としては VS Code の Salesforce DX 拡張機能がとても出来が良いです。 弊社のプロダクトではソースコードのボリュームが増えてきたため、差分デプロイできるのは非常に助かります。 今後、開発する場合はSalesforceDXを使わない手はないと思います。 今後の課題 弊社の今後の課題としては、Scratch Org の活用拡大、第2世代管理パッケージの活用があります。 Scratch Org の活用拡大 先ほど master ブランチだけで CI を実行している、ことを話しました。 これは DevHub として Developer Edition 組織を利用しており作成できるスクラッチ組織の数が限られるため、 master ブランチ以外で CI を実行できていません。 今後はよりスクラッチ組織を作成できる PBO (Partner Business Org) などに移行していきたいと考えています。 第2世代管理パッケージ 第2世代管理パッケージについては、Winter'20 で GA となりました。 とはいえ、既存の管理パッケージについては移行が今後の開発予定となっています。 当面は、第2世代管理パッケージの研究を進めながら移行機能のリリースを待ちたいと思います。 おわりに 前編では、Salesforce Webinar の発表内容についてご紹介しました。2019年8月末に発表して3ヵ月程度経過したので、その後に解決できた課題について後編で紹介したいと思います。 エンジニア募集♪ チームスピリットでは、アジャイルなプロダクト開発を共に推進してくれるエンジニアを募集しています。どんな考えや想いで開発しているのか少しでも興味を持っていただいた方、ぜひご連絡ください!(直接メッセージでも、下記の応募フォームからでも構いません) Enjoy DX!
0 notes
Quote
From Twitter: JSforce いつのまにかtrailheadに載ってた / Connect to Salesforce 単元 | Salesforce Trailhead https://t.co/LYCW5SI3LG— Shinichi Tomita (@stomita) October 15, 2019
http://twitter.com/stomita
0 notes
Quote
From Twitter: そのほか、streaming APIのReplay対応追加、OAuth PKCE対応、その結果jsforce CLIのOAuthに接続アプリの設定が要らなくなったこと、などなど— Shinichi Tomita (@stomita) July 25, 2018
http://twitter.com/stomita
0 notes
Quote
From Twitter: JSforce 1.8.5 リリースされてます。1.8.4 以前には脆弱性を含むライブラリが同梱されていますので、アップデートをお願いします。https://t.co/I54qu90C2j— Shinichi Tomita (@stomita) July 10, 2018
http://twitter.com/stomita
0 notes
Quote
From Twitter: Creating Scratch Org in Salesforce DX from API using JSforce - JSforce #TDX17 https://t.co/LsozKW9LO0— JSforce (@_JSforce) June 30, 2017
http://twitter.com/_JSforce
0 notes