Lanka Developers Community

    Lanka Developers

    • Register
    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • Shop
    1. Home
    2. Udith Indrakantha
    • Profile
    • Following 1
    • Followers 1
    • Topics 10
    • Posts 19
    • Best 14
    • Controversial 0
    • Groups 4

    Udith Gayan Indrakantha

    @Udith Indrakantha

    Web Development

    An IT Undergraduate of University of Moratuwa, with good experience with Angular 7+ , Spring boot and MySQL and working on .NET Core recently. You can find me on my portfolio site at https://udith.netlify.com

    26
    Reputation
    460
    Profile views
    19
    Posts
    1
    Followers
    1
    Following
    Joined Last Online
    Website udith.netlify.com Location Colombo Age 27

    Udith Indrakantha Unfollow Follow
    Ethical Hacking & Pen-Testing Mobile Development Web Development Google API

    Best posts made by Udith Indrakantha

    • Upload Images and save them in a database( Angular 8 + Spring boot + Mysql )

      0_1563374901877_27c7393e-d31b-4342-8009-59ef72023d9b-image.png
      This article is all about uploading an image through your angular project , sending it into the backend and saving it in a database.
      Not only that, the way how to query the database and viewing back the image in the frontend is also explained here.
      [As this article is written for explaining the simple mechanism of uploading an image, web page decorations are not done, only the relevant parts are designed for explanation.]

      • The frontend used is Angular 8.

      • The backend use is Spring boot

      • The database used is Mysql

      Please note that,

      Some basic knowledge about angular ,spring boot and mysql is essential.( because the way of project creating in those frameworks is not discussed as it makes this article lengthier.)
      As IDEs , VS code is used for Angular and IntelliJ IDE is used for Spring boot.

      1.0 Frontend
      First , create an angular project . ( See how )
      We need HttpClientModule for dealing with the backend. So, We
      have to import that module to the project.
      Go to src/app/app.module.ts

      • Add the following code lines in app.module.ts file as in the image
        below.

           import { HttpClientModule } from '@angular/common/http';
        

      0_1563374947508_320b5d8c-f59e-4d12-b1d4-18d2d7bb9b9d-image.png

        and, declare the module in imports array.
      
      • Go to app.component.html file and add the following code.
      <h3>Image Uploading Module</h3>
      <div>
      <input type="file" (change)="onFileChanged($event)">
      <img [src]="imgURL" height="200" *ngIf="imgURL">
      </div>
      
      <!-- upload image  -->
      
      <input type="button" (click)="onUpload()" value="upload">
      <hr />
      Received Image:
      {{ receivedImageData['pic'] | json}}
      
      <img [src]="convertedImage" >
      

      The view will be like this.
      0_1563375202159_049eedae-2833-41e0-b55a-421b67d2bf75-image.png
      In this code,
      (change)="onFileChanged($event)
      is used to listen to any file choosing event and trigger the onFileChange(event) method in .ts file.

      imgURL, convertedImage are properties in the .ts file.

      *Go to src/app/app.component.html file and write the following code snippets in it.

      0_1563375278047_63d39039-4011-4fea-98fe-769a81d45a41-image.png

      Import HttpClient class from '@angular/common/http' .
      And, inject it via the constructor of the class as in the image.

      0_1563375341351_b2712168-0322-4548-90ed-d459b6ec6a9f-image.png

      Write and complete your app.component.ts file as shown in the images.

      As the backend is running on local port 8080, posting url is also given as preferred.
      We send the image to the backend as a FormData,so that the backend can retrieve it as a multipart file.
      By,subscribing to the post method ,we have retrieved the returned image data by the backend and assigned them to the properties which are used to render in the view.

      ***You may find the code snippets here.

      app.component.ts
      app.component.html
      app.module.ts


      2.0 Spring Boot Backend

      Now,let's move to the backend part.

      0_1563375391917_bd2de260-f0c5-4914-8086-d35b77528bdf-image.png

      First , create a maven project through Spring Initializer website.

      1. Give a group name to the project
      2. Give a artifact nae to the project
        3.Add three dependencies given[Spring Web Starter, Spring Data JPA, MySQL Driver, Lombok]
      3. Genereate the project and download the zipped file of the project.

      Extract the zipped file .
      Open your IDE(Here,IntelliJ IDE is used).
      Open the extracted project by selecting the pom.xml file, through the IDE.

      This is the file structure in the project I created.

      A controller class as TestController.java [Get code]
      A model class as ImageModel.java [Get Code]
      A repository interface as ImageRepository.java [Get code]

      **ImageModel.java
      0_1563375444427_a91f492b-61be-4146-bab0-58f0bf51ba3b-image.png

      **ImageRepository.java
      0_1563375454867_09610e67-bedb-4ac4-bee1-9daf22d8dfec-image.png

      **TestController.java
      0_1563375462787_5e491490-c47c-4a19-b873-7c4f34ea88ab-image.png

      Here , in the controller file, image is captured in MulipartFile format . From the frontend, the image data is sent as a form data by appending the data to the request parameter named "myFile" .

      *You can read about MultipartFile interface here.

      *You need to edit the application.properties file , to connect to the mysql database according to your PC settings. (Read how)


      Enjoy!

      posted in Web Development
      Udith Indrakantha
      Udith Indrakantha
    • The way how to solve the issue related with Infinite Recursive fetching of data from relationships between Entity classes (Spring Boot JPA Hibernate)

      This article is all about how to avoid recursive fetching of data from relationships designed in Database. I’ll explain everything with an example so that you will all understand clearly. Here I’m working with Intellij IDEA and MySQL databases.

      1.1 Brief about the tables and the relationship used
      Here in my example, I have created two Entity classes and they are connected with a OnetoMany relationship.
      0_1566052237730_ba5448b6-b4a2-46cf-8311-07cf97a5ee95-image.png

      One student can have more than one email and this is the scenario taken. StudentId in ContactModel refers to the id field in StudentModel and This is a OnetoMany relationship. StudentModel is the “One” side and ContactModel is the “Many” side.

      1.2 The classes before resolving the error

      How the Entity classes are designed in Spring boot is given below in images.

      StudentModel.java
      0_1566052271116_bac17b36-a2d4-48eb-94b7-9fb6a0fd11fd-image.png

      ContactModel.java
      0_1566052291862_c7597d82-ec12-43c0-a8b8-b59afb55ce64-image.png

      1.3 Issue looks like this

      Some data is included in the database and I have run some queries to fetch the data from the contact table.This is how it appears after fetching data,
      0_1566052336520_d615763e-e3c2-4d03-8d66-3bf6d4f4ef0e-image.png

      This is an infinite recursion. This is the issue after designing the entity classes as above.

      1.4 How to solve

      There are many annotations such as @JsonManagedReference, @JsonBackReference, @JsonIgnore etc, to avoid this infinite recursion.But, when used them creates some errors in fetching and inserting data from and to the entities.

      After searching a lot in internet and trying a lot, I came across the best way to solve this. It’s very simple.I used only to one annotation in the “One” side of the relationship.
      @JsonIgnoreProperties

      This annotation ignores the fields from Jsonification. You need to use this in class level as below,
      0_1566052423734_1d78cb76-5c35-453f-a7bf-65462ff24f19-image.png

      Actually when fetching data from StudentModel, you don’t need to fetch data from the field “contact”. So, I have asked to ignore that field . This annotation take the ignoring fields in a String array.So you need to give the field-names in an String array as above.

      [ Note: You need to ignore two more fields, hibernateLazyInitializer, handler, otherwise it gives an error message like this when fetching data

        “No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]>com.project.inventoryManagement.Models.ContactModel[\”student\”>com.project.inventoryManagement.Models.StudentModel$HibernateProxy$bYhYXmwK[\”hi bernateLazyInitializer\”])" 
      

      ]

      Happy Coding without bugs!
      Thank you.

      posted in Back-End Development
      Udith Indrakantha
      Udith Indrakantha
    • පහසුන්වෙන්ම ඔබෙ Angular Application එක නොමිලෙ Netlify server එකෙ deploy කර ගමු. (Simple English)

      alt text
      This article is all about how you can deploy your Angular application securely on Netlify server . This is a free place for you to deploy your application.

      First you need to have a Netlify Accout (Create if not) and a GitHub repo of your project.
      ( I assume that you already have a github repo of your Angular project.)
      I teach you the way with a sample project I created just for fun.

      Let’s begin

      Configuring Netlify

      1. First go to your Netlify account. There you can see a button “New site from Git” (Fig 1.1). Click on it.

      0_1573148079548_0608d448-a21c-4063-9249-efabdf7b6631-image.png
      Fig 1.1

      2. Then select the repository site. I here select GitHub.(You can select the site where your project is.)
      When selected, you are redirected to authorize the access from netlify and there you can select the repository that you need to deploy.

      3. Select the repository again and go to step 3. (Fig 1.2)
      alt text
      Fig 1.2

      Here in this page, you have to fill some information. (you can change these later too)

      You can specify which branch needs to be deployed.
      For Build Command , give ng build — prod
      For Publish directory , give dist/<your project name>
      (You can find your correct project name at the end of angular.json file of your project. Ex: dist/my-blogger-web as in Fig(1.3))

      alt text
      Fig 1.3

      If all set. Click the button “Deploy site”. You will be directed to something like this in Fig 1.4.

      alt text
      Fig 1.4

      4. Next, go to Settings tab and copy the API ID and save it somewhere because we are gonna need it later. (Fig 1.5)
      [Here, you can change your site name also.]

      alt text
      Fig 1.5

      5. We need to find a Personal Access Token key .
      Click on Avatar picture of your profile on right top corner, select User settings,
      Select Applications from the menu,
      Under Personal access tokens, click New access token button .
      (Fig 1.6, Fig 1.7)

      alt text
      Fig 1.6
      alt text
      Fig 1.7

      Give a simple description for the token so that you can identify why this token is used, when you check tokens sometimes later.

      Click the button to Generate a token. Copy and paste that token somewhere to use it later. Then click Done! at last.

      Configuration in Angular project

      6. Open the command window inside your Angular project’s root folder.

      and run this command
      ng add @netlify-builder/deploy

      **There you are asked to enter API ID: you can enter it from where you copied and saved it earlier.
      ** You are asked next to enter personal Acccess token which you generated earlier . Please, do not enter it here.Just press enter and skip it.( Because these details are entered in your angular.json file which can be tracked in your github repo easily so that outsider can use your API ID and access token to get access to your site. see Fig 1.8 )

      alt text
      Fig 1.8

      7. Next you have to set up the access token key as an environment variable of your computer.

      Right click on This PC icon on desktop of you computer ==> Properties ==> Advanced system settings ==> Advanced tab ==>Environment Variables ==> User Variables

      Under User variables , you have to enter a new variable, Variable Name as NETLIFY_TOKEN and Variable value as the access token key generated earlier and saved for later use by you. see Fig 1.9

      alt text
      Fig 1.9

      9. Next you have to run
      ng run <your project name>:deploy

      Plz, give your project name when running the above command.(See ,no space when typing the colon : )
      Ex: ng run my-blogger-web:deploy

      [For Angular vCLI 8.3.0 and above, just run ng deploy instead]

      This creates a folder dist/<Your project name> which you gave as the Publish directory for netlify site.

      10. Next part is, open your .gitignore file of your project and delete the line with /dist to track dist folder to be pushed to gitHub.

      At last commit and push.

      Here you go, go to your netlify site, and Click Trigger Deploy button to deploy. You can change ‘deploy settings’ there if you want.

      alt text

      All done!

      Your site is available at https://<your site name>.netlify.com

      ex: https://udithdemo.netlify.com

      Thank you.

      posted in Front-End Development
      Udith Indrakantha
      Udith Indrakantha
    • All about .replaceAll() in Java

      alt text
      java.lang.String class brings you a very powerful method to do replacements within a string.

      This method allows you to target specific substrings using regular expression ,so that you can even remove and replace any pattern within a string.

      Mainly, this method can

           * replace a given substring found any where in the string
           * replace a given character found any where in the string
           * replace a given reg expression found any where in the string
      

      Even though there are separate methods like replace(char old, char new), replace(charSequence old, charSequence new) to do above functions, this replaceAll() method acts as a versatile method for all those functions.

      This is how this method is defined in String class,

      String replaceAll(String regex , String new)

      As you can see , this method returns a new string. Actually, a string is immutable in JAVA , so it is not possible to alter a string. This method returns a new string instead.You need to catch it with a string variable.

      **This method accepts to two parameters which must be in type String. So , when you need to replace a character, you have to use a double quotation for the characters (instead of single quotations which are used for representing char).

      Examples:

      alt text
      Character replacement

      alt text
      String replacement

      alt text
      Regex replacement

      Keep in Touch!!!

      posted in Blogs
      Udith Indrakantha
      Udith Indrakantha
    • Say “bye bye!!!”​ to Annoying Getters/Setters & Shorten your Java Code with `​ lombok `

      0_1561548435753_Capture.PNG
      Still, there are things that a Java programmer has to do over and over again just to get the code complete from language/syntax point-of-view rather than spending time on business logic, the actual task at hand. Having to write or even auto-generate Getters ,Setters, custom Constructors and custom toString method in POJOs is one such issue. As a solution for this cumbersome problem, Project Lombok has quite elegantly addressed this issue.

      First, just need to add the lombok dependency to your project and then use the available annotations appropriately. In your Spring boot project, go to pom.xml file and add the below dependency within the tags <dependencies>...</dependencies>

      <dependency>
         <groupId>org.projectlombok</groupId>
         <artifactId>lombok</artifactId>
         <optional>true</optional>
         <version>1.18.8</version>
      </dependency>
      

      Check for the most recent available version here.

      For the latest lombok.jar file

      1.0 Annotations Available for Use

      Lombok project provides us with several annotations to avoid boilerplate codes in our entity class. Given below is a list of the available annotations and some very essential set of the annotations will be discussed briefly with examples.

              *Annotation List*
      

      @Getter @Setter @Builder @NonNull

      @Data @ToString @Getter(lazy=true) @AllArgsConstructor

      @NonNull @EqualsAndHashCode

      @NoArgsConstructor @Value @Log @Synchronized

      @RequiredArgsConstructor @SneakyThrows @Cleanup

      @ToString.Exclude @ToString.Include
      @EqualsAndHashCode.Exclude

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

      @Getter/@Setter

      When you annotate your Entity class with @Getter and @Setter , it will generate getter methods and setter methods for all the fields in your class.

      Or, you can place these two annotations separately before the necessary fields (Not before the class name) ,when you don't need getting and setting methods for all the fields available.

      0_1561548586703_757cfdd1-785e-4990-9ff5-664bb9f11380-image.png


      @NoArgsConstructor

      When you place this constructor before the class name, this will create a constructor without any arguments in it.(an empty constructor)

      0_1561548645658_02b31c37-bd7a-42a1-88c5-b0faef078895-image.png

      This annotation is useful primarily in combination with either @Data or one of the other constructor generating annotations.


      @AllArgsConstructor

      This annotation when place before the class name, generates a constructor taking all the fields as arguments in it.

      0_1561548696953_d2f49d31-ba1c-47ec-b674-dd73f60f4dc9-image.png


      @NonNull

      You can use @NonNull on the parameter of a method or constructor to have lombok generate a null-check statement for you.(See below code examples)

      ** Using @NonNull annotation **

      package com.udith.articles.lombokDemo.entities;
      
      import com.udith.articles.lombokDemo.entities.Person;
      import java.io.Serializable;
      
      import lombok.NonNull;
      
      public class Student extends Serializable {
        private String name;
        
        public Student(@NonNull Person person) {
          super("Hello");
          this.name = person.getName();
        }
      }
      

      ** When lombok generates the code for the above snippet, the code looks like this **

      package com.udith.articles.lombokDemo.entities;
      
      import com.udith.articles.lombokDemo.entities.Person;
      import java.io.Serializable;
      
      import lombok.NonNull;
      
      
      public class Student extends Serializable {
        private String name;
        
        public Student(@NonNull Person person) {
          super("Hello");
      
         if (person == null) {
            throw new NullPointerException("person is marked @NonNull but is null");
          }
      
      
          this.name = person.getName();
        }
      
      }
      

      Further, you can annotate the fields in an entity class so that those marked fields will be used for creating constructor with the annotations @Data and @RequiredArgsConstructor .


      @RequiredArgsConstructor

      @RequiredArgsConstructor generates a constructor with parameters for the fields that requires special handling. All non-initialized final fields get a parameter, as well as any fields that are marked as @NonNull that aren't initialized where they are declared.

      See the code snippet below. The commented part shows the lombok generated constructor.
      0_1561549118069_4f5c9b40-79ac-45fd-aace-200c2356291c-image.png

      When this annotation generates the constructor, the parameters included are ordered in the way the corresponding fields are ordered.


      @ToString

      This is also a very useful annotation in debugging etc. Any class definition may be annotated with @ToString to let lombok generate an implementation of the toString() method. By default, it'll print your class name, along with each field, in order, separated by commas.

      0_1561549165225_1c8cfb91-ea12-462d-9aaf-6b7cff34a46c-image.png
      @ToString annotation by default implies @ToString(includeFieldNames = true) .

      But, by changing its above property to false, a string without fields' names can be returned.

      Further, we can customize the fields that we need to exclude and include to the ToString() method. This can be achieved in two ways.

      1) Use of @ToString.Exclude annotation with @ToString annotation.

      Just add @ToString.Exclude annotation before the fields that you need to exclude from the returned string. (See the example right).
      0_1561549307286_cec3a8e9-910e-4305-ab77-2f9e9cf52e6a-image.png

      2) Use of @ToString.Include annotation with @ToString(onlyExplicitlyIncluded = true) annotation.

      After adding @ToString(onlyExplicitlyIncluded = true) before the class, add @ToString.Include before the required fields. Then, only those required fields will be included in the returned string.

      0_1561549372258_a759b4a8-559b-47d2-badf-b84ae31d080b-image.png


      @EqualsAndHashCode

      When placed before a class declaration , this annotation implements public boolean equals(Object obj){} method for all the fields and public int hashCode(){} method for all the fields.


      You can exclude any field that needn't to be inserted in the generated two methods, simply by placing @EqualsAndHashCode.Exclude annotation over the field you need to exclude.
      0_1561550156747_3d028d4c-8a7d-48b6-8752-e968a878890d-image.png

        [ Or, you can explicitly include the required fields for these two methods by replacing @EqualsAndHashCode with ** @EqualsAndHashCode(onlyExplicitlyIncluded = true) ** before the class declaration and then placing @EqualsAndHashCode.Include over the required fields. ]
      

      @Data

      This is a very convenient shortcut key that bundles the features of @ToString, @EqualsAndHashCode, @Getter / @Setter and @RequiredArgsConstructor together.

      package com.udith.lombokdemo.entities;
      
      
      import java.io.Serializable;
      import java.util.Date;
      import java.util.Objects;
      import javax.persistence.Entity;
      import javax.persistence.Id;
      
      
      import lombok.Data;
      
      
      @Entity
      @Data
      public class Student implements Serializable {
          
          @Id
          private long id;     
          private int age;
          private Date birthday;
      
      }
      

      ===================*******************************============================

      Above explained are only some frequently used annotations, but you can handle them smoother as you require with lombok. You can find more features here.



      By,
      Udith Indrakantha,
      Author of https://webtechmora.blogspot.com

      posted in Back-End Development
      Udith Indrakantha
      Udith Indrakantha
    • RE: පහසුන්වෙන්ම ඔබෙ Angular Application එක නොමිලෙ Netlify server එකෙ deploy කර ගමු. (Simple English)

      @root Thanks bro. I'll upload the article on hosting on heroku soon. I just selected Netlify as first one because I just like that word "Netlify" more than "heroku". By the way, if you find any mistakes in my article, plz don't hesitate to let me know.

      posted in Front-End Development
      Udith Indrakantha
      Udith Indrakantha
    • Need Support for the Survey from Software Engineers

      මේ community එකෙ ඉන්න software Engineersලාගෙන් මගෙ final year research ප්‍රොජෙක්ට් එකට පොඩි උදව්වක් ඕනි.

      මන් රිසච් ප්‍රොජෙක්ට් එකක් කරනවා code comments' quality rating system එකක් හදන්න. ඒකට ඔයාලා කෝඩ් කරද්දි comments කරන ස්ටයිල්ස් ගැන දැන ගන්න ඕනි. මෙකෙදි ඔයාලාගෙ පොඩි විස්තර ටිකක් අරන් , ඊට පස්සෙ තියෙන්නෙ 1-5ට රේට් එකක් තෝරන්න.
      උපරිම විනඩි 5ක් විතර යාවි, පුලුවන්නම් මේක ඔයාලගෙ ටයිම් එකෙන් පොඩි වෙලාවක් අරන් පුරවන්නකො.

      https://forms.gle/tbGQtjrjqbohurkF6

      මේ වෙලාවෙ හැටියට මේක ලොකු උදව්වක් මට. ඔයලට ගොඩක් ස්තූතියි.
      මොනා හරිම යෝජනාවක් , චෝදනාවක් තියේ නම් කරුණාකරලා ඔනිම වෙලාවක මට ඊ-මේ එකක් දාන්න.
      උදිත් ඉන්ද්‍රකාන්ත - [email protected]

      posted in Comments & Feedback
      Udith Indrakantha
      Udith Indrakantha
    • Fixing 401 Error with CORS Preflights (with Spring boot)

      alt text
      When the web application runs on a different domain and the server runs on another domain, we have to deal with cross origin requests. But, if we don’t know the mechanism of cross origin resource sharing (CORS), we will end up with errors like 401.

      Error in brief

      My Angular web application runs on port 4200, and my spring boot application runs on server on port 8080. I could not enable CORS in my backend, so, I got an error when sending a request from my application like this.

      alt text

      Reason
      My pre-flight request is not responded with status OK(200).

      Solution

      I enabled CORS in my backend. To do this, there are several methods. Here in my post, I have shown the easiest way to do that. But, if you are interest in knowing other ways, click me )

      By using Web Security in Spring Boot,

      You have to create a web security configuration class. I hope everybody creates that class for backend authentication purposes.

      If you have already created that class, inside configure( HttpSecurity httpSecurity ) method ,add this line httpSecurity.cors();
      alt text

      It’s that simple !!!
      Originally published at https://webtechmora.blogspot.com.

      posted in Back-End Development
      Udith Indrakantha
      Udith Indrakantha
    • Send Emails without a server-side code with Angular

      alt text
      Without any server-side code hosted on a server, you can send emails through your Angular application with smtpJS, a client-side Javascript library.

      First you need to download this library and include it into the necessary component of the Angular Application.
      Click here to download the library file.
      (If any error in download, go to smtpJS.com , where you can directly download or get the CDN link)

      Next , put this downloaded js file into the assets folder found in src directory of the project.

      Next we have to get the help of an email service provider to send the email. I here use Elastic Email site for this. First go to the Elastic Email site to create an account. Just complete the sign up process, it’s that simple.

      After logging into the site, go to Start — → Connect To SMTP API .

      alt text

      Next, you can see a button to create new credentials. Create a new credentials following the simple steps. The system will generate a password for you. Copy that password and save it somewhere before you close that popup model.

      Finally you’ll see something like this.

      alt text

      Here, your user name and password (You saved it earlier) can be seen .These details are used to access this.

      Coding part

      Go to your angular project’s relevant component from which an email must be sent.

      1. Import the smtp.js file from assets folder to the component by typing
        import ‘./../../../assets/smtp.js’;             <! — path might change — >
        declare let Email : any;

      2. Write the code to send the email with the user-inputs within onSubmit() method as below,

      import { Component, OnInit } from '@angular/core';
      import { ProfileService } from '../profile.service';
      import { Model } from './contact-form';
      import { NgForm } from '@angular/forms';
      import  './../../../assets/js/smtp.js '; <! — file path may change →
      declare let Email: any;
      
      @Component({ selector: ‘app-contact’,
       templateUrl: ‘./contact.component.html’,
       styleUrls: [‘./contact.component.scss’]})
      
      export class ContactComponent implements OnInit {
      
      model: Model = new Model();
      
      constructor( private profile: ProfileService) { }
      
      ngOnInit() {
      }
      
      onSubmit(f: NgForm) {
      
      Email.send({
                    Host : ‘smtp.elasticemail.com’,
                   Username : ‘[email protected]’, 
                   Password : ‘**************************’,          //Enter your password here
                   To : ‘[email protected]’,
                   From : `[email protected]`,
                   Subject : this.model.subject,
                  Body : `
                         <i>This is sent as a feedback from my resume page.</i> <br/>
                         <b>Name: 
                        </b>${this.model.name} <br />
                         <b>Email: </b>${this.model.email}<br />
                        <b>Subject: 
                        </b>${this.model.subject}<br />
                        <b>Message:</b> <br /> 
                        ${this.model.message} <br> 
                        <br> <b>~End of Message.~</b> `
      }).then( 
                   message => {alert(message); f.resetForm(); } 
                   );
          }
      }
      

      Here , within Email.send(….); method, you can give the elastic mail registered email as the username ,
      and earlier saved password for the password field.
      From: email should be equal to the elastic mail’s registered email and you can set the receiver’s email under To field.

      Other fields can be taken from your form created .

      That’s it.

      Original Post: https://medium.com/@udith.indrakantha/send-emails-without-a-server-side-code-with-angular-e227c3e62dbd

      posted in Front-End Development
      Udith Indrakantha
      Udith Indrakantha
    • Generate Word Documents from Templates Easily Using Vue.JS with TypeScript

      32099fab-0e7e-4ca4-9950-4af807bdddd1-image.png

      Introduction

      In one of my Vue projects, I needed to generate word documents with different templates. I did a small R&D and came across several libraries and APIs to achieve this. All of them were not free and we have to buy a subscription which is very expensive for me. The available free libraries used an approach where we have to design the template with HTML first and then render them as a word document. This approach did not fit my need as there were many templates and they could frequently change as per the client’s need.

      Finally, I came across a great library ( which was the only library available on the Internet) to generate word documents from a given template that includes tags that can be replaced with contemporary data when generating the report. It was a JavaScript library but my Vue project was in Typescript.

      In this article, I am going to explain how to implement this feature easily with Vue.JS project in TypeScript. If you are new to Vue with TypeScript, please follow this article explaining how to create a new Vue.JS project in TypeScript. The others can proceed.

      Installing necessary libraries

      For generating the word document we use docxtemplater library by Edgar Hipp. First of all, run these commands in the console inside your project folder.

      npm install --save docxtemplater
      npm install --save jszip@2
      npm install --save jszip-utils
      npm install --save file-saver
      

      In addition to the main library, we need the other libraries mentioned above in this process. File saver library is used to save the final output to the local machine.

      Writing definition files for TypeScript

      Some JavaScript libraries cannot be directly used in a TypeScript project if they do not include a type definition file for TypeScript. Type definition files usually appear as <libraryName>.d.ts and you can check if there is a such file in the installed library in the node_modules folder of the project.

      Except for the docxtemplater library, the other three libraries do not include such definition files. Therefore, we have to write definition files for them separately by our own. These files are created, named according to the structure <libraryName>.d.ts and placed inside the src folder.

      jszip.d.ts

      declare module "jszip" {
        import jszip from 'jszip';
        export default JSZip;
      }
      

      jszip-utils.ts

      declare module "jszip-utils" {
        import JSZipUtils from 'jszip-utils.js';
        export default JSZipUtils;
      }
      

      file-saver.d.ts

      declare module "file-saver" {
        import { saveAs } from 'file-saver';
        export default saveAs;
      }
      

      After creating these files in the src folder, you can use these in any component.

      Submitting the templates

      First, you have to place your template document that is composed of tags, inside the public folder of the Vue project. The tags are written inside two curly brackets. ex:- {full_name} .

      For this explanation, I have created my sample template and placed it inside a separate folder inside the public folder ( public → ReportTemplates → template-1.docx ).

      c989cdcc-110d-4fd4-aa99-ef8cca51ad70-image.png

      All inside the {} are tags and they are replaced by the JSON dataset provided when rendering. The tag name and the property name in the JSON object must be similar to run a replacement for a tag.

      {#students}……{/students} inside a row of a table represents a list named “students” in the JSON object which we are going to provide when rendering.

      For this example, this is the JSON dataset we will provide.

      {
                "students": [
                  {
                    "first_name": "Udith",
                    "last_name": "Indrakantha",
                    "phone": "+94760000000"
                  },
                  {
                    "first_name": "Chamal",
                    "last_name": "Silva",
                    "phone": "+94760000001"
                  },
                  {
                    "first_name": "Tharindu",
                    "last_name": "Jayasinghe",
                    "phone": "+94760000002"
                  },
                  {
                    "first_name": "Sanindu",
                    "last_name": "Rathnayake",
                    "phone": "+94760000003"
                  },
                  {
                    "first_name": "Pramodi",
                    "last_name": "Samaratunga",
                    "phone": "+94760000004"
                  },
                  {
                    "first_name": "Samanthika",
                    "last_name": "Rajapaksha",
                    "phone": "+94760000005"
                  }
                ],
                "creater_name": "Udith Gayan Indrakantha",
                "created_date": "22/12/2020",
                "header": "Some Students' Details"
      }
      

      Writing the component

      This is how my final component code appears. When I click the button, it downloads the final word document in docx format with the hardcoded dataset in JSON format. Normally, you should call your back-end API and fetch this dataset for the report.

      <template>
        <div>
          <button @click="getDoc">Download Word Document</button>
        </div>
      </template>
      
      <script lang="ts">
      /* eslint-disable */
        import { Component, Prop, Vue } from "vue-property-decorator";
        import docxtemplater from 'docxtemplater';
        import JSZip from 'jszip';
        import JSzipUtils from 'jszip-utils';
        import  saveAs  from 'file-saver';
        @Component(
          {
            components: {
            }
          }
        )
        export default class ReportComponent extends Vue {
          getDoc() {
            this.createAndSaveDocument();
          }
          loadFile(url: any,callback: any){
              JSzipUtils.getBinaryContent(url,callback);
          }
          createAndSaveDocument(){
              /*
              *   This required JSON dataset must be fetched from the backend API.
              *   The tags in the template will be replaced by these data.
              *   For demonstrations, I have hardcoded the tesdt dataset
              */
              let dataset = {
                "students": [
                  {
                    "first_name": "Udith",
                    "last_name": "Indrakantha",
                    "phone": "+94760000000"
                  },
                  {
                    "first_name": "Chamal",
                    "last_name": "Silva",
                    "phone": "+94760000001"
                  },
                  {
                    "first_name": "Tharindu",
                    "last_name": "Jayasinghe",
                    "phone": "+94760000002"
                  },
                  {
                    "first_name": "Sanindu",
                    "last_name": "Rathnayake",
                    "phone": "+94760000003"
                  },
                  {
                    "first_name": "Pramodi",
                    "last_name": "Samaratunga",
                    "phone": "+94760000004"
                  },
                  {
                    "first_name": "Samanthika",
                    "last_name": "Rajapaksha",
                    "phone": "+94760000005"
                  }
                ],
                creater_name: "Udith Gayan Indrakantha",
                created_date: "22/12/2020",
                header: "Some Students' Details"
              };
              /* *
              * The template's path must be passed as an arguement .
              * This path can be either a URL(as  in the commented line) or a path relative to the Public folder
              * For testing, I have created a folder named  "ReportTemplates" inside the public folder and it contains my sample
              * template named "template1.docx" .
              * */
              // this.loadFile("https://docxtemplater.com/tag-example.docx",function(error: any,content : any){
                this.loadFile('ReportTemplates/template-1.docx',function(error: any,content : any){
                  if (error) { 
                    throw error
                  };
                  let zip = new JSZip(content);
                  let doc = new docxtemplater().loadZip(zip)
                  doc.setData(dataset)
                  try {
                      doc.render()
                  }
                  catch (error) {
                      let e = {
                          message: error.message,
                          name: error.name,
                          stack: error.stack,
                          properties: error.properties,
                      }
                      console.log(JSON.stringify({error: e}));
                      // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
                      throw error;
                  }
                  // docx generating
                  let out = doc.getZip().generate({
                      type:"blob",
                      mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                      })
                  saveAs(out,`MyDocument.docx`);    // You can pass this blob to a custom file saver component in the project.  
              });
          }
        }
      </script>
      
      
      <style scoped lang="scss">
      </style>
      

      n line 82, for the loadFile function’s first parameter, you can give the path of the template relative to the public folder.

      Or

      As in line 81 (commented), you can pass a URL too. This can be from a server or a cloud storage too.

      JSUtils library is used here to read the binary content from the template document and prepare it in a way that can be zipped. JSZip library is used to create the zipped content . The docxtemplater library requires the template as a zipped content. That is why we use other two libraries in the process.

      In line 89, you can see that I have set the JSON dataset to the document. This dataset can be as mentioned earlier, from an API.

      In line 113, saveAs function exported in file-saver.js library, has been used to download the blob with a given file name ( here it is MyDocument.docx ).

      I have put some useful comments too in the above code, so that you can modify the code as you wish.

      Final Output

      After submitting the templates, creating the definition files, and writing the Vue component, we can download the nice word document below.

      a8d9cf13-026e-49e3-9fee-415db484e46f-image.png

      ........

      What else can we do with this library?

      Only word documents with “.docx” can be generated in the free version. ( commercial version supports for pptx and xlsx generation too)

      The free version supports the features below, which are sufficient to generate good looking impressive reports in your project.

      • Filling data in tables ( As in the example we discussed)

      • Repeating a section in the word document with a given list of objects. (Loops)

      • Conditional Rendering of tags by enabling the angular parser option.

      • Creating a loop-list

      You can test these features at the Demo Section of their official page.

      Conclusion

      I explained how to use this docxtemplater library with a Vue.JS project in TypeScript. With this approach, the frequent changes of the templates can be accommodated while the tag names are kept unchanged . This is one of the most advantageous libraries I have come across so far and I am sure it will be same for you one day.

      If you have any issue or a question regarding this, please do not hesitate to use the comment section.

      Thank you for reading & happy coding!

      ..................................

      If you have any difficulty in reading this here, please visit my article on medium.

      posted in Web Development
      Udith Indrakantha
      Udith Indrakantha

    Latest posts made by Udith Indrakantha

    • Need Support for the Survey from Software Engineers

      මේ community එකෙ ඉන්න software Engineersලාගෙන් මගෙ final year research ප්‍රොජෙක්ට් එකට පොඩි උදව්වක් ඕනි.

      මන් රිසච් ප්‍රොජෙක්ට් එකක් කරනවා code comments' quality rating system එකක් හදන්න. ඒකට ඔයාලා කෝඩ් කරද්දි comments කරන ස්ටයිල්ස් ගැන දැන ගන්න ඕනි. මෙකෙදි ඔයාලාගෙ පොඩි විස්තර ටිකක් අරන් , ඊට පස්සෙ තියෙන්නෙ 1-5ට රේට් එකක් තෝරන්න.
      උපරිම විනඩි 5ක් විතර යාවි, පුලුවන්නම් මේක ඔයාලගෙ ටයිම් එකෙන් පොඩි වෙලාවක් අරන් පුරවන්නකො.

      https://forms.gle/tbGQtjrjqbohurkF6

      මේ වෙලාවෙ හැටියට මේක ලොකු උදව්වක් මට. ඔයලට ගොඩක් ස්තූතියි.
      මොනා හරිම යෝජනාවක් , චෝදනාවක් තියේ නම් කරුණාකරලා ඔනිම වෙලාවක මට ඊ-මේ එකක් දාන්න.
      උදිත් ඉන්ද්‍රකාන්ත - [email protected]

      posted in Comments & Feedback
      Udith Indrakantha
      Udith Indrakantha
    • Generate Word Documents from Templates Easily Using Vue.JS with TypeScript

      32099fab-0e7e-4ca4-9950-4af807bdddd1-image.png

      Introduction

      In one of my Vue projects, I needed to generate word documents with different templates. I did a small R&D and came across several libraries and APIs to achieve this. All of them were not free and we have to buy a subscription which is very expensive for me. The available free libraries used an approach where we have to design the template with HTML first and then render them as a word document. This approach did not fit my need as there were many templates and they could frequently change as per the client’s need.

      Finally, I came across a great library ( which was the only library available on the Internet) to generate word documents from a given template that includes tags that can be replaced with contemporary data when generating the report. It was a JavaScript library but my Vue project was in Typescript.

      In this article, I am going to explain how to implement this feature easily with Vue.JS project in TypeScript. If you are new to Vue with TypeScript, please follow this article explaining how to create a new Vue.JS project in TypeScript. The others can proceed.

      Installing necessary libraries

      For generating the word document we use docxtemplater library by Edgar Hipp. First of all, run these commands in the console inside your project folder.

      npm install --save docxtemplater
      npm install --save jszip@2
      npm install --save jszip-utils
      npm install --save file-saver
      

      In addition to the main library, we need the other libraries mentioned above in this process. File saver library is used to save the final output to the local machine.

      Writing definition files for TypeScript

      Some JavaScript libraries cannot be directly used in a TypeScript project if they do not include a type definition file for TypeScript. Type definition files usually appear as <libraryName>.d.ts and you can check if there is a such file in the installed library in the node_modules folder of the project.

      Except for the docxtemplater library, the other three libraries do not include such definition files. Therefore, we have to write definition files for them separately by our own. These files are created, named according to the structure <libraryName>.d.ts and placed inside the src folder.

      jszip.d.ts

      declare module "jszip" {
        import jszip from 'jszip';
        export default JSZip;
      }
      

      jszip-utils.ts

      declare module "jszip-utils" {
        import JSZipUtils from 'jszip-utils.js';
        export default JSZipUtils;
      }
      

      file-saver.d.ts

      declare module "file-saver" {
        import { saveAs } from 'file-saver';
        export default saveAs;
      }
      

      After creating these files in the src folder, you can use these in any component.

      Submitting the templates

      First, you have to place your template document that is composed of tags, inside the public folder of the Vue project. The tags are written inside two curly brackets. ex:- {full_name} .

      For this explanation, I have created my sample template and placed it inside a separate folder inside the public folder ( public → ReportTemplates → template-1.docx ).

      c989cdcc-110d-4fd4-aa99-ef8cca51ad70-image.png

      All inside the {} are tags and they are replaced by the JSON dataset provided when rendering. The tag name and the property name in the JSON object must be similar to run a replacement for a tag.

      {#students}……{/students} inside a row of a table represents a list named “students” in the JSON object which we are going to provide when rendering.

      For this example, this is the JSON dataset we will provide.

      {
                "students": [
                  {
                    "first_name": "Udith",
                    "last_name": "Indrakantha",
                    "phone": "+94760000000"
                  },
                  {
                    "first_name": "Chamal",
                    "last_name": "Silva",
                    "phone": "+94760000001"
                  },
                  {
                    "first_name": "Tharindu",
                    "last_name": "Jayasinghe",
                    "phone": "+94760000002"
                  },
                  {
                    "first_name": "Sanindu",
                    "last_name": "Rathnayake",
                    "phone": "+94760000003"
                  },
                  {
                    "first_name": "Pramodi",
                    "last_name": "Samaratunga",
                    "phone": "+94760000004"
                  },
                  {
                    "first_name": "Samanthika",
                    "last_name": "Rajapaksha",
                    "phone": "+94760000005"
                  }
                ],
                "creater_name": "Udith Gayan Indrakantha",
                "created_date": "22/12/2020",
                "header": "Some Students' Details"
      }
      

      Writing the component

      This is how my final component code appears. When I click the button, it downloads the final word document in docx format with the hardcoded dataset in JSON format. Normally, you should call your back-end API and fetch this dataset for the report.

      <template>
        <div>
          <button @click="getDoc">Download Word Document</button>
        </div>
      </template>
      
      <script lang="ts">
      /* eslint-disable */
        import { Component, Prop, Vue } from "vue-property-decorator";
        import docxtemplater from 'docxtemplater';
        import JSZip from 'jszip';
        import JSzipUtils from 'jszip-utils';
        import  saveAs  from 'file-saver';
        @Component(
          {
            components: {
            }
          }
        )
        export default class ReportComponent extends Vue {
          getDoc() {
            this.createAndSaveDocument();
          }
          loadFile(url: any,callback: any){
              JSzipUtils.getBinaryContent(url,callback);
          }
          createAndSaveDocument(){
              /*
              *   This required JSON dataset must be fetched from the backend API.
              *   The tags in the template will be replaced by these data.
              *   For demonstrations, I have hardcoded the tesdt dataset
              */
              let dataset = {
                "students": [
                  {
                    "first_name": "Udith",
                    "last_name": "Indrakantha",
                    "phone": "+94760000000"
                  },
                  {
                    "first_name": "Chamal",
                    "last_name": "Silva",
                    "phone": "+94760000001"
                  },
                  {
                    "first_name": "Tharindu",
                    "last_name": "Jayasinghe",
                    "phone": "+94760000002"
                  },
                  {
                    "first_name": "Sanindu",
                    "last_name": "Rathnayake",
                    "phone": "+94760000003"
                  },
                  {
                    "first_name": "Pramodi",
                    "last_name": "Samaratunga",
                    "phone": "+94760000004"
                  },
                  {
                    "first_name": "Samanthika",
                    "last_name": "Rajapaksha",
                    "phone": "+94760000005"
                  }
                ],
                creater_name: "Udith Gayan Indrakantha",
                created_date: "22/12/2020",
                header: "Some Students' Details"
              };
              /* *
              * The template's path must be passed as an arguement .
              * This path can be either a URL(as  in the commented line) or a path relative to the Public folder
              * For testing, I have created a folder named  "ReportTemplates" inside the public folder and it contains my sample
              * template named "template1.docx" .
              * */
              // this.loadFile("https://docxtemplater.com/tag-example.docx",function(error: any,content : any){
                this.loadFile('ReportTemplates/template-1.docx',function(error: any,content : any){
                  if (error) { 
                    throw error
                  };
                  let zip = new JSZip(content);
                  let doc = new docxtemplater().loadZip(zip)
                  doc.setData(dataset)
                  try {
                      doc.render()
                  }
                  catch (error) {
                      let e = {
                          message: error.message,
                          name: error.name,
                          stack: error.stack,
                          properties: error.properties,
                      }
                      console.log(JSON.stringify({error: e}));
                      // The error thrown here contains additional information when logged with JSON.stringify (it contains a property object).
                      throw error;
                  }
                  // docx generating
                  let out = doc.getZip().generate({
                      type:"blob",
                      mimeType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
                      })
                  saveAs(out,`MyDocument.docx`);    // You can pass this blob to a custom file saver component in the project.  
              });
          }
        }
      </script>
      
      
      <style scoped lang="scss">
      </style>
      

      n line 82, for the loadFile function’s first parameter, you can give the path of the template relative to the public folder.

      Or

      As in line 81 (commented), you can pass a URL too. This can be from a server or a cloud storage too.

      JSUtils library is used here to read the binary content from the template document and prepare it in a way that can be zipped. JSZip library is used to create the zipped content . The docxtemplater library requires the template as a zipped content. That is why we use other two libraries in the process.

      In line 89, you can see that I have set the JSON dataset to the document. This dataset can be as mentioned earlier, from an API.

      In line 113, saveAs function exported in file-saver.js library, has been used to download the blob with a given file name ( here it is MyDocument.docx ).

      I have put some useful comments too in the above code, so that you can modify the code as you wish.

      Final Output

      After submitting the templates, creating the definition files, and writing the Vue component, we can download the nice word document below.

      a8d9cf13-026e-49e3-9fee-415db484e46f-image.png

      ........

      What else can we do with this library?

      Only word documents with “.docx” can be generated in the free version. ( commercial version supports for pptx and xlsx generation too)

      The free version supports the features below, which are sufficient to generate good looking impressive reports in your project.

      • Filling data in tables ( As in the example we discussed)

      • Repeating a section in the word document with a given list of objects. (Loops)

      • Conditional Rendering of tags by enabling the angular parser option.

      • Creating a loop-list

      You can test these features at the Demo Section of their official page.

      Conclusion

      I explained how to use this docxtemplater library with a Vue.JS project in TypeScript. With this approach, the frequent changes of the templates can be accommodated while the tag names are kept unchanged . This is one of the most advantageous libraries I have come across so far and I am sure it will be same for you one day.

      If you have any issue or a question regarding this, please do not hesitate to use the comment section.

      Thank you for reading & happy coding!

      ..................................

      If you have any difficulty in reading this here, please visit my article on medium.

      posted in Web Development
      Udith Indrakantha
      Udith Indrakantha
    • RE: Send Emails without a server-side code with Angular

      @root Yes bro. we can use it for Ionic also because SMTP js is a javascript code. You just need to add the file and import it to the .ts file if the component. The way to import a js file is simply the same described in this post.

      posted in Front-End Development
      Udith Indrakantha
      Udith Indrakantha
    • Send Emails without a server-side code with Angular

      alt text
      Without any server-side code hosted on a server, you can send emails through your Angular application with smtpJS, a client-side Javascript library.

      First you need to download this library and include it into the necessary component of the Angular Application.
      Click here to download the library file.
      (If any error in download, go to smtpJS.com , where you can directly download or get the CDN link)

      Next , put this downloaded js file into the assets folder found in src directory of the project.

      Next we have to get the help of an email service provider to send the email. I here use Elastic Email site for this. First go to the Elastic Email site to create an account. Just complete the sign up process, it’s that simple.

      After logging into the site, go to Start — → Connect To SMTP API .

      alt text

      Next, you can see a button to create new credentials. Create a new credentials following the simple steps. The system will generate a password for you. Copy that password and save it somewhere before you close that popup model.

      Finally you’ll see something like this.

      alt text

      Here, your user name and password (You saved it earlier) can be seen .These details are used to access this.

      Coding part

      Go to your angular project’s relevant component from which an email must be sent.

      1. Import the smtp.js file from assets folder to the component by typing
        import ‘./../../../assets/smtp.js’;             <! — path might change — >
        declare let Email : any;

      2. Write the code to send the email with the user-inputs within onSubmit() method as below,

      import { Component, OnInit } from '@angular/core';
      import { ProfileService } from '../profile.service';
      import { Model } from './contact-form';
      import { NgForm } from '@angular/forms';
      import  './../../../assets/js/smtp.js '; <! — file path may change →
      declare let Email: any;
      
      @Component({ selector: ‘app-contact’,
       templateUrl: ‘./contact.component.html’,
       styleUrls: [‘./contact.component.scss’]})
      
      export class ContactComponent implements OnInit {
      
      model: Model = new Model();
      
      constructor( private profile: ProfileService) { }
      
      ngOnInit() {
      }
      
      onSubmit(f: NgForm) {
      
      Email.send({
                    Host : ‘smtp.elasticemail.com’,
                   Username : ‘[email protected]’, 
                   Password : ‘**************************’,          //Enter your password here
                   To : ‘[email protected]’,
                   From : `[email protected]`,
                   Subject : this.model.subject,
                  Body : `
                         <i>This is sent as a feedback from my resume page.</i> <br/>
                         <b>Name: 
                        </b>${this.model.name} <br />
                         <b>Email: </b>${this.model.email}<br />
                        <b>Subject: 
                        </b>${this.model.subject}<br />
                        <b>Message:</b> <br /> 
                        ${this.model.message} <br> 
                        <br> <b>~End of Message.~</b> `
      }).then( 
                   message => {alert(message); f.resetForm(); } 
                   );
          }
      }
      

      Here , within Email.send(….); method, you can give the elastic mail registered email as the username ,
      and earlier saved password for the password field.
      From: email should be equal to the elastic mail’s registered email and you can set the receiver’s email under To field.

      Other fields can be taken from your form created .

      That’s it.

      Original Post: https://medium.com/@udith.indrakantha/send-emails-without-a-server-side-code-with-angular-e227c3e62dbd

      posted in Front-End Development
      Udith Indrakantha
      Udith Indrakantha
    • RE: Deploy Angular on Firebase Hosting for FREE!

      Great bro

      posted in Front-End Development
      Udith Indrakantha
      Udith Indrakantha
    • RE: පහසුන්වෙන්ම ඔබෙ Angular Application එක නොමිලෙ Netlify server එකෙ deploy කර ගමු. (Simple English)

      @root Thanks bro. I'll upload the article on hosting on heroku soon. I just selected Netlify as first one because I just like that word "Netlify" more than "heroku". By the way, if you find any mistakes in my article, plz don't hesitate to let me know.

      posted in Front-End Development
      Udith Indrakantha
      Udith Indrakantha
    • පහසුන්වෙන්ම ඔබෙ Angular Application එක නොමිලෙ Netlify server එකෙ deploy කර ගමු. (Simple English)

      alt text
      This article is all about how you can deploy your Angular application securely on Netlify server . This is a free place for you to deploy your application.

      First you need to have a Netlify Accout (Create if not) and a GitHub repo of your project.
      ( I assume that you already have a github repo of your Angular project.)
      I teach you the way with a sample project I created just for fun.

      Let’s begin

      Configuring Netlify

      1. First go to your Netlify account. There you can see a button “New site from Git” (Fig 1.1). Click on it.

      0_1573148079548_0608d448-a21c-4063-9249-efabdf7b6631-image.png
      Fig 1.1

      2. Then select the repository site. I here select GitHub.(You can select the site where your project is.)
      When selected, you are redirected to authorize the access from netlify and there you can select the repository that you need to deploy.

      3. Select the repository again and go to step 3. (Fig 1.2)
      alt text
      Fig 1.2

      Here in this page, you have to fill some information. (you can change these later too)

      You can specify which branch needs to be deployed.
      For Build Command , give ng build — prod
      For Publish directory , give dist/<your project name>
      (You can find your correct project name at the end of angular.json file of your project. Ex: dist/my-blogger-web as in Fig(1.3))

      alt text
      Fig 1.3

      If all set. Click the button “Deploy site”. You will be directed to something like this in Fig 1.4.

      alt text
      Fig 1.4

      4. Next, go to Settings tab and copy the API ID and save it somewhere because we are gonna need it later. (Fig 1.5)
      [Here, you can change your site name also.]

      alt text
      Fig 1.5

      5. We need to find a Personal Access Token key .
      Click on Avatar picture of your profile on right top corner, select User settings,
      Select Applications from the menu,
      Under Personal access tokens, click New access token button .
      (Fig 1.6, Fig 1.7)

      alt text
      Fig 1.6
      alt text
      Fig 1.7

      Give a simple description for the token so that you can identify why this token is used, when you check tokens sometimes later.

      Click the button to Generate a token. Copy and paste that token somewhere to use it later. Then click Done! at last.

      Configuration in Angular project

      6. Open the command window inside your Angular project’s root folder.

      and run this command
      ng add @netlify-builder/deploy

      **There you are asked to enter API ID: you can enter it from where you copied and saved it earlier.
      ** You are asked next to enter personal Acccess token which you generated earlier . Please, do not enter it here.Just press enter and skip it.( Because these details are entered in your angular.json file which can be tracked in your github repo easily so that outsider can use your API ID and access token to get access to your site. see Fig 1.8 )

      alt text
      Fig 1.8

      7. Next you have to set up the access token key as an environment variable of your computer.

      Right click on This PC icon on desktop of you computer ==> Properties ==> Advanced system settings ==> Advanced tab ==>Environment Variables ==> User Variables

      Under User variables , you have to enter a new variable, Variable Name as NETLIFY_TOKEN and Variable value as the access token key generated earlier and saved for later use by you. see Fig 1.9

      alt text
      Fig 1.9

      9. Next you have to run
      ng run <your project name>:deploy

      Plz, give your project name when running the above command.(See ,no space when typing the colon : )
      Ex: ng run my-blogger-web:deploy

      [For Angular vCLI 8.3.0 and above, just run ng deploy instead]

      This creates a folder dist/<Your project name> which you gave as the Publish directory for netlify site.

      10. Next part is, open your .gitignore file of your project and delete the line with /dist to track dist folder to be pushed to gitHub.

      At last commit and push.

      Here you go, go to your netlify site, and Click Trigger Deploy button to deploy. You can change ‘deploy settings’ there if you want.

      alt text

      All done!

      Your site is available at https://<your site name>.netlify.com

      ex: https://udithdemo.netlify.com

      Thank you.

      posted in Front-End Development
      Udith Indrakantha
      Udith Indrakantha
    • Fixing 401 Error with CORS Preflights (with Spring boot)

      alt text
      When the web application runs on a different domain and the server runs on another domain, we have to deal with cross origin requests. But, if we don’t know the mechanism of cross origin resource sharing (CORS), we will end up with errors like 401.

      Error in brief

      My Angular web application runs on port 4200, and my spring boot application runs on server on port 8080. I could not enable CORS in my backend, so, I got an error when sending a request from my application like this.

      alt text

      Reason
      My pre-flight request is not responded with status OK(200).

      Solution

      I enabled CORS in my backend. To do this, there are several methods. Here in my post, I have shown the easiest way to do that. But, if you are interest in knowing other ways, click me )

      By using Web Security in Spring Boot,

      You have to create a web security configuration class. I hope everybody creates that class for backend authentication purposes.

      If you have already created that class, inside configure( HttpSecurity httpSecurity ) method ,add this line httpSecurity.cors();
      alt text

      It’s that simple !!!
      Originally published at https://webtechmora.blogspot.com.

      posted in Back-End Development
      Udith Indrakantha
      Udith Indrakantha
    • All about .replaceAll() in Java

      alt text
      java.lang.String class brings you a very powerful method to do replacements within a string.

      This method allows you to target specific substrings using regular expression ,so that you can even remove and replace any pattern within a string.

      Mainly, this method can

           * replace a given substring found any where in the string
           * replace a given character found any where in the string
           * replace a given reg expression found any where in the string
      

      Even though there are separate methods like replace(char old, char new), replace(charSequence old, charSequence new) to do above functions, this replaceAll() method acts as a versatile method for all those functions.

      This is how this method is defined in String class,

      String replaceAll(String regex , String new)

      As you can see , this method returns a new string. Actually, a string is immutable in JAVA , so it is not possible to alter a string. This method returns a new string instead.You need to catch it with a string variable.

      **This method accepts to two parameters which must be in type String. So , when you need to replace a character, you have to use a double quotation for the characters (instead of single quotations which are used for representing char).

      Examples:

      alt text
      Character replacement

      alt text
      String replacement

      alt text
      Regex replacement

      Keep in Touch!!!

      posted in Blogs
      Udith Indrakantha
      Udith Indrakantha
    • RE: Agile methodology in software development

      Great post

      posted in Blogs
      Udith Indrakantha
      Udith Indrakantha