Saturday, 12 June 2021

React, Angular Rich Text editor - CKEditor npm module

 React, Angular Rich Text editor - CKEditor npm module

==========================================


In order to create an editor instance in React, install the ckeditor4-react npm package as a dependency of your project:

React:

=======


Project_cmd:>npm install ckeditor4-react


After installing, the CKEditor 4 React component can be imported in your JavaScript code:


import CKEditor from 'ckeditor4-react';


e.g:


import React, { Component } from 'react';

import CKEditor from 'ckeditor4-react';


class App extends Component {

    render() {

        return (

            <div className="App">

                <h2>Using CKEditor 4 in React</h2>

                <CKEditor

                    data="<p>Hello from CKEditor 4!</p>"

                />

            </div>

        );

    }

}


export default App;


Angular:

========


In order to create an editor instance in Angular, install the ckeditor4-angular npm package as a dependency of your project:


Project_cmd:>npm install ckeditor4-angular


After installing, import CKEditorModule to your application:


import { CKEditorModule } from 'ckeditor4-angular';


@NgModule( {

    imports: [

        ...

        CKEditorModule,

        ...

    ],

    …

} )


e.g:


The initial data of the WYSIWYG editor. It can be a static value:


<ckeditor data="<p>Hello, world!</p>"></ckeditor>

or a shared parent component’s property:

import { CKEditor4 } from 'ckeditor4-angular/ckeditor';

@Component( {

    ...

} )

export class MyComponent {

    public editorData = '<p>Hello, world!</p>';

}

<ckeditor [data]="editorData"></ckeditor>


Integrated with ngModel:

------------------------


To use it, first create a model in your component:


@Component( {

    ...

} )

export class MyComponent {

    public model = {

        editorData: '<p>Hello, world!</p>'

    };

    ...

}

Then you can use the model in the template to enable the two-way data binding.


<ckeditor [(ngModel)]="model.editorData"></ckeditor>

Thursday, 10 June 2021

React File Upload - import CSV Axios POST

 


React File Upload - import CSV Axios POST - (blob from Spring Boot)

------------------------------------------------------------------------


<div className="form-group files color">

  <label>Upload Your File </label>

  <input type="file" className="form-control" name="file" onChange={onFileChangeHandler}/>

</div>



onFileChangeHandler = (e) => {

e.preventDefault();


setSelectedFile: e.target.files[0]


const formData = new FormData();

formData.append('file', selectedFile);

fetch('http://localhost:8080/upload', {

method: 'post',

body: formData

}).then(res => {

if(res.ok) {

console.log(res.data);

alert("File uploaded successfully.")

}

});

};



Upload specfic button to make API call

-----------------------------------------------

<input type="file" className="form-control" name="file" onChange={onFileChangeHandler}/>


<Button type="button"  onClick={() => uploadChanges()}>Upload</Button>





onFileChangeHandler = (e) => {

e.preventDefault();


setSelectedFile: e.target.files[0]

}



const uploadChanges = () => {



const formData = new FormData();

formData.append('file', selectedFile);


axios.post("/api/endPointURL, data, {

headers: {

"Content-Type": "text/plain;charset=utf8",

}

// receive two parameter endpoint url ,form data

} ).then(res => { // then print response status

console.log("response->"+res.data.statusMessage);


if(res.data.statusTxt === 'Success'){

setMessage('Uploaded Successfully');

setToastrType("success");

}else {

setMessage(res.data.errorTxt);

setToastrType("error");

}

setShowToastr(true);

})

}else{

//alert("Choose the excel and click upload");

setMessage("Choose the excel and click upload");

setToastrType("error");

setShowToastr(true);

}

}

React File Download - exportCSV Axios POST

 React File Download - exportCSV Axios POST - (blob from Spring Boot)

--------------------------------------------------------------------


component.js

---------------

import ServiceApi from './ServiceAPI';


<Button onClick={downLoadFile}> DownLoad</Button>



function downLoadFile(){


ServiceApi.exportCSV(postData).then( response =>{

const url = window.URL.createObjectURL(new Blob([response.data]));

const link = document.createElement('a');

link.href = url;

link.setAttribute('download', 'FileName.xls'); //or any other extension

document.body.appendChild(link);

link.click();

});


}



ServiceAPI.js

------------------


import axios from 'axios';


class ServiceApi {


exportCSV(postData){

return axios.post('/api/endPointURL',postData, {ContentDisposition: "attachment;filename=report.xls", responseType:

'blob'} ).catch(function(error) {

console.log(error);

});

}


export default new ServiceApi()


Tuesday, 8 June 2021

React- Hooks- Gloabal spinner for react applicaiton

 React- Hooks- Gloabal spinner for react application

======================================


src/hooks/useFullPageSpinner.js

-------------------------------


import React, { useState } from 'react';


import { Spinner } from '@mat-ui/spinner';

import { AriaAnnouncerProvider } from '@mat-ui/aria-announcer';


const useFullPageSpinner = () => {


  const [loading, setLoading] = useState(false);



  return [

    loading ?     <>  <AriaAnnouncerProvider>

                          <Spinner style={{ position: "absolute", top: "50%", left: "50%" , zIndex:1000}} className="circular-spinner large" />

                      </AriaAnnouncerProvider>

                  </>: null,

    () => setLoading(true),   // show the spinner

    () => setLoading(false)  // hide the spinner

   ]

}

export default useFullPageSpinner;



src/App/componets.js

--------------------


import React from 'react';


import useFullPageSpinner from "../hooks/useFullPageSpinner";



App () {


  const [loader, showLoader, hideLoader] = useFullPageSpinner();

  const [ userData, setUserData] = useState([]);


   useEffect( () =>{

    loadUserData();

  },[]);


  function loadUserData(){

    showLoader();

    api.get('/api/endpoint').then( res =>{

      hideLoader();

      if(res.status){

        console.log(res);

        setUserData(res.data);

      }

      else{

        setUserData([]);

      }

    });

  }

  return (


    <loader>


     { userData.map( item=> <div >{ itemv} </div>) }

   


    </>


  )

}

React - CORS issue, Axios API call in one place to entire app, Service componet DI , component - 3 ways

 React - Axios call - hooks based - 3 types API connection - CORS issue fix

===========================================================================

cmd:>npx create-react-app reactProject


cd reactProject


....


develop some pages/component/screens in react projects

.....


reactProject:> npm i Axios


verify the axios version at package.json


Avoid the cors issue in local development, while prod - both UI and service need to be in same place.

package.json

-----------------


"proxy": "http://localhost:8080",

"engines": {

"node": "^12",

"npm": "^6"

},


Best - Method:1


src/utils/api.js

----------------------


import axios from 'axios';



const call = method => (url, { body, query, headers } = {}) => {

return axios({

method,

baseURL: url, //baseURL: `http://localhost:8080${url}`,

data: body,

headers, //headers:{"Access-Control-Allow-Origin": "*"},

params: query

})

.then(response => response.data)

.catch(function(error) {

console.log(error);

});

};


export default {

get: call('GET'),

post: call('POST'),

put: call('PUT'),

delete: call('DELETE')

};




App.js

-------

useEffect( () =>{

// global get,post,put methos, just pass end point url of API, Error handling done in one place.


const userData = api.get('/api/endpoint');

console.log(userData)

});




Method:2

----------


src/services/serviceApi.js

---------------------------

import axios from 'axios';


class ServiceApi {


getUserData() {

return axios.get('/api/endPoint').catch(function(error) {

console.log(error);

});

}


getUserInfoData() {

return axios.get('/api/user').catch(function(error) {

console.log(error);

});

}

}



export default new ServiceApi()



App.js

------

import ServiceApi from '../services/serviceApi';


useEffect( () =>{

ServiceApi.getUserData().then(res => {

console.log(res.data.data);

//setData(res.data.data[0]);

})


});


Method:3

--------

component.ts

-------------


import axios from 'axios'; // method:3


useEffect( () =>{

axios.get('/api/endpoint').then ( response =>{

console.log(response)

}).catch( function(error){

console.log(error)

});

},[])

Sunday, 30 May 2021

React - Functional - Dynamic Form

 import React, { useState } from 'react';


const Form = () => {

    const [ownerState, setOwnerState] = useState({

        owner: '',

        description: '',

    });


    const [cateState, setCateState] = useState({

        name: '',

        age: '',

    });


    const [cats, setCats] = useState([]);


    const handleOwnerChange = (e) => {

        setOwnerState({

        ...ownerState,

        [e.target.name]: [e.target.value],

    });

        setCateState([

            ...cats,

            cateState,

        ])

        

    };


    const blankCat = { name: '', age: '' };

    const [catState, setCatState] = useState([

        { ...blankCat },

    ]);


    const addCat = () => {

        setCatState([...catState, { ...blankCat }]);

    };


    const formSubmit = (e) =>{

        e.preventDefault();

        console.log(catState,ownerState);

    }


    return (

        <form  onSubmit={formSubmit}>

            {/* <label htmlFor="owner">Owner</label>

            <input

                type="text"

                name="owner"

                id="owner"

                value={ownerState.owner}

                onChange={handleOwnerChange}

            />

            <label htmlFor="description">Description</label>

            <input

                type="text"

                name="description"

                id="description"

                value={ownerState.description}

                onChange={handleOwnerChange}

            /> */}

            <input

                type="button"

                value="Add New Cat"

                onClick={addCat}

            />

            {

                catState.map((val, idx) => {

                    const catId = `name-${idx}`;

                    const ageId = `age-${idx}`;

                    return (

                        <div key={`cat-${idx}`}>

                            <label htmlFor={catId}>{`Cat #${idx + 1}`}</label>

                            <input

                                type="text"

                                name={catId}

                                data-idx={idx}

                                id={catId}

                                className="name"

                                onChange={handleOwnerChange}

                            />

                            <label htmlFor={ageId}>Age</label>

                            <input

                                type="text"

                                name={ageId}

                                data-idx={idx}

                                id={ageId}

                                className="age"

                                onChange={handleOwnerChange}

                            />

                        </div>

                    );

                })

            }

            <input type="submit" value="Submit" />

        </form>

    );

};


export default Form;

React Class based - Dynamic Form -

 import React from "react";



class Form extends React.Component {

  state = {

    devices: [{name:"", password:""}],  

  }

handleChange = (e) => {

    if (["name", "password"].includes(e.target.className) ) {

      let devices = [...this.state.devices]

      devices[e.target.dataset.id][e.target.className] = e.target.value.toUpperCase()

      this.setState({ devices }, () => console.log(this.state.devices))

    } else {

      this.setState({ [e.target.name]: e.target.value.toUpperCase() })

    }

  }

addCat = (e) => {

    this.setState((prevState) => ({

    devices: [...prevState.devices, {name:"", password:""}],

    }));

  }

handleSubmit = (e) => { 

    e.preventDefault() 

    alert(JSON.stringify(this.state.devices));

}

render() {

    let { devices} = this.state

    return (

      <form onSubmit={this.handleSubmit} onChange={this.handleChange} >

        {/* <label htmlFor="name">Owner</label> 

        <input type="text" name="owner" id="owner" value={owner} />

        <label htmlFor="description">Description</label> 

        <input type="text" name="description" id="description" value={description} /> */}

        <button onClick={this.addCat}>Add new cat</button>

        {

          devices.map((val, idx)=> {

            let deviceId = `Device Name-${idx}`, passwordId = `Password-${idx}`

            return (

              <div key={idx}>

                <label htmlFor={deviceId}>{`Device #${idx + 1}`}</label>

                <input

                  type="text"

                  name={deviceId}

                  data-id={idx}

                  id={deviceId}

                  value={devices[idx].name} 

                  className="name"

                />

                <label htmlFor={passwordId}>password</label>

                <input

                  type="password"

                  name={passwordId}

                  data-id={idx}

                  id={passwordId}

                  value={devices[idx].password} 

                  className="password"

                />

              </div>

            )

          })

        }

        <input type="submit" value="Submit" /> 

      </form>

    )

  }

}

export default Form;

Friday, 8 January 2021

AWS - Free Tier - Apply coupon Code

 

How do I add a promotional code to my AWS account?


I received a promotional code or credit for AWS services. How do I add it to my AWS account?

Resolution

You can add a promotional code to your AWS account by doing the following:

  1. Open the Credits page of the Billing and Cost Management console.
  2. For Promo Code, enter the promotional code.
  3. For Please type the characters as shown above, enter the code shown in the CAPTCHA.
  4. Choose Redeem.

If the promotional code was entered correctly, is valid, hasn't expired, and hasn't been previously redeemed, it is added automatically to your AWS account.

Friday, 25 September 2020

Full Stack Developer - React + Spring Boot

Full Stack Developer - React + Spring Boot

==============================


React - JS ( hooks, redux, formik, testing)

********************************************


1.codevolution - youtube 


1.1 Practical React -14 features

1.2 Formik

1.3 ReactJS Tutorial for Beginners - Basic with class based

1.4 React Hooks Tutorial

1.5 React Redux


2.tkssharma - CodeLabs -youtube


2.1 react-fullcourse

--2.2 react-hooks-crashcourse

--2.3 react-component-testing

--2.4 redux-react-statemngt

--2.5 react-formik

--2.6 build-react-apps

3.Udemy_techsith + youtube 


3.1 React Hooks Beginner to Expert - Udemy 

3.2 react from scratch + hooks + redux--

4.netninja - youtube


4.1 react-context-hooks

4.2 react-redux-firebase-app

4.3 complete react-tutuorial--- V-covered


5.codingthesmartway - youtube




spring boot: ( SPB, FSD, Best practice, Miroservices ,AWS )

***********************************************************


6.javagudies -spb FSD- youtube 


6.1 React Spring Boot FSD (Employee CRUD opeation)

6.2 SPB - features - profiles, actuator, JPA, spring Web, dev tools, swagger, @Value, .yml, H2, Maria DB


7.javabrains - spb microserices - youtube 


7.1 SPB ( Course ,Topic)


8.javatecchi - youtube -spb, Miroservices ,aws, docker


8.1 Spring boot - Miroservices ( Order, Payment, GateWay, Eureka Registry serve )

--8.2 SPB tutorial


9.tecchprime - youtube


--9.1 spb_primer


10.in28mintues -workspace

10.1 spring boot 100 steps - beginner to expert - Udemy

10.2 Full stack React + spring boot

10.3 AWS - Certtified solution architect

--10.4 SPB Tutorial



11.telusko - youtube



12. SPB _ tutorials

12.1 tutorial points

12.2 online Tutorials points



tutorials:

***********


12.Machine Learning


13.Database




Sunday, 19 April 2020

MicroFrontend - UI Angular9 custom element with Web components

MicroFrontend - UI Angular custom element with Web components:
------------------------------------------------------------------------
NodeJs 10.x Ng-CLI 9.0.1 as on 19-apr-2020 12:21AM

Source CODE: https://github.com/gnganpath/Angular9-MicroFrontend-customElement-WebComponent

MicroApp:

Step:1
ng new MicroApp

complete the All the development of Child/Micro app as entire app or particular component as ??? Particular module???
Note: For Module ill be part of any component. So, The idea will module will become component as mciroApp

Step:2
MicroApp:> ng add @angular/elements

will generate / Impact
package.json ->
  "@angular/elements": "^9.0.7",
  "document-register-element": "1.8.1",   --> change the version 1.8.1 if not then npm install

polyfill.ts ->Automatically Import this packages into polyfills.ts file: if not do it maually and npm i
  import 'document-register-element';

Step:3

Install some polyfills:
MicroApp:> npm i @webcomponents/custom-elements --save

Import those packages into polyfills.ts file:

import "@webcomponents/custom-elements/src/native-shim";
import "@webcomponents/custom-elements/custom-elements.min";

Step:4
MicroApp:> ng add ngx-build-plus

will generate / Impact
package.json ->
 "ngx-build-plus": "^9.0.6",


"architect": {  "build": {    "builder": "ngx-build-plus:browser  .... $while building$ "builder": "ngx-build-plus:build",  ....
"budget": [
              // to avoid budget Error  Delete this part in Micro UI angular.json , ->budget error occurs
                {
                   "type": "anyComponentStyle",
                   "maximumWarning": "2mb",  //from 6kb
                    "maximumError": "5mb"     // from10kb
                }
              ]
"serve": {    "builder": "ngx-build-plus:dev-server",    ...
"test": {    "builder": "ngx-build-plus:karma",


Step:5
MicroApp:> app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Injector} from '@angular/core';

import { createCustomElement } from '@angular/elements';

bootstrap: [],   // while develop it will get fill , but in build time it must be empty
entryComponents: [AppComponent]   // entire app as microUI

export class AppModule {

  constructor(private injector: Injector){   }

  ngDoBootstrap(){
    const myCustomElement = createCustomElement(AppComponent, { injector: this.injector });
    customElements.define('micro-app1', myCustomElement);    /// micto-app is <custom-elment-tag> like <header> <footer>
  }
}

Step:6

build the child app and generate dist for master/parent app

MicroApp:>ng build --prod --output-hashing none --single-bundle true --bundle-styles false
Notes:
--output-hashing none ->will avoid hashing the file names.
--single-bundle true ->will bundle all the compiled files into a single JS file.
--bundle-styles false ->if we follow the same library css for all the projects

Step:6.1
Sometimes budget error will occur. so, Make the correction at MicroApp angular.json
 "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2mb",  //from 6kb
                  "maximumError": "5mb"     // from10kb
                }
              ]
copy the dist folder into master app src/app/assets/MicroApp --> which contains Main.js, index.html,3 other files

Step:6.2

To do the auto copy -> npm install copyfiles -g   // in the machine/ laptop

MciroApp:> npm run copfiles : copyfiles ./dist/*.* MasterAppPath/src/app/assets

ALternatively :   ng build make output path from MciroApp

Step:7

To generate mutliple micro app follow the step -> Step 1- 6

Another child app or MciroApp dist


Step:8 
MasterApp / ContainerApp /
ng new MasterApp

Step: 9 ( Repeat Step 2 )
MasterApp:> ng add @angular/elements

will generate / Impact
package.json ->
  "@angular/elements": "^9.0.7",
  "document-register-element": "1.8.1",   --> change the version 1.8.1 if not then npm install

polyfill.ts ->Automatically Import this packages into polyfills.ts file: if not do it manually and npm i
  import 'document-register-element';

Step:10 (  Repeat Step 3 )  [ No need ngx-build - Which is step 4 ]

Install some polyfills:
MicroApp:> npm i @webcomponents/custom-elements --save

Import those packages into polyfills.ts file:

import "@webcomponents/custom-elements/src/native-shim";
import "@webcomponents/custom-elements/custom-elements.min";

Step:11

MasterApp
app.module.ts
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]  // which allows custom element as recognized element in master App
})
export class AppModule { }

Step:12
MastetApp:

Whichever the component need to import/use the in that component

MasterApp - Requiedcomponent.component.ts

  childAppPath = 'http://localhost:4200/assets/MicroApp/main.js';
  constructor(){   }

  ngOnInit() {
    this.loadScript(this.childAppPath); 
  }

  loadScript(scriptPath): void {

    var alreadyLoaded = false;

    for (var scriptIndex in document.scripts) {
     // console.log(scriptPath, scriptIndex, document.scripts[scriptIndex].src)
      if (!alreadyLoaded && scriptPath === document.scripts[scriptIndex].src) {
        alreadyLoaded = true;
        break;
      }
    }
    if (!alreadyLoaded) {
      const content = document.getElementById('content');
      const script = document.createElement('script');
      script.src = scriptPath;
      content.appendChild(script);
    }
  }

Step:13
MasterApp -

<div id="content"><micro-app1></micro-app1></div>    // <micro-app1> is the custom Tag element mentioned at MicroApp app.module.ts

MasterApp:> ng serve ==> http://localhost:4200 default if chagne the default port Change the ChilAppPath/port

note: Some times, node js 12 will gives Build for http-server error. Other type of method .So maintain node js version 10 for angualr cli9
      Sometime Buget[.] will come, So increase the angular.json  in child app,


Ref: https://dzone.com/articles/build-micro-front-ends-using-angular-elements-the
Ref: https://www.techiediaries.com/angular/angular-9-web-components-custom-elements-shadow-dom
Ref: https://medium.com/@IMM9O/web-components-with-angular-d0205c9db08f

Thursday, 16 April 2020

Ng9 Method to Micro UI angular Element

add into package.json files
----------------------------

 "@angular/elements": "^7.2.14",   "@angular/elements": "^8.2.13",

 "document-register-element": "1.8.1",
 "@webcomponents/custom-elements": "^1.1.3",
 "@webcomponents/webcomponentsjs": "^2.0.4"

 "ngx-build-plus": "^9.0.0",

webpcak.externals.js add the file into train booking root level
----------------------------------------------------------------
module.exports = {
externals: {
},
output: {
jsonpFunction: 'webpackJsonpAppname',
library: 'assetreview'
}
};


app.component.ts:
---------------------

import {createCustomElement} from "@angular/elements";

 bootstrap: [],
 entryComponents: [AppComponent] 

 export class AppModule {
 constructor(private injector: Injector) { }

  ngDoBootstrap() {
    const myCustomElement = createCustomElement(AppComponent, { injector: this.injector });
    customElements.define('micro-app1', myCustomElement);
  }

"build-angular-element": "ng build --prod --extraWebpackConfig webpack.externals.js --output-hashing none --single-bundle true --bundle-styles false"

Schema validation failed with the following errors:
  Data path ".budgets[1].type" should be equal to one of the allowed values.

 
   {
                  "type": "anyComponentStyle",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }




polyfill.ts

// Used for browsers with partially native support of Custom Elements -
import '@webcomponents/custom-elements/src/native-shim';
import '@webcomponents/custom-elements/custom-elements.min';
import '@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js'; 



    this.assetReviewPath = 'http://localhost:4200/assets/assetreview/main.js'
  this.loadScript(this.assetReviewPath, "asset-review");
  loadScript(scriptPath: string, tagName: string): void {

    var alreadyLoaded = false;

    for (var scriptIndex in document.scripts) {
      if (!alreadyLoaded && scriptPath === document.scripts[scriptIndex].src) {
        alreadyLoaded = true;
        break;
      }
    }
    if (!alreadyLoaded) {
      const content = document.getElementById('content');
      const script = document.createElement('script');
      script.src = scriptPath;
      content.appendChild(script);
    }

    this.currentApp = tagName;
  }
 
 
 
  flightAppPath = 'http://localhost:4500/assets/flight-booking/main.js';
  traintAppPath = 'http://localhost:4500/assets/train-booking/main.js';
  constructor(){


  }

  ngOnInit() {
    this.loadScript(this.flightAppPath);
    this.loadScript(this.traintAppPath);
  }

  loadScript(scriptPath): void {

    var alreadyLoaded = false;

    for (var scriptIndex in document.scripts) {
      if (!alreadyLoaded && scriptPath === document.scripts[scriptIndex].src) {
        alreadyLoaded = true;
        break;
      }
    }
    if (!alreadyLoaded) {
      const content = document.getElementById('content');
      const script = document.createElement('script');
      script.src = scriptPath;
      content.appendChild(script);
    }

  }

AWS account creation - Sep2026

AWS conosle to build AWS skills- Account creation inclues Digilocker - Aadhar connectivity, UPI autopay, mobile, email verification process.