Monday, December 12, 2022

postgreSQL: how to copy (duplicate) a row with binary data

 

>PROBLEM

You need to duplicate a table's row copying from a previous one that contains decode binary data that we shal avoid using copy/paste.


>SOLUTION

Notice that in this example, prtkey and pubkey are binary fields using bytea type.

The uptime is a timestamptz not null field.

 

INSERT INTO keysvc (id,title,pvtkey,pubkey,status,uptime) VALUES( 2, 'ramnode4',null ,null ,1, CURRENT_TIMESTAMP);  

with keys as (SELECT pvtkey, pubkey, uptime FROM keysvc where id = 1)
update keysvc set pvtkey=(select pvtkey from keys), pubkey=(select pubkey from keys), uptime=(select uptime from keys) where id =40;

NOTE: this solution was also published by myself at this date on 
There you'll find another alternative.

>ENV

PostgreSQL


Thursday, December 8, 2022

angular: [webpack-dev-server] Disconnected! polyfills.js:1 [webpack-dev-server] Trying to reconnect...

  

>PROBLEM


When you access the Angular app, the browser's console returns the following message, that keeps repeating:

[webpack-dev-server] Disconnected!
polyfills.js:1 [webpack-dev-server] Trying to reconnect...


>SOLUTION


When starting the Angular app using the "--host" flag, it may also require the "--disable-host-check" flag.

It usually happens when using docker, and it is required the "--host" flag to enable access to the app.


Notice that, when you start the service using just the "host" flag, you get this advice:


  Warning: This is a simple server for use in testing or debugging Angular applications

  locally. It hasn't been reviewed for security issues.

  Binding this server to an open connection can result in compromising your application or

  computer. Using a different host than the one passed to the "--host" flag might result in

  websocket connection issues. You might need to use "--disable-host-check" if that's the

  case.

  


>ENV

Angular CLI: 14.2.9

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64

debian/docker




[MYREF]:
y;faq-angular [webpack-dev-server] Disconnected! polyfills.js:1 [webpack-dev-server] Trying to reconnect...<memo<angularx;.

Monday, November 28, 2022

Refused to apply style from 'http://localhost:80/api/index' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

 


>PROBLEM

Attempt to access the server returns:

Refused to apply style from 'http://localhost:80/api/index' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.


>SOLUTION 


This kind of issue usually happens because it was not possible to reference the sources.

In this examples, the code was developed using "/" as root URL by the respective spring annotation:

  @RequestMapping("/")   

In this specific case this annotation may be omitted, because the framework assumes it as default, but shown here to clarify.


And the access was:

  http://localhost:8047/


After, the root URL was mapped to "/sg5", using:

  @RequestMapping("/sg5")


And the access was switched:

  http://localhost:8047/sg5


Considering the changes also made in the security layer (in this case the spring security class), it is also required to refactor the static references adding "../" before them.


NOTES: 

1. JavaScript scripts generates CORS messages instead of MIME message. 

To solve, check the example below:

- BEFORE:

<script src="bootstrap/js/bootstrap.min.js"></script>



- SOLUTION: relative path was fixed:

<script src="../bootstrap/js/bootstrap.min.js"></script>


2. Possibly, It may be necessary to update the application's CORS configuration depending of its architecture.


>ENV

springboot

java17



[MYREF]:
y;faq-Refused to apply style from 'http://localhost:8047/sg5/index' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.<memo<springboot;.

Saturday, November 26, 2022

linux: docker: docker: Error response from daemon: driver failed programming external connectivity on endpoint


>PROBLEM


Attempt to start a docker container, returns:

  Error response from daemon: driver failed programming external connectivity on endpoint YOUR_CONTAINER_NAME

  (a8dc1e2b183712da69829c9efd642bf2bdcb504556a8dbd3324902adcb79fc3b): (

  iptables failed: iptables --wait -t nat -A DOCKER -p tcp -d 0/0 --dport SOME_PORT_HERE -j DNAT --to-destination 172.17.0.2:8048 ! -i docker0

  : iptables: No chain/target/match by that name. 

   (exit status 1))

  Error: failed to start containers: YOUR_CONTAINER_NAME


>SOLUTION

This kind of issue has more than one cause.
It will be described two of them, very common causes.


1. iptables config

Set the following iptables rule before the others, at the beginning:

  iptables -t nat -A POSTROUTING -o docker0 -j MASQUERADE


2. Restart docker

If you already has set procedure below and if it happens again, try to do:

  systemctl restart docker



>ENV

docker/debian based distributions



[MYREF]:

y;faq-docker: Error response from daemon: driver failed programming external connectivity on endpoint<memo<docker;.


Thursday, November 24, 2022

linux: OpenVz: docker: iptables nat issue: iptables v1.8.7 (legacy): can't initialize iptables table `nat': Table does not exist (do you need to insmod?)


 >PROBLEM

Common scenarios:

1. Docker installation fails on Linux distributions,

 or  

2. Attempt to run "iptables -t nat -L -n" command fails.


Both scenarios return the same message:

iptables v1.8.7 (legacy): can't initialize iptables table `nat': Table does not exist (do you need to insmod?)
Perhaps iptables or your kernel needs to be upgraded.


Reason:

Docker uses iptables during installations where the S.O. has this firewall command by default.


>SOLUTION


Make sure that is the case by running the following command:

iptables -t nat -L -n


If it fails, there are two main possibilities.
Choose first the easier one.

- If using a cloud hosting, check with the support service to "enable NatFilter".

or

- Maybe a system upgrade is required, sometimes even the kernel.


A successful test, when the NatFilter is enabled shall return something like this:

$ iptables -t nat -L -n

Chain PREROUTING (policy ACCEPT)

target     prot opt source               destination

Chain INPUT (policy ACCEPT)

target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)

target     prot opt source               destination

Chain POSTROUTING (policy ACCEPT)

target     prot opt source               destination


>ENV

cloud hosting

OpenVz/debian 9-11/Ubunto18-22



MYREF: 
y;faq-iptables v1.8.7 (legacy): can't initialize iptables table `nat': Table does not exist (do you need to insmod?)<memo<linux;.

Saturday, November 19, 2022

windows: npm: angular: 'ng' is not recognized as an internal command

 

>PROBLEM

Running the command "ng v", returns:

  'ng' is not recognized as an internal command

  'ng' não é reconhecido como um comando interno  (Portuguese)


>SOLUTION


This procedure is about Windows O.S.

After attempting to solve the problem through other experiences, I got no solution.

My Path seemed to be corrupted and there were no files under the user's folder, for instance at:

  C:\Users\<USER>\AppData\Roaming\npm\node_modules


So, to solve the issue, I decided to restart the environment installation from scratch.

This same procedure were executed several times, including restarting the sytem, until the success came. :-)

  1. Uninstall node.js using the windows "Add remove application...".

  2. Remove leftovers. Sometimes there are "skeleton" folder left behind. In my case, it was: C:\Users\<USER>\AppData\Roaming\npm\node_modules

  3. Run the node.js as Administrator. Make sure of that, because it is important.

  4. After the installation is fineshed, check it:
    node --version
    npm --version

  5. Install @angular/cli that it is the lib that provides the "ng" command, as global installation (important: not locally).

  6. The previous command will install the latest version. If you're working with a specific version, go to the angular project's root folder and check the package.json file to verify which version the project is working with: 
    "dependencies": {
     ...
     "@angular/cli": "^13.2.2",  
    ...

  7. Under the project's root folder, install cli using the same version:
    npm install @angular/cli@13.2.2

  8. Eventually, check it the project's env:
    ng v

  9. It shall return the same version used for the project.








>ENV

Angular
Node.js 16


Monday, November 7, 2022

angular: ERROR: TypeError: Cannot read properties of undefined (reading 'valid')

 

>PROBLEM


When the page loads, the browser's console shows the following error:

  ERROR: TypeError: Cannot read properties of undefined (reading 'valid')






>SOLUTION

1. Check if the HTML template uses form validation. For instance: f.form.valid.

Example:

  <button type="submit" class="btn btn-primary" [disabled]="!f.form.valid">Create info</button>


2. Check the form binding.

It shall be something like this:
#f="ngForm"


>BEFORE

        <form name="modalForm" id="modal_create_info_form" #f novalidate
          (ngSubmit)="f.form.valid && createInfo(modalSelector.value)">

>AFTER

        <form name="modalForm" id="modal_create_info_form" #f="ngForm" novalidate
          (ngSubmit)="f.form.valid && createInfo(modalSelector.value)">



3. Make sure that it declared the respective libs:
 

import { FormControl } from '@angular/forms';

or

// import { FormControl, AbstractControl, FormBuilder, FormGroup, Validators } from '@angular/forms';



>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64

Wednesday, November 2, 2022

angular: template/component renderization failure

 

>PROBLEM


The template/component fails to renderize (it doesn't appear where it should).


>SOLUTION


Considering an example component in the component.html file: 

<my-component></my-component>


Supposing multi-level modules, declare the component in the first level module.


>firts-level.module.ts

import { MyComponentComponent } from './first level path/MyComponentComponent.component';


@NgModule({

  declarations: [

    // ...

    MyComponentComponent,

  ],


NOTE: if the component has parent-child binding, check also its configuration.



>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


angular: Error: Inlining of fonts failed. An error has occurred while retrieving

 


>PROBLEM


Angular compilation fails returning the following message:


  Error: Inlining of fonts failed. An error has occurred while retrieving https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap over the internet.

  getaddrinfo ENOTFOUND fonts.googleapis.com





>SOLUTION


Check your Internet connection.



>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


Friday, October 28, 2022

angular: Error: NG0301

 

>PROBLEM


The angular app throws the following error during attempt to open a child modal:

   Error: NG0301

This error may have many types of causes.
It usually means some issue between the component and the template configuration or some subjacent library version incompatibility.

Below there are the four different solutions from different real cases that worked for me.

NOTE: the 3rd solution is the one that I most use. If you are sure that nothing changed in your code, try it. Run the "npm audit fix --force" once or more, but make sure that a node_modules backup is made before. If this folder gets corrupted, fixing it is time-consuming.


>SOLUTION #1


>before

<button id="btn_update_activity_" type="button" class="btn btn-primary icon-config icon-update_20g"
  style="margin-top: 5px; margin-left: 5px;" (click)="openModal(template)">Open modal</button>

<ng-template #template>

>after

Found duplicated ng-template reference.
The second one was switched to solve the conflict.

<button id="btn_update_todo_" type="button" class="btn btn-primary icon-config icon-update_20g"
  style="margin-top: 5px; margin-left: 5px;" (click)="openModal(templateUpTodo)">Open modal</button>

<ng-template #templateUpTodo>



>SOLUTION #2


>before

- todos.component.ts (parent-child biding):

  <!-- xxmodal TODO UPDATE -->

  <app-uptodo [theTodo]="todoi" [email]="email" [stoken]="stoken" [activity]="activity" [activities]="activities"

  (click)="setTodoi(todo)" (updateEvent)="updateTodo($event)"></app-uptodo>

  <!-- xxupdate -->



- uptodo.component.ts (child):

export class UptodoComponent implements OnInit {

  modalRef: BsModalRef;

  @Input()

  email: string;

  @Input()

  stoken: string;

  @Input()

  activities = [];

  @Input()

  theTodo: any;

  activity: string;

  @Output()

  updateEvent = new EventEmitter<string>();


>after

- uptodo.component.ts (child):

export class UptodoComponent implements OnInit {

// ...

  @Input()

  activity: string;

  @Output()

  updateEvent = new EventEmitter<string>();



>SOLUTION #3

Make a backup of the node_modules folder in another place.
Stop the app.

1. Run the command:
npm install

2. Apply the fix command:
npm audit fix

3. Usually there are issues. Run again with --force flag, one or many times:
npm audit fix --force

4. Restart the app.


>SOLUTION #4

If the issue happens too frequently, maybe an update may solve it.
Do:
npm update

Please!!! Create a backup first to not cry later!  :-)

NOTE:
After the update, it may appear some VSCode error messages.
Restart VSCode.


>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64






MyRef;
y;faq-Error: NG0301<memo<angularx;.

Saturday, October 15, 2022

angular: ngx-bootstrap modal fails when closing

 

>PROBLEM

Attempt to close the modal fails.






ERROR TypeError: Cannot read properties of undefined (reading 'hide')
    at main.js:1:434209
    at UT (main.js:1:69900)
    at s (main.js:1:70062)
    at HTMLButtonElement.<anonymous>


>SOLUTION

BEFORE

The new modal component code:

import { Component, OnInit, TemplateRef } from '@angular/core';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';

@Component({
  selector: 'app-deltodo',
  templateUrl: './deltodo.component.html',
  styleUrls: ['./deltodo.component.scss'],
})
export class DeltodoComponent implements OnInit {

  modalRef: BsModalRef;
  title: string;

  constructor() {}


  ngOnInit(): void {}

}

AFTER

The modal component code:

 

import { Component, OnInit, TemplateRef } from '@angular/core';
import { BsModalRef, BsModalService } from 'ngx-bootstrap/modal';

@Component({
  selector: 'app-deltodo',
  templateUrl: './deltodo.component.html',
  styleUrls: ['./deltodo.component.scss'],
})
export class DeltodoComponent implements OnInit {

  title: string;
  // list: any[] = [];

  constructor(public modalRef: BsModalRef) {}

  ngOnInit(): void {}

}

 

  


>ENV

angularx_ngx_bootstrap_modal_

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64

Friday, September 9, 2022

angular tutorial: After some time without programming, I need a refresh! :-)

 

>PROBLEM


Like as everybody never forgets... What a lie!  :-)

After sometime without using a technology, you need "swap from disk to memory".


>SOLUTION


Create a revision summary.

Example here.


>ENV

Angular

Thursday, September 1, 2022

node.js: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

 

>PROBLEM


A request generates the following error:

  Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client


>SOLUTION


It happens when some exception occurs before returning the request, for instance a "res.sent" statement.

Debug the application step-by-step.

To simplify, you may comment on the code from the start.

Tip: check database exceptions not treated.

Having more than one exception becomes tricky if you can't reproduce the same request.


Be sure to fix all possible exceptions.

TIPS

- Verify database possible exceptions (undefined/null values).
- If using JWT, check possible "jwt session expired" exception.
- "if conditions" and "redirections".
Some if conditions may not avoid running the code ahead from it.
- Make sure that you have guarded your arguments checking if they are possibly null or undefined.
- Unexpected type values.
 JavaScript is not a typed language, so part of the code may get something different from expected.

The above tips are just some of them. 


>ENV

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


Saturday, August 27, 2022

node.js: date-and-time offset = dateObj.getTimezoneOffset() TypeError: Cannot read properties of undefined (reading 'getTimezoneOffset')

 

>PROBLEM


Supposing using date-and-time lib:

  npm install date-and-time --save

  const date = require('date-and-time')


and the date returning the standard format, something like this (locale: Brazil):

obj.createdAt = 'Fri Aug 26 2022 21:14:34 GMT-0300 (Horário Padrão de Brasília)';


the compiler throws the following error:

  date-and-time offset = dateObj.getTimezoneOffset() 

  TypeError: Cannot read properties of undefined (reading 'getTimezoneOffset')



>SOLUTION


***WRONG

created_at: date.format(obj.createdAt, 'YYYY/MM/DD HH:mm:ss'),


>RIGHT

created_at: date.format(new Date(obj.createdAt), 'YYYY/MM/DD HH:mm:ss'),



>ENV

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


Tuesday, August 16, 2022

javascript: TypeError: Cannot read properties of undefined

 


>PROBLEM


TypeError: Cannot read properties of undefined


>SOLUTION


This error may have many causes.

Here, it's shown a tricky one — cyclic reference, when one file references the other.

Check the example below:


>file1 - SecTools.js

const UserSvc = require('../../models/business/UserSvc');

static verifySToken(req) {

if (req === 'undefined' || req == null) return false;

let userStoken = UserSvc.stokenSvc[req.body.email];

//...

}


>file2: UserSvc.js

const SecTools = require('../security/SecTools');

myOtherfunction() {

user.token = SecTools.signWithJwt(user.email);

}

The SecTools has reference to UserSvc, and vice-e-versa.


Remove the cyclic reference to fix the issue.


>IMPORTANT NOTE

When it happens an error during runtime, the same message may happen.
For instance, if the code calls a persistence method that is not recognized (found), to debug the app try to comment previous operations before that method is called. There is a good probability that one operation before (above the call that fails) is throwing an exception that results with this message.
It happens with many compilers, for many programming languages.
Something "mad", unexpected, think about this hypotheses.
Do not take compiler messages as they were always possible to show the real problem that it is causing the issue.


>ENV

Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64


express: Error: Cannot find module ...code: 'MODULE_NOT_FOUND'

 


>PROBLEM

Express returns compilation error:


node:internal/modules/cjs/loader:488

      throw e;

      ^

node:internal/modules/cjs/loader:488
      throw e;
      ^

Error: Cannot find module 'M:\work\devcli_\javascript\jstopics\
   express\node_sequelize_ultering_ml40643\prj\node_modules\sequelize\types'
    at createEsmNotFoundErr (node:internal/modules/cjs/loader:960:15)
    at finalizeEsmResolution (node:internal/modules/cjs/loader:953:15)
    at resolveExports (node:internal/modules/cjs/loader:482:14)
    at Function.Module._findPath (node:internal/modules/cjs/loader:522:31)
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:919:27)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.&lt;anonymous&gt; (M:\work\devcli_\javascript\jstopics\
       express\node_sequelize_ultering_ml40643\prj\models\security\SecTools.js:5:19)
    at Module._compile (node:internal/modules/cjs/loader:1101:14) {
  code: 'MODULE_NOT_FOUND',
  path: 'M:\\work\\devcli_\\javascript\\jstopics\\
      express\\node_sequelize_ultering_ml40643\\prj\\node_modules\\sequelize\\package.json'
}




 

>SOLUTION


The tip is in this line (red):

Error: Cannot find module 'M:\work\devcli_\javascript\jstopics\express\node_sequelize_ultering_ml40643\prj\node_modules\sequelize\types'

that means the class loader was not able to find a reference.
Check the require statements that contain the type.

In this example, it was found the mistake in this declaration:

const { Utils } = require('sequelize/types');



>ENV

Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64

Monday, August 8, 2022

java: javax.mail fails to send email to Gmail account returning: 535-5.7.8 Username and Password not accepted. Learn more at


 >PROBLEM

Attempt to send email fails returning the following message:

javax.mail fails to send email to Gmail account returning: 535-5.7.8 Username and Password not accepted. Learn more at


>SOLUTION

Since 05/30/2022 , you may lose access to apps that are using less secure sign-in technology.
To help keep your account secure, Google will no longer support the use of third-party apps or devices which ask you to sign in to 
your Google Account using only your username and password. 

To solve this issue, there are options available.
A fast approach is to use the "App Password" option that generates a new password for the application to get access.

Using this option, the only thing necessary is to replace the previous user's password in your java code with the new password generated.

Go to "Fix Problems", then "Use an App Password".
Follow by the pictures.















>Extra

Configuration used:

PROPS.put("mail.debug", "false");

PROPS.put("mail.smtp.port", "587");

PROPS.put("mail.smtp.auth", "true");

PROPS.put("mail.smtp.starttls.enable", "true");

PROPS.put("mail.smtp.host", "smtp.googlemail.com");

PROPS.put("mail.smtp.ssl.trust", "smtp.gmail.com");

PROPS.put("mail.smtp.ssl.protocols", "TLSv1.2");

PROPS.put("mail.smtp.host", "smtp.gmail.com");

session = Session.getInstance(PROPS, new javax.mail.Authenticator() {

&#64;Override

protected PasswordAuthentication getPasswordAuthentication() {

return new PasswordAuthentication(SENDER, PASSWORD);

}

});


>ENV

Java (javax.mail)
Windows

Wednesday, August 3, 2022

angular/node.js: debugging "Warning: Module not found: Error: Can't resolve..."


 >PROBLEM


After installing MongoDB libs

npm i --save mongoose

npm install @types/mongoose --save-dev


-- used for MongoClient

npm install --save mongodb

npm install --save dotenv



Warning: Module not found: Error: Can't resolve


./node_modules/mongodb/lib/bson.js:12:9-28 - Warning: Module not found: Error: Can't resolve 'bson-ext' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/deps.js:36:2-40 - Warning: Module not found: Error: Can't resolve 'kerberos' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/deps.js:43:2-49 - Warning: Module not found: Error: Can't resolve '@mongodb-js/zstd' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/deps.js:51:2-36 - Warning: Module not found: Error: Can't resolve 'snappy' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/deps.js:54:75-105 - Warning: Module not found: Error: Can't resolve 'snappy/package.json' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'

./node_modules/mongodb/lib/utils.js:1399:32-87 - Warning: Critical dependency: the request of a dependency is an expression

./node_modules/mongodb/lib/utils.js:1407:32-68 - Warning: Module not found: Error: Can't resolve 'mongodb-client-encryption' in 'M:\work\devcli_\javascript\jstopics\angularxLab\prj\node_modules\mongodb\lib'



>SOLUTION


Sometimes, we are not sure if the environment is consistent or not.

The issue reported here was caused by the last lib installed (mongodb) in the app's env.

If you want to check this, you may skip steps and go straight to the fourth approach topic, at the end.

If you do want to recheck your app's env, you may start from the 1st approach.

First of all, stop the application, and close the IDE (VSCode/Eclipse, etc.).


1. APPROACH


- try:

npm cach verify


Retest.


2. APPROACH


If the 1st step didn't work, try to unistall the last libs installed.

In this case, it was the following:


npm uninstall mongoose

npm uninstall  @types/mongoose

npm uninstall mongodb

npm uninstall dotenv


- do:

npm cach clean

or

npm cach clean --force


- reinstall them:


npm i --save mongoose

npm install @types/mongoose --save-dev

npm install --save mongodb

npm install --save dotenv


- do:

npm install


- restart the app.


3. APPROACH


If the 2nd step didn't work, remove all cache and node_modules, reinstalling the libs.


- alternatively install:

npm install node-gyp -g


- run:

npm cache clean --force

rm -Rf node_modules

npm install

npm cache verify


- restart the app.


4. APPROACH


If the 3rd step didn't work, probably it is some lib issue.

To discover the cause, the libs were tested one at a time.


To discover the cause, test the libs one at a time.

Making rollback, both libs were uninstalled.

The it was reinstalled mongoose and tested with minimal code.

Passed.

Then, it was installed MongoClient and tested with minimal code.

The issue returned.

To discover the cause, the code was commented and tested one statement at a time, restarting the app.

First:

import * as mongoDB from 'mongodb';

import * as dotenv from 'dotenv';

After, code was commented and the cause was this line:

    const client = new mongoDB.MongoClient('mongodb://localhost:27017/test');




NOTE:

Sometimes it is necessary to repeat the procedure of cleaning, uninstalling, and installing until the application starts successfully (remember to stop the app and close the IDE):

npm cache clean --force
npm uninstal ... (all the libs to be uninstalled - rollback)
npm install
restart the app


5. APPROACH - Version Issue? Solving the mystery

After identifying the cause through the tests performed, it was possible to try another version to solve the mysterious incompatibility. So, the previous version was uninstalled and replace by another one, in this case a version already working fine in another demo application.

Current version to be replaced:
"mongoose": "^6.5.0",

Uninstalling:
npm uninstall mongoose --no-save

Replacing:
npm install --save mongoose@^5.8.3

Restarting application: success.





6. FINAL TIPS

The compiler for certain kinds of problems returns messages that are not very helpful.
If you stick on the error messages, you get stuck because they have nothing to do with the real cause.
Do not wait for a kind message telling necessarily the real issue behind the exception because it is not always possible.
Checking the result, you will not see something like that:
"Please, fix my mongoose version... blah, blah, blah'.    :-)   :-|   




7. Rule of thumb

Having issues?
Think:

1. Is my environment healthy, stable, and consistent?
First, make sure of that.

2. Think about version conflict.
This is a complicated matter.
Too many libs, too many versions, lead to possible many conflicts.


>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


tslint: expected call-signature: ... to have a typedef

 

>PROBLEM


Using typscript and TSLint, return the following message:

  expected call-signature: 'run1' to have a typedef


>SOLUTION


>BEFORE

  async run1() {

    await mongoose.connect('mongodb://127.0.0.1');

  }

>AFTER  

  async run1(): Promise<any> {

    await mongoose.connect('mongodb://127.0.0.1');

  }


>ENV

VSCode

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


Thursday, July 28, 2022

node.js/express: crbug/1173575, non-JS module files deprecated. ... ERR_SSL_PROTOCOL_ERROR

 

>PROBLEM

Attempt to access the site returns the following error messages:


- On browser console:

crbug/1173575, non-JS module files deprecated.


- On browser page:

ERR_SSL_PROTOCOL_ERROR

Não foi possível estabelecer uma conexão segura com este site

Not possible to establish a secure connection with the site





>SOLUTION

Probably you've tried to access the site using https where it should be http.

Ex.:

- wrong:

https://localhost:3000

- because it uses the http protocol service, so:

http://localhost:3000


>ENV

Angular CLI: 13.2.2
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64

Monday, July 25, 2022

angular: Warning: There are multiple modules with names that only differ in casing. This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.

 

>PROBLEM


The compilation returns the follwing warning message:

  Warning: There are multiple modules with names that only differ in casing.
  This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.
  Use equal casing. Compare these module identifiers:


>SOLUTION

Two things to check:

1. If working on Windows, files hasn't case sensitive approach.
So, make sure that the file pointed by the warning message matches case.
If not, remember that it doesn't help renaming the file. It is necessary to rename the file to a different one and then rename it back using the name with the right case.

2. Check the import referred by the error message that it is pointing to the path with different case.
It works on Windows but not on *nix or Mac.
Follow by the images.








Fixed: switched from "_ConfigDb"  to  "_ConfigDB"







>ENV

Angular CLI: 13.2.2
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64



Sunday, July 24, 2022

angular: is not a known element

 

>PROBLEM

An element is not recognized, returning the following error message:

angular: is not a known element




>SOLUTION

A referencing error may lead to side effects during parsing operation.

The issue is caused by a missing reference that becomes invalid.
It is example happened because the component was deleted using the editor, but it was not able to remove the respective reference together.
It may happen also when you rename or move componets.


Removing the missing references:


the problem is gone.



NOTE:

Errors of @NgModule may lead also to another errors, for instance like NG8002.


>CHECK

>MODULE/SUB-MODULE CONFIG BY IMAGES

Follow by the images how to set up the imports using module and sub-modules through images.











>ENV

Angular CLI: 13.2.2
Node: 16.13.1
Package Manager: npm 8.5.4
OS: win32 x64

Thursday, July 21, 2022

angular: error NG8001: 'pagination-controls' is not a known element



>PROBLEM

 

When angular compiles, returns the following error:

Error: src/app/crud/crud-employee/crud-employee-list/crud-employee-list.component.html:28:11 - error NG8001: 'pagination-controls' is not a known element:

1. If 'pagination-controls' is an Angular component, then verify that it is part of this module.

2. If 'pagination-controls' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.


28           <pagination-controls id="employees_listing_pagination" maxSize="5" directionLinks="true" (pageChange)="page = $event"></pagination-controls>



>SOLUTION

This kind of error message happened when using ngx-bootstrap and some other kind of issue promotes a compilation errors returning eventually this message.

The most common issues were:

1. Malformed module configuration.

2. Non-visible chars resulting in unexpected combinations.

3. Components not declared.


Details at:

Window
Node.js
Angular + ngx-bootstrap

angular or another framework/language: Mysterious compilation errors suddenly appeared after restarting app

 

>PROBLEM

Mysterious compilation errors suddenly appeared after restarting app.
It may happen with any framework/language.

Context:
Everything was done right and the modifications implemented were compiled successfully. Suddenly, after restarting the app, many error messages come from nowhere and they seem not compatible with the code written.




>SOLUTION

When the compilation goes mad, indicates that something outside the project, pertaining to the O.S. system has come to the scene.

Most common causes that occurred to me:
- HD issue
- Corrupted files.
- Non-visible chars (the worst scenario) resulting in unexpected combinations..

The first two causes may be easier to find out.
The third may turn your search into hell.

Through the editor used during the project implementation may not help, because the issue in this cases usually comes transparent to it. For instance, if you are using VS Code (excellent), it will be necessary to use another one to identify the issue, for instance the Notepad++, SciTE, or another one.

In the image below, check the red arrow.
The strange char comes out.

It doesn't help correcting in the editor. The issue may persist because it may have not visible chars during the fix, and they will be still there and may cause more issues.

The best thing to do is to create a new file and retype the code.
You may risk doing just this with just the defective line.
Better if you replace all the code from another source or manually.


This kind of issue happened to me three times and the first one drove me crazy.


>VERSIONING CONTROL  SIDE EFFECTS (Git, etc.)

The versioning is also affected.
The best approach, because it is faster and more effective, is:

1. Copy the current code to a temporary folder.
2. Checkout to a previous version — the most recent state that compiles successfully.
3. Replace the differences without copying, otherwise, you may contaminate the content again.

NOTE:
Non-visible chars produce issues to the compiler and also to any other software working with the files, and that is the case of the versioning control, spoiling the merges.

>ENV

Windows
Node.js
Angular 12 and higher.



Wednesday, July 20, 2022

angular: Error: node_modules/ngx-bootstrap/modal/bs-modal.service.d.ts:7:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

 


>PROBLEM

Angular compilation throws the following error:

Error: node_modules/ngx-bootstrap/modal/bs-modal.service.d.ts:7:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

This likely means that the library (ngx-bootstrap/modal) which declares BsModalService has not been processed correctly by ngcc, or is not compatible with Angular Ivy. Check if a newer version of the library is available, and update if so. Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy.


>SOLUTION

>BEFORE (WRONG)

imports: [

BsModalService,

],

providers: [

],


>AFTER (RIGHT)

imports: [

BsModalService,

],

providers: [

BsModalService,

],




>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


angular: Error: node_modules/ngx-bootstrap/datepicker/bs-datepicker.config.d.ts:8:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.

 

>PROBLEM

Angular compilation returns:

Error: node_modules/ngx-bootstrap/datepicker/bs-datepicker.config.d.ts:8:22 - error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class.


This likely means that the library (ngx-bootstrap/datepicker) which declares BsDatepickerConfig has not been processed correctly by ngcc, or is not compatible with Angular Ivy. 

Check if a newer version of the library is available, and update if so. 

Also consider checking with the library's authors to see if the library is expected to be compatible with Ivy. 



>SOLUTION


Edit app.module.ts and fix its configuration as follows:


>BEFORE (WRONG)

  imports: [

AlertConfig, 

BsDropdownConfig, 

BsDatepickerConfig

  ],

  providers: [],


>AFTER (RIGHT)

  imports: [

  ],

  providers: [AlertConfig, BsDropdownConfig, BsDatepickerConfig],



>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


Thursday, July 14, 2022

angular: ngForm: error NG8002: Can't bind to 'formControl' since it isn't a known property of 'input'.

 

>PROBLEM

After adding an implementation to bind using ngModel , for instance:

    <label for="example-ngModel">[(ngModel)]:</label>

    <input [(ngModel)]="currentItem.name" id="example-ngModel">


Running angular using ngModels, returns the error message:

error NG8002: Can't bind to 'ngModel' since it isn't a known property of 'input'
Can't bind to 'formGroup' since it isn't a known property of 'form'

Error: src/app/crud/crud-employee/crud-employee-update/crud-employee-update.component.html:2:9 - error NG8002: Can't bind to 'formGroup' since it isn't a known property of 'form'.

2   <form [formGroup]="updateForm" (ngSubmit)="saveToList(updateForm)">


For instance, implementing a simple example like this:




You get:




Another example:



>SOLUTION


@NgModule is a key concern in Angular.

This NG8002 error usually comes from the @NgModule misconfiguration (missing something).
For instance, a usual occurrence may happen with these scenarios:

1. A new module is created and not registered on app.module.ts.
or

2. A new component is created and not registered in its specific module.
or

3. The selector's module is not registered in the module.

The selector is that declared in the .ts file, for instance at:
@Component({
  selector: 'app-modal-list',

Referenced in the .html file comes like this:
<app-modal-list></app-modal-list>



There are a few things to be observed.


1. Requires modules setup.

Set the required modules in app.modules.ts. Example:


import { FormsModule, ReactiveFormsModule } from "@angular/forms";

...

@NgModule({

  declarations: [
        //...
   ],

  imports: [
//...
    FormsModule,
    ReactiveFormsModule,
  ],


*** IMPORTANT NOTE:

If you are using a page under its specific module, declare in that module too.

Example:

app
+--forms-lab
+-- forms1
--- forms-lab.module.ts


Edit forms-lab.module.ts and declare both modules referred to above.


2. Make sure that you have not overwritten the angular modules: 

It is something easy to happen, for instance, if you create a module called forms, as it is:


ng g m forms


This command will generate a FormsModule that overrides the angular's module.
This conflict causes the same issue.

If it happened, delete, and recreate it with another name.


3. Check if all components are declared in its modules.ts file.

Using the example above, it would be something like this in the forms-lab.module.ts file:

import { Forms1Component } from './forms1/forms1.component';
...
@NgModule({
  declarations: [
    Forms1Component,
  ],


4. Check if there isn't naming conflict.

Sometimes, the way the components are named may cause the issue.

Check the following image:




@MORE: 

https://stackoverflow.com/questions/43220348/cant-bind-to-formcontrol-since-it-isnt-a-known-property-of-input-angular


>ENV

Angular CLI: 13.2.2

Node: 16.13.1

Package Manager: npm 8.5.4

OS: win32 x64


eclipse: java: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder" or Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/impl/StaticLoggerBinder

  >PROBLEM Using Eclipse, you try to run a simple logging test using "org.slf4j.Logger" like the sample below: package Test; im...