Friday, December 29, 2017

Uncaught Error: Encountered undefined provider

Hi Guys,

Here is how you can fix the issue "Uncaught Error: Encountered undefined provider" . Have a look at the stack trace below.


compiler.js:485 

Uncaught Error: Encountered undefined provider! Usually this means you have a circular dependencies (might be caused by using 'barrel' index.ts files.
    at syntaxError (compiler.js:485)
    at eval (compiler.js:15725)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver._getProvidersMetadata (compiler.js:15710)
    at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (compiler.js:14994)
    at CompileMetadataResolver._getEntryComponentMetadata (compiler.js:15812)
    at eval (compiler.js:15293)
    at Array.map (<anonymous>)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15293)
    at JitCompiler._loadModules (compiler.js:34226)


To find out which part of the code is throwing  this error , first have a check in the component.ts file.
Check the value of provider attribute in the @Component decorator .



Invalid providers for "AppComponent" - only instances of Provider and Type are allowed

Hi Guys,

You might have faced the issue "Invalid providers for "AppComponent" - only instances of Provider and Type are allowed" .

The full stack trace is as below:

Uncaught Error: Invalid providers for "AppComponent" - only instances of Provider and Type are allowed, got: [?./user.service.ts?]
    at syntaxError (webpack-internal:///../../../compiler/esm5/compiler.js:706)
    at eval (webpack-internal:///../../../compiler/esm5/compiler.js:15963)
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver._getProvidersMetadata (webpack-internal:///../../../compiler/esm5/compiler.js:15931)
    at CompileMetadataResolver.getNonNormalizedDirectiveMetadata (webpack-internal:///../../../compiler/esm5/compiler.js:15215)
    at CompileMetadataResolver._getEntryComponentMetadata (webpack-internal:///../../../compiler/esm5/compiler.js:16033)
    at eval (webpack-internal:///../../../compiler/esm5/compiler.js:15514)
    at Array.map (<anonymous>)
    at CompileMetadataResolver.getNgModuleMetadata (webpack-internal:///../../../compiler/esm5/compiler.js:15514)
    at JitCompiler._loadModules (webpack-internal:///../../../compiler/esm5/compiler.js:34447)



To find the root cause of the issue first check the providers attribute of @Component decorator in the component.ts file.

If the value is anything other than a valid Typescript type you will get the above error.


Sunday, December 10, 2017

property binding in Angular 5

Hi Guys,

Let's understand what is property binding in angular 5.

We all know that an HTML element has various properties like id , name , value, etc. . Angular provides a way to bind to the property of HTML elements , called property binding .

There are multiple use cases that can be simplified using property binding like , if you have to change the value of a text field dynamically , or enable/disable a button. Let's see how can we do it.

First create an html file which will act as a component . Name this file as test.component.html , in this file have a text field . To bind a property we need to put the property in []. Here we are going to bind the value property , so I have placed value in square brackets . Since I am going to bind this property to a dynamic value , I will do so by assigning the property to a variable myValue.

<input type="text" [value]="myValue">

You need to define myValue in the component file . So , create a typescript file and name it as test.component.ts . The content of the file should be as below.

import { Component } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html'
})
export class TestComponent {
myValue="test";
}



Finally update your index.html as 
<app-test></app-test>
That's all , verify the code by refreshing the localhost:4200 in chrome browser . You will see the output as



Wednesday, December 6, 2017

node_modules appears empty, you may need to run 'npm install'

Hi Guys,


You might face the error node_modules appears empty, you may need to run 'npm install'  if you try to test an angular 2/4/5 application . 

node_modules appears empty, you may need to run 'npm install'
This error occurs when you use the command ng serve.
C:\projects\my-app> ng serve
Note that this command is used to start a server , serving the angular application .

The most common cause of this error is missing node_modules folder in the directory from which you have called ng serve.

To solve this take the following steps.

1. Check , if you have called ng serve from the correct location ? to serve the application you need to navigate to the project folder and then call ng serve .

2. If you are in correct folder , check if you have a folder named node_modules in it.If not your project is incomplete . Create a new application using ng new and replace the src folder of new app with src folder of your existing app.

C:\projects> ng new my-app-new
Copy the src folder in my-app to my-app-new
C:\projects> cd my-app-new
C:\projects\my-app-new> ng serve
3. If you have node_modules  folder available and in your app folder then it might be corrupted. To solve this create a new application using ng new and replace the src folder of new app with src folder of your existing app.


Important links
S O

Friday, November 24, 2017

The selector "app-root" did not match any elements

Hi Guys,

You might face this error when we try add a newly created component in Angular 2/4/5.

Let's have a look at the complete stack trace:


ERROR Error: The selector "app-root" did not match any elements
    at DefaultDomRenderer2.selectRootElement (platform-browser.js:2791)
    at DebugRenderer2.selectRootElement (core.js:14962)
    at createElement (core.js:10279)
    at createViewNodes (core.js:13409)
    at createRootView (core.js:13338)
    at callWithDebugContext (core.js:14739)
    at Object.debugCreateRootView [as createRootView] (core.js:14040)
    at ComponentFactory_.create (core.js:10959)
    at ComponentFactoryBoundToModule.create (core.js:3919)
    at ApplicationRef.bootstrap (core.js:5730)
This would come if you have placed the newly created component selector in the root component .

Let's look at the working code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyFirstApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>

</body>
</html>

Remember this code is working fine , now lets see the erroneous code.
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>MyFirstApp</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-mycomponent></app-mycomponent>
</body>
</html>

So the error is due to the app-mycomponent which is not present. So , how to fix this error ? You need to add the new component in the app component , not in the index.html.
<app-mycomponent></app-mycomponent>
<div style="text-align:center">
  <h1>
    Welcome  {{title}}!
  </h1>
  <img width="300" src="xyz">
</div>
Now, we see the output as:
mycomponent works!

Refer to similar answers in Stack Overflow site.

Sunday, November 12, 2017

Lexical scoping in JavaScript

If you are familiar with JavaScript you might be aware that JavaScript uses lexical scoping . Now what really is lexical scoping and how is it different than other languages like java ?
What is actually a scope ? A scope is the visibility and accessibility of the variable . So when a JavaScript function tries to refer to a variable , the scope of the variable comes into play . Now lexical scoping means the variable will be accessible to the function only if it was in scope when it was defined.
The key point is variable does have different scopes while definition and execution.

Monday, June 19, 2017

Angular Js


Angular js is mainly used to build single page application . It is based on MVC architecture.
  1. model The form fields act as model , we need to use ng-model attribute to specify the model name.
  2. view The HTML page is the view , which is being displayed to the user
  3. controller We can create a JavaScript function which will be the controller


There are 3 most important components of angular js.
  1. application
  2. controller
  3. service

Common Errors:
Error: [$injector:unpr] Unknown provider: myServiceProvider
 When you see this error you need to check if have my service defined for your application.
Click on the buttons inside the tabbed menu:
angular.module("home",home); var home=function (){ }

Wednesday, June 14, 2017

Gradle

Hi Guys,
I have started learning cradle and this blog will help you getting familiar with gradle.

Gradle is a build tool where in you can have a project comprising of tasks.
Your build related details will be mentioned in build.gradle file .
By default the folder name is the rootProject  name if you want to configure it change in settings.gradle file.
End.

rootProject=org.myProject

The project inside the root project will be the subProject .
You can specify the dependency in build.gradle as

If you want to use a repository you can use the repository to define it.
repository {
maven{
url "http://testRepo.org"
}
}

Saturday, June 10, 2017

Wildfly 10


Hi Guys, I have started using Wildfly 10 sometime back and here is my guide on how to successfully configure wildfly 10. First of all download it from site.
http://wildfly.org/downloads/
Now, check if you have JAVA in the environment variables .Make sure it is pointed to Java 8.
echo %JAVA%
C:\Program Files\Java\jdk1.8.0_91\jre\bin\java.exe
open command prompt ,goto Wildfly\bin and type the following command
standalone.bat -Djboss.home.dir=\softwares\wildfly_10\wildfly-10.1.0.Final -Djboss.server.config.dir=\softwares\wildfly_10\wildfly-10.1.0.Final\standalone\configuration
If you are using powershell type the following command
.\standalone.bat -Djboss.home.dir=\softwares\wildfly_10\wildfly-10.1.0.Final -Djboss.server.config.dir=\softwares\wildfly_10\wildfly-10.1.0.Final\standalone\configuration
Note : you need to change the path to the path where wildfly installation is.
If you face the following error while starting

Unable to read the logging configuration from 'file:F:\shahbaz\softwares\wildfly_10\wildfly-10.1.0.Final\standalone/logging.properties' (java.io.FileNotFoundException: F:\shahbaz\softwares\wildfly_10\wildfly-10.1.0.Final\standalone\logging.properties (The system cannot find the file specified))
change the -Djboss.server.config.dir to the proper config path.
To find out which port number the http server is running , open standalone.xml and check the following attribute.
<socket-binding name="http" port="${jboss.http.port:8090}"/>
Once you start wildfly hit the following URL http://localhost:8090

Click on admin console and then you might see the following screen.
Run add-user.bat and set the username and password for application as well as management realm

Goto the home page after adding the users

Done with the server configuration . Now you can start playing with the server. So,Lets create a simple application and deploy .We will have a index page which will display a message on load.
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <display-name>My App </display-name>
</web-app>
<html>
<body>
Hi ,
This is my app.
</body>
</html>
Now build the war file which will be deployed . Type the following command in the console.
"C:\Program Files\Java\jdk1.8.0_91\bin\jar" -cvf myApp.war *
Once you have the war file ready you can deploy it using wildfly admin console.Follow the steps to deploy a war file.
Deploy the selected war file
Lets create servlet jsp project and deploy it.
package org.myApp;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.myApp.TempConvertor;

public class Converter extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException,ServletException{
try{
String farenhiet=request.getParameter("farenhiet");
if(farenhiet != null ){
String celcius=TempConvertor.farenhietToCelcius(Float.parseFloat(farenhiet));
request.setAttribute("celcius",celcius);
RequestDispatcher requestDispatcher=request.getRequestDispatcher("/conv/result.jsp");
requestDispatcher.forward(request,response);
}
}catch(Exception e){
e.printStackTrace();
RequestDispatcher requestDispatcher=request.getRequestDispatcher("/conv/error.jsp");
requestDispatcher.forward(request,response);
}

}
public void doPost(HttpServletRequest request,HttpServletResponse response){
}
}
public class TempConvertor
{
public static String farenhietToCelcius(float farenhiet){
float celcius =(farenhiet -32 )*5/9;
return String.valueOf(celcius);
}
}
Your code here.
you can start it using eclipse, if you face the following error you need to change the Java installations.
Exception in thread "main" java.lang.UnsupportedClassVersionError: org/jboss/modules/Main : Unsupported major.minor version 52.0 at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:800) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:449) at java.net.URLClassLoader.access$100(URLClassLoader.java:71) at java.net.URLClassLoader$1.run(URLClassLoader.java:361) at java.net.URLClassLoader$1.run(URLClassLoader.java:355) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:354) at java.lang.ClassLoader.loadClass(ClassLoader.java:425) at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308) at java.lang.ClassLoader.loadClass(ClassLoader.java:358) at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:482)

Wednesday, May 31, 2017

org.dom4j.DocumentFactory cannot be cast to org.dom4j.DocumentFactory


Hi Guys , You might face this exception when using wildfly 10 with hibernate. This exception is linked with the classloader since the same class is loaded by two different class loaders. You can the following solution

 <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.1.0.Final</version>
            <scope>provided</scope>
        </dependency>

Tuesday, May 30, 2017

Uncaught TypeError: Converting circular structure to JSON


Hi Guys
You will see this error on converting a json to string using JSON.stringify .
Full stacktrace is like
Uncaught TypeError: Converting circular structure to JSON
at JSON.stringify (<anonymous>)
at <anonymous>:1:6
Below is the sample code that can cause this exception. You can see that we have created an element object in line number 1 and in line number 2 we are assigning the same element object to the node attribute of the element. This is having a circular reference . Hence you will experience the exception.
var element={"node":{}};
element.node=element;
JSON.stringify(element);
You might also face the error for the following block of code :
var element={"node":{}};
element.node=element;
angular.toJson(element);
Uncaught is added since the exception is not catched by a catch block . According to MSDN, A TypeError is thrown when an operand or argument passed to a function is incompatible with the type expected by that operator or function .So here it is explicitly thrown by stringify method.It is also possible that a common utility method is throwing this exception. Check if your code has the following statement .
new TypeError("Converting circular structure to JSON");

Sunday, May 28, 2017

The integer literal does not conform to the expected type String

Hi Guys ,

There are multiple reasons for getting this error .

1. If you have a class for which you are trying to create an object and you have missed to specify any of the class variables while creating the object, you might face the exception like :
The boolean literal does not conform to the expected type String .

Take a look at the program below :

class Student(
    val name: String,
    var age: Int
)

fun main(args: Array<String>) {
    val student= Student(1)
    println(student.name)
    println(student.age)
}


If you try to run the above program you might face an error like .
Click here to run this test.



Friday, May 26, 2017

Java vs. Kotlin

Hi Guys,
There are a lot of difference in how a java program and kotlin program.
1. package
2.import
Java program by default imports java.lang.* package.

Thursday, May 25, 2017

Kotlin Hello World

Let's check out a simple kotlin program to print hello world to the console.
Let's check out a simple kotlin program to print hello world to the console.
Here's the program to print hello world to the console.

package demo
fun main(args : Array<String>){
println("hello world")
}
If you run the above program you will get the following output.
hello world
Now let's go the program and try to understand the way it works.
Its way more simple for developers with java background,and I strongly recommend get hands on java experience to get expertise on kotlin.
The program starts with package deceleration , which is optional. If you do not declare the package the file goes to the default package . You have few restrictions for the package name . You cannot name package as java , this is same for the programs written in java language. But kotlin is different from java , you can actually name your package as kotlin .

Tuesday, April 4, 2017

Sorting Algorithms

Hi Guys,

This blog is about the various algorithm used to sort a collection .
Let's have a look into each of these available algorithms.

1. Selection Sort
This is the easiest logic to sort a group of objects .You need to pick the smallest element and swap it with the element at first position. Now you have the first element sorted . Just repeat the same step for the remaining elements and your objects will be sorted . Easy.

2.Bubble Sort
Logic  In an array of N number , start with comparing the first two numbers . Move the lowest element up. Now take the next two numbers , compare and move the lowest of them up. Similarly proceed till the last element . Iteration one is over and we have the largest element at the bottom. Now, make N-1 iterations each time reducing the array by excluding the last element.

3.Insertion Sort
Logic  In an array of N numbers take first two numbers and sort it. This will be the sorted subset . Now, take the next number and compare it with the sorted subset and position it so that..

4.Heap Sort
Logic : Take the array of N numbers and arrange it in form of Complete Binary Tree .After that take the first element and swap it with the element at last index. Form completely Binary tree with the elements excluding the one at the first index. Continue this process until all elements are sorted .

ec2-user@ec2 Permission denied