javaniceday.com

  • Home
  • AboutAbout me
  • Subscribe
  • SalesforceSalesforce related content
  • Node JSNodejs related content
  • JavaJava related content
  • Electric Vehicles
  • Autos Eléctricos
  • Estaciones de carga UTE
  • Mapa cargadores autos eléctricos en Uruguay
  • Syntax highlighter highlight.js

    February 9th, 2023

    highlight.js it’s an awesome library to highlight code from several languages. With an easy-to-customize aesthetic. It’s very straightforward to add it to any project: just include the library, the stylesheet, and set up a <pre> tag with HTML. After that, wrap any code snippet with either the <pre> tag and add a <code class="language-name"> classic class. The library will take care of the rest!

    Highlight.js supports over 180 languages in the core library. List of supported languages

    The official site of highlight.js: https://highlightjs.org/

    example of syntax highlighting by highlight.js
    Example of syntax highlighting by highlight.js

    How to install highlight.js

    Download the styles and include it between the <head></head> tags:

    <head>
      ...
      <link rel="stylesheet"  href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
      ...
    </head>

    Import the script at the end of the body tag

    <body>
      ...
      //cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js
      <script>hljs.initHighlightingOnLoad();</script>
    </body>

    How to use highlight.js

    <pre><code class="language-javascript">
    const myConst = "example"
    </code></pre>

    How to highlight XML with highlight.js

    If you want to highlight you will have to escape the brackets with:

    &lt; and &gt;

    Example:

    <pre><code class="xml">
      &lt;my-tag&gt; my content &lt;/my-tag&gt;
    </code></pre>

    Custom dark mode syntax highlighter for highlight.js

    It’s possible to override the default styles. Let’s say you want a dark mode, you can use these styles and modify the colors as needed.

    
    /* custom hljs styles*/
    
    .hljs {
    	display: block;
    	overflow-x: auto;
    	padding: .5em;
    	background: #1d1f21
    }
    
    .hljs,
    .hljs-subst {
    	color: #c5c8c6
    }
    
    .hljs-comment {
    	color: #888
    }
    
    .hljs-attribute,
    .hljs-doctag,
    .hljs-keyword,
    .hljs-meta-keyword,
    .hljs-name,
    .hljs-selector-tag {
        font-weight: 700;
        color: #81a2be;
    }
    
    .hljs-deletion,
    .hljs-number,
    .hljs-quote,
    .hljs-selector-class,
    .hljs-selector-id,
    .hljs-string,
    .hljs-template-tag,
    .hljs-type {
    	color: #99cc99;
    }
    
    .hljs-section,
    .hljs-title {
    	color: #99cc99;
    	font-weight: 700
    }
    
    .hljs-link,
    .hljs-regexp,
    .hljs-selector-attr,
    .hljs-selector-pseudo,
    .hljs-symbol,
    .hljs-template-variable,
    .hljs-variable {
    	color: #bc6060
    }
    
    .hljs-literal {
    	color: #78a960
    }
    
    .hljs-addition,
    .hljs-built_in,
    .hljs-bullet,
    .hljs-code {
    	color: #de935f;
    }
    
    .hljs-meta {
    	color: #1f7199
    }
    
    .hljs-meta-string {
    	color: #4d99bf
    }
    
    .hljs-emphasis {
    	font-style: italic
    }
    
    .hljs-strong {
    	font-weight: 700
    }
     
        

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Salesforce CLI configuration for Mac

    February 9th, 2023

    Configuring the Salesforce CLI (Command Line Interface) on Mac can seem like a tedious task. However, it doesn’t have to be! There are simple steps you can follow to ensure that your Salesforce CLI is configured correctly for Mac. This post will outline the steps needed to successfully configure the Salesforce CLI on Mac.

    The Salesforce CLI is a powerful tool that helps you develop, customize, and enhance your Salesforce applications. The CLI offers several commands that can be used to create, configure, update, deploy, and delete metadata components. The Salesforce CLI can be used on both Windows and Mac operating systems.

    This guide will walk you through the steps you need to take to configure the Salesforce CLI for Mac.

    Download the Salesforce DX CLI

    Download from https://developer.salesforce.com/tools/sfdxcli and install it as any other mac application

    Check installation. Open your terminal and type:

    $ sfdx version
    
    $ sfdx help

    You can ask for help on an specific command. For example, let’s ask how auth command works:

    $ sfdx auth --help

    Authenticate the Salesforce CLI.

    $ sfdx auth

    Select:

    $ auth web login


    Follow the OAuth steps. This will open a browser window from which you can log in. Once you’re done, you can use the. rest of the commands available in the SFDX CLI tool.

    Once the authentication is done, you can close the tab and go to the command line to see:

    $ Successfully authorized my@username.dev with org ID 00A9V000001wCajUAB

    To start downloading metadata c reate Salesforce DX project in your local machine:

    $ sfdx force:project:create -n myProject --manifest

    The above command will create the default project structure for a typical Salesforce DX project.

    Now let’s download one Apex class:

    $ sfdx force:source:retrieve -m "ApexClass:MyApexClass" -u myuser@something.dev

    Now let’s make some modifications to your Apex class to deploy the changes to your dev org. Type:

    $ sfdx force:source:deploy -m "ApexClass:MyApexClass" -u myuser@something.dev

    Configure Visual Studio Code to use Salesforce CLI

    There are several Visual Studio Code plugins available to make it easier to use Salesforce CLI in your development process. You can install these plugins and configure them to use your Salesforce org.

    Take a look at this guide to configure it: https://www.apexhours.com/how-to-setup-visual-studio-code-for-salesforce/

    How to update the Salesforce CLI

    $ sfdx update

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Functional programming JavaScript

    February 7th, 2023

    Functional programming is an increasingly popular style of programming in the JavaScript world, but what makes it so powerful? Functional programming relies heavily on the use of pure functions, high-order functions, immutable data structures, and more to create code that is easy to maintain, test, and modify.

    Learning Functional Programming with JavaScript – Anjana Vakil – JSUnconf

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Tips for writing useful error messages

    February 2nd, 2023

    Validation rules are an important tool for ensuring that data is accurate, complete, and consistent. Validation rules are used to check the data in a record before it is saved. Rules can be set to require specific data types, such as dates or numbers, meet the minimum or maximum values, or contain certain characters or text strings. Validation rules can also be used to enforce complex business rules, such as ensuring that a customer’s address matches the one on their credit card. With validation rules, you can ensure that your records always contain the correct information before they are saved.

    Let’s see some useful tips to write good error messages.

    • Give instructions that tell the user the type of entry that’s valid, such as birthday must be before today.
    • Include the field label to identify the field that failed validation, especially if the error message appears in a common place such as a toast or a popup.
    • Try to describe the source of the error.
    • Avoid the “try again” at the end of every error message. Only use it if the error is related to a temporal error such as a network connection and a second try can resolve the problem. Trying again won’t make the problem to be resolved automagically, give some tips to the user to know how to resolve it, even if it is “Please contact the support team”
    • Make sure the error message is not exposing sensitive data. Sometimes this is a good excuse to just display “internal error, try again”

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Why I adopted Heroku

    January 29th, 2023

    As a web developer, I have always been on the lookout for ways to simplify the process of deploying and managing my applications. That’s why I recently decided to adopt Heroku as my platform of choice.

    Heroku is an incredibly user-friendly platform that allows developers to quickly and easily deploy their applications in minutes. With a few clicks, my applications can be deployed to production. More importantly, with Heroku, I can focus on development rather than having to spend time dealing with tedious server configuration.

    This post is built from a developer perspective where the main task we do daily is (obviously) development. So if you are a sysadmin guy, Heroku will like you at the beginning but soon you will have your hands tied since flexibility is not the main feature.

    It’s not a complete guide and probably won’t be enough to make a decision but it sure will be useful to start investigating a bit more about this great platform.

    What is Heroku?

    Heroku is a platform as a service (PaaS) acquired by Salesforce in 2011.

    Let’s say it’s a smart hosting for your web apps (*)

    (*) Even you can deploy a daemon (a.k.a Heroku worker), I would bet that most of the software deployed on Heroku are web applications.

    You developed your web application and then what?

    You created a beautiful web application and now you want to publish it under your own domain http://www.myawesomeapp.com. You have a couple of options.

    One option is to hire a Virtual Private Server (VPS).

    Another option is to hire a dedicated server. Both of them require some sysadmin knowledge because most of the time you get (literally) an OS with enough software to boot.

    For sure that has some advantages such as total control of security and performance. The main disadvantage I see is you lose focus on development to pay attention to backups, security, deployments, etc.

    Concentrate on development, not on deployment

    Even if you build your own blog where you document your experiences, you need a 99% uptime so you will have these main tasks:

    • Development
    • Configure the production environment
    • Deployment
    • Writing
    • Backups
    • Scale. Ok, only if you write lots and interesting articles 🙂

    It seems lots of tasks just for a personal blog, right?

    Most of those tasks you can delegate to Heroku and concentrate more on development.

    • Great support
    • Nice uptime
    • A large list of Add-ons
    • A free plan to start learning and to have your testing environment (unless you do stress testing).

    Disadvantages

    Flexibility. Is not like a VPS where you are able to customize lots of things such as web server configuration and even the OS.

    But wait… is not too expensive?

    The answer depends on the value you add to your time and headaches.

    Since most of the time we don’t have a sysadmin guy on our team, we will have to that work, taking time from our main task: development our cool app.

    My experience with Java and Heroku

    I’m involved in the Java world for 10+ years and even more if I count years from the university. However, I started to use Heroku a couple of years ago. In the past, I used to configure a server from scratch, install Tomcat, Glassfish, MySql, Iptables, Mail server (very painful), Apache, PHP, JRE, etc. Even it’s hard, it’s also fun to learn

    Currently, I’m involved in some projects with Java plus Heroku and It feels very comfortable to do deployments just with one command or click without configuring so much stuff.

    Security

    If you deal with sensitive data such as Salesforce org data, Heroku offers private spaces that have (among other things) special configuration for those cases.

    Photos by Tim Gouw on Unsplash

    and Alex Knight on Unsplash

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Hash text in Node.js

    January 29th, 2023

    Hashing is an essential part of encryption and data security. A hash is an algorithm that takes the text of a file, message, or other data and converts it into a unique string of characters. The hash acts as an immutable representation of the text and can be used to verify the integrity of the original data.

    In this post, we’ll look at how to hash text in Node.js with the Crypto library.

          
    const crypto = require('crypto');
    const stringToHash = 'hello';
    const hash = crypto.createHash('sha256').update(stringToHash).digest('hex');
    // the output will be something like: 20ccfac05d596dfb08509494fc7753780ac6d79a23c88ef02514f4c5b2a3ff45
    
    // instead of .digest('hex'); you can use also .digest('base64');
          
        

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • How to setup Github Actions workflow lint

    January 29th, 2023

    GitHub Actions provides a great way to automate workflow processes and make development and deployment more efficient. Linting is an important part of any software development project to ensure code consistency and maintain uniform standards. In this post, I will explain how to setup a Github Actions workflow lint to automate your linting process.


    Setting up a GitHub Actions workflow lint is easy and can help keep your codebase consistent and maintainable.

    First, you need to create a workflow file in your project’s root directory. This file should be named .github/workflows/lint.yml and should contain the configuration necessary to run your linting script.

    Let’s say your package.json file looks like this:

    "scripts": {
        (...)
        "lint": "eslint --ignore-path .gitignore . --ext .js"
      },

    Create a file at ./github/workflows/lint.yml

    Paste this content:

    name: lint
    
    on: push
    
    jobs:
      lint:
        runs-on: ubuntu-latest
    
        steps:
          - uses: actions/checkout@v2
    
          - name: Cache node modules
            uses: actions/cache@v2
            env:
              cache-name: cache-node-modules
            with:
              path: ~/.npm
              key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
              restore-keys: |
                ${{ runner.os }}-build-${{ env.cache-name }}-
                ${{ runner.os }}-build-
                ${{ runner.os }}-
          - name: Install Dependencies
            run: npm install
    
          - name: Lint
            run: npm run lint
    

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Transform a JSON object keys and values to lower case

    January 29th, 2023

    We all know that JavaScript Object Notation (JSON) is a powerful and popular data markup language. It is widely used in web development and API design. But what if you wanted to transform a JSON object’s keys and values to lowercase?

    Fortunately, there is a simple way to do this. All you need to do is to loop through the object, retrieving each key and value, and then convert it to lowercase using the JavaScript toLowerCase() method.

    But what if you do it in a fancy way using reduce?

    export const objToLowerCase = (obj) => {
      if (!obj) return obj;
      return Object.keys(obj).reduce((prev, current) => ({ ...prev, [current.toLowerCase()]: obj[current].toLowerCase() }), {});
    };

    And the unit test looks like this:

     test("obj to lowercase", () => {
        const obj = {
          MyKey1: "MY Value 1",
          MyKey2: "MY Value 2",
        
        const result = objToLowerCase(obj);
        expect(result["MyKey1"]).toBeDefined();
        expect(result["MyKey1"]).toBe("my value 1");
        expect(result["MyKey2"]).toBeDefined();
        expect(result["MyKey2"]).toBe("my value 2");
      });

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • How to write to S3 bucket from Lambda function

    January 29th, 2023

    AWS Lambda functions are a great way to automate certain tasks and processes in the cloud. They can be triggered by events, such as a file upload to an S3 bucket or a message sent to an SNS topic, allowing you to execute some code in response.

    In this post, we’ll show you how to write data to an S3 bucket from a Lambda function. This can be useful for a variety of tasks, such as archiving log files or uploading data to a data lake.


    S3 (Simple Storage Service) is Amazon’s cloud storage solution that allows you to store and access data from anywhere in the world. Writing to an S3 bucket from a Lambda function is a simple way to store and access data in the cloud.

    In this post, I’ll walk you through how to write to an S3 bucket from a Lambda function. We’ll use the AWS SDK for Node.js to access S3.

    Take this example as a starting point. This is not a production-ready code, probably some tweaks for permissions will be necessary to meet your requirements.

    AWS resources we need

    • Lambda Function
    • S3 Bucket
    • Lambda Role
    • Bucket Policy

    The Lambda function

    const AWS = require("aws-sdk");
    const s3 = new AWS.S3({
        region: "us-east-1",
    });
    let response;
    
    exports.lambdaHandler = async (event, context) => {
        try {
            console.log(event);
            const params = {
                Bucket: process.env.MY_BUCKET,
                Key: 'test-file.txt',
                Body: "test content"
            }
            console.log('writing to s3', params);
            const result =  await s3.putObject(params).promise();
            console.log(result);
    
            response = {
                'statusCode': 200,
            }
        } catch (err) {
            console.log(err);
            return err;
        }
    
        return response
    };
    
    

    The SAM template

    For the sake of simplicity, we are going to use Principal: “*” which makes your bucket 100% public!

    AWSTemplateFormatVersion: '2010-09-09'
    Transform: AWS::Serverless-2016-10-31
    Description: >
      Sample SAM Template for Lambda and S3
    Parameters:
      Environment:
        Type: String
        Description: Environment name. Example, staging
    Resources:
      MyLambda:
        Type: AWS::Serverless::Function
        DependsOn:
          - "MyBucket"
        Properties:
          CodeUri: hello-world/
          Handler: app.lambdaHandler
          Runtime: nodejs12.x
          Environment:
            Variables:
              MY_BUCKET:
                Ref: "MyBucket"
          Role:
            Fn::GetAtt:
              - "MyLambdaRole"
              - "Arn"
        Tags:
          Name: !Sub "${Environment}-my-test-lambda"
    
      MyBucket:
        Type: AWS::S3::Bucket
        Properties:
          BucketName: !Sub "${Environment}-my-test-bucket"
    
      MyBucketPolicy:
        Type: AWS::S3::BucketPolicy
        Properties:
          PolicyDocument:
            Id: BucketPolicy
            Version: 2012-10-17
            Statement:
              - Sid: AccessAll
                Action: s3:*
                Effect: Allow
                # Beware: this makes your bucket public!
                Principal: "*"
                Resource: !Join
                  - ''
                  - - 'arn:aws:s3:::'
                    - !Ref MyBucket
                    - /*
          Bucket: !Ref MyBucket
    
      MyLambdaRole:
        Type: AWS::IAM::Role
        Properties:
          AssumeRolePolicyDocument:
            Statement:
              - Effect: Allow
                Action: "sts:AssumeRole"
                Principal:
                  Service:
                    - "lambda.amazonaws.com"
            Version: "2012-10-17"
          ManagedPolicyArns:
            - arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
          Policies:
            - PolicyName: MyLambdaPolicy
              PolicyDocument:
                Statement:
                  - Effect: Allow
                    Action: "s3:*"
                    Resource:
                      - Fn::GetAtt:
                          - "MyBucket"
                          - "Arn"
                Version: "2012-10-17"

    As a good practice, always receive the environment as a parameter. This way, all your resources will be easier to identify.

    Deploy

    Build our lambda and template. This will check also the syntax of your template

    $ sam build

    Only for the first time run and follow the steps:

    $ sam deploy --guided

    The second time and so on you can execute:

    $ sam deploy --no-confirm-changeset

    Clean up your test AWS resources. Delete unused lambdas, buckets, etc to keep your account organized and the most important: no extra costs

    Resources

    • Tutorial: How to Create, Upload, and Invoke an AWS Lambda Function
    • Getting started with Amazon S3

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
  • Configure Prettier in your Node JS project

    January 29th, 2023

    Prettier is a great tool for making your Node.js code look clean and consistent. It is an easy way to eliminate some of the frustrations associated with coding, such as redundant and messy code formatting. With a few simple steps, you can set up Prettier and get your code looking beautiful.

    Overview

    Prettier is a code formatter that supports many languages and can be integrated with most of the editors.

    Also, you can integrate it with your CI/CD.

    That way nobody will be able to merge to the master branch if the code is not well-formatted.

    With Prettier you will be able to define your own rules, however default rules are enough at the beginning.

    Your rules will be defined in a file called .prettierrc placed in your project’s root.

    Let’s see how to install Prettier and then make some configurations.

          
    npm install prettier --save-dev
      
        

    Example of Prettier config file

          
    {
      "trailingComma": "es5",
      "tabWidth": 4,
      "printWidth": 120,
      "semi": true,
      "singleQuote": false,
      "useTabs": false,
      "quoteProps": "as-needed",
      "jsxSingleQuote": false,
      "bracketSpacing": false,
      "jsxBracketSameLine": true,
      "arrowParens": "avoid",
      "requirePragma": false,
      "insertPragma": false,
      "proseWrap": "preserve",
      "endOfLine": "lf"
      }
      
        

    See more options for the .prettierrc file

    Gulp integration

          
    npm install gulp-prettier -save-dev
      
        
          
    gulp.task("prettier", () => {
      return gulp
      .src("./**/*.js")
      .pipe(prettier(".prettierrc"))
      .pipe(gulp.dest("./"));
    });
      
        

    PhpStorm IDE integration

    If you are using PHP Storm, it’s highly recommended that you configure your IDE to auto-format your code every time you save a .js file

    https://prettier.io/docs/en/webstorm.html
    The plugin will take the rules from you .prettierrc file

    Configure a File Watcher in PhpStorm to auto-format the code on save.

    Visual Studio Code

    You can install the extension as any other and then you can use these configurations in you settings.js with the prefix “prettier”

          
    {
      "prettier.useTabs": false,
      "prettier.trailingComma": "es5",
      "prettier.tabWidth": 4,
      "prettier.printWidth": 120,
      "prettier.semi": true,
      "prettier.singleQuote": false,
      "prettier.quoteProps": "as-needed",
      "prettier.jsxSingleQuote": false,
      "prettier.bracketSpacing": false,
      "prettier.jsxBracketSameLine": true,
      "prettier.arrowParens": "avoid",
      "prettier.proseWrap": "preserve",
      "prettier.endOfLine": "lf"
    }
      
        
    Photo by Alexander Schimmeck on Unsplash

    Share this:

    • Click to share on X (Opens in new window) X
    • Click to share on LinkedIn (Opens in new window) LinkedIn
    • Click to share on Reddit (Opens in new window) Reddit
    • Click to email a link to a friend (Opens in new window) Email
    Like Loading…
←Previous Page
1 … 6 7 8 9 10 … 25
Next Page→

  • LinkedIn
  • GitHub
  • WordPress

Privacy PolicyTerms of Use

Website Powered by WordPress.com.

  • Subscribe Subscribed
    • javaniceday.com
    • Already have a WordPress.com account? Log in now.
    • javaniceday.com
    • Subscribe Subscribed
    • Sign up
    • Log in
    • Report this content
    • View site in Reader
    • Manage subscriptions
    • Collapse this bar
%d