Wednesday, July 31, 2019

How to solve the windows update hanging at "Gear" icon in Windows10?

Windows 10 needs to have windows update installed regularly.
Sometimes, updates are not getting downloaded without visible reasons.
One important service for Windows Update is "Windows Update Medic Service".

  • Open the Registry Editor by executing regedit command.
  • Go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\WaaSMedicSvc in registry editor.
  • Double-click on Start registry DWORD to modify its Value data in right pane.
  • Set the Value data to 4 to disable Windows Update Medic Service (1 to enable that service)
  • Click "OK". Close Registry Editor and restart the machine to make changes effective.

Monday, July 1, 2019

How to keep track the changes to JPA in Spring Boot?

We develop the LOB software of different domain and almost every app use backend database to persist the data. In Java, JPA is widely use for ORM layer in between of app and database. In many occasions, CRUD logging is part of the basic requirement.
One common scenario is application needs to keep track of price change on a particular stock item within a year. It start with $25 initially and increase to $30 in a month. After 3 months, it goes down a little bit to $28 due to excess supply. In following month, it goes back to $30 thanks to higher demand and etc.
Most probably, this kind of information is useful for the end-users and our application needs to support this.
Of course, we can implement this feature by hard-coding each updates to the database, can't we ???
But, we have better option with JPA Entity Listeners. We can easily bind the event listener and persist each changes to database. It is simple and easy to implement with the help of Spring Boot.
Create a new Spring Boot application. Assume we have the following in file.
spring.datasource.url = jdbc:mysql://localhost:3306/jpa-logger?useSSL=false
spring.datasource.username = test
spring.datasource.password = test = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = create
Detail implementation is as followed.
This is REST controller which is for testing JPA logging feature

AutowireUtil class is used to auto-wire spring-beans inside JPA listener

This is the base class for all model which require the JPA logging for CRUD action.

This is Employee class which inherit from BaseModel.

This is the meta information of CRUD event to be logged into database.

This is the listener class which persist the CRUD meta information into database.

This class inject auto-wire the bean for listener.

Saturday, April 27, 2019

How to enable image resizing inside contenteditable DIV (aka WYSIWYG editor) in Chrome?

When we put the image inside contenteditable DIV (aka WYSIWYG editor), IE allow resizing by default but Chrome does not. In fact, we can easily implement this features using pure Javascript. I compile DOM handling to mouse, mouseup and other event handler into a sample program.
Source code


Sunday, April 14, 2019

Paste the image into contenteditable div

When we accept the user input data, user input text data most of the time. But for some application, users need to input image and website needs to persist them. With the support of FileReader and clipboardData of paste event, we can easily enable that direct image input. User can directly copy the images from the software like MS-Paint or Web Browser and paste it into our input control (contenteditable div in our scenario).

Sample Text Editor with Image copy-paste support
Show HTML source

Sunday, March 10, 2019

Race condition in multi-threaded application

When we develop the multi-threaded application, it's critical to ensure that no race condition occurs. Otherwise, our program will produce the inconsistent result.
Let see the demo program. When we execute this program for 5 times, it will output 1000 for each run.
public class RaceCondition implements Runnable {
static Object lock = new Object();
static int sharedNumber = 0;

public static void main(String[] args) {
Thread t1 = new Thread(new RaceCondition());
Thread t2 = new Thread(new RaceCondition());
try {
} catch (Exception e) {

public void run() {
boolean wait = true;
for (int i = 0; i < 500; i++) {
synchronized (lock) {
int buffer = sharedNumber;
if (Math.random() > 0.5 && wait) {
wait = false;
try {
} catch (InterruptedException e) {
sharedNumber = buffer;
Ok, let's comment "synchronized" code line and it's closing curly brace line. This time, we will have 5 different values after executing for 5 times.
synchronized block ensure that only one thread can execute on the share/same object at a time in its block. It prevent the possible race condition.

Tuesday, March 5, 2019

How to implement CRUD features in ASP.NET Web API?

We are going to discuss how we can implement RESTful service layer using ASP.NET Web API.
In this program, we will use session object to persist as in-memory datastore.
Yes, REST is stateless. By using session, we will make it stateful. Well, the only purpose of using session in this program is to use some kind of back-end data store when we do CRUD actions. We are not using this type of data store in production code. We will use industry grade databases for that.
Alright, let's start hands-on work now. Open up Visual Studio 2015 and select File => New => Project and select "ASP.NET Web Application (.NET Framework)". Click "WebAPI" checkbox and create new project.
First we will create the Model class for Employee entity.
Model class
And make sure our WebApi return data in json format.
Configure to return JSON format
Here we will implement the API controller logic
Implement the RESTful API in the controller
In real-word application, we will have back-end database with ORM tool like Entity Framework. We will use dummy data for demo.
Generate the sample data in ActionFilter
For any WebApi, security is a very important factor. For simplicity sake, I just basic authentication to show-case the usage pattern.
For authenticating the routes
Add the entry for authentication in web.config file.
  <system.webServer>    <modules>      <add name="BasicAuthHttpModule" type="WebApiSampleProject.BasicAuthHttpModule, WebApiSampleProject" />    </modules>  </system.webServer>

Saturday, February 23, 2019

Convert the tab separated data into grid-style data

We use different kinds of text layout styles, like Comma-delimited, tab-delimited, etc. Some of the customers give feedback about they find it more intuitive to see the data in simple grid layout for some tabular format data.
This program is simplified version of what we can do to convert tab-delimited data into grid layout table-style data with simple pure JavaScript.

Sunday, January 20, 2019

Database Normalization

What is Normalization?
Normalzation is a database design technique that reduces the data redundancy and dependency.
Let's start to see how we do normalization in sample data of football player information.
We will see how we procced from Un-normalized Form to First, Second, Third Normal Form step-by step.

Initially, our data is in un-normalized form. It contains composite or multiple values in an attribute (Clubs).
Player Name Clubs Agent Position
Ronaldo Juventus, Real Madrid, Manchester United, Sporting Lisbon Mandez Forward
Rooney DC United, Manchester United, Everton David Forward
Nani Manchester United, Sporting Lisbon Mandez Winger

1st Normal Form
Each column should contain a single value and each record have to be unique.
Player Name Club Agent Position
Ronaldo Juventus Mandez Forward
Ronaldo Real Madrid Mandez Forward
Ronaldo Manchester United Mandez Forward
Ronaldo Sporting Lisbon Mandez Forward
Rooney DC United David Forward
Rooney Manchester United David Forward
Rooney Everton David Forward
Nani Manchester United Mandez Winger
Nani Sporting Lisbon Mandez Winger

2nd Normal Form
Now, we are in 1NF. To make it 2NF, we need to define primary key.
Player Id Player Name Agent Position
1 Ronaldo Mandez Forward
2 Rooney David Forward
3 Nani Mandez Winger

Player Id Club
1 Juventus
1 Real Madrid
1 Manchester United
1 Sporting Lisbon
2 DC United
2 Manchester United
2 Everton
3 Manchester United
3 Sporting Lisbon

3rd Normal Form
There are data anomalies and inconsistencies in current design, for example:
+ If we deleted the "Ronaldo" and "Nani", we would inevitably delete the agent "Mandez" completely from the database.
+ We cannot add a new agent to the database unless we also add a player.
+ If "Mandez" retired from agent job, we would have to change it in all records in which he appears.
So, we will remove this transitive functional dependency in 3NF. Agents will be moved to another table and its id will be used as foreign key in Player table.
Player Id Player Name Agent Id Position
1 Ronaldo 1 Forward
2 Rooney 2 Forward
3 Nani 1 Winger

Agent Id Name
1 Mandez
2 David
Now, we have "Players", "Agents", "Players_Clubs" tables.
We can optimized by moving Clubs into "Clubs" table and linking its id as foreign key in "Players_Clubs" table.

Saturday, January 12, 2019

How can we dynamically generate pivot table in MySQL?

Pivot table is an important concept we are using in many applications. Technically, it generate the data values into dynamic columns. One of the examples is attendance information. We store the person name, date and present (boolean that determined if that person is present or absent on this date).

This is how data is stored is database. This is what we want to see in report.
id student date present
1 John 2019-01-07 1
2 David 2019-01-07 1
3 Larry 2019-01-07 1
4 Wesley 2019-01-07 0
5 Amy 2019-01-07 1
6 John 2019-01-08 1
7 David 2019-01-08 0
8 Larry 2019-01-08 1
9 Wesley 2019-01-08 1
10 Amy 2019-01-08 1
11 John 2019-01-09 0
12 David 2019-01-09 1
13 Larry 2019-01-09 1
14 Wesley 2019-01-09 1
15 Amy 2019-01-09 1
16 John 2019-01-10 1
17 David 2019-01-10 1
18 Larry 2019-01-10 0
19 Wesley 2019-01-10 1
20 Amy 2019-01-10 1
21 John 2019-01-11 1
22 David 2019-01-11 1
23 Larry 2019-01-11 0
24 Wesley 2019-01-11 1
25 Amy 2019-01-11 0
date John David Larry Wesley Amy
2019-01-07 1 1 1 0 1
2019-01-08 1 0 1 1 1
2019-01-09 0 1 1 1 1
2019-01-10 1 1 0 1 1
2019-01-11 1 1 0 1 0

SQL Code
SET @dynamic_columns = NULL;
select group_concat(student_col) from (
select DISTINCT CONCAT('MIN(IF(student = ''', student, ''', present, NULL)) AS ', student) as student_col from 
) column_list INTO @dynamic_columns;
SET @sql = CONCAT('SELECT date, ', @dynamic_columns, ' FROM attendance GROUP BY date');
PREPARE qry FROM @sql;

Retrieve all the employees under a manager from a self-referencing table in MySQL

In previous post, we discussed how we can manage to store the hierarchical data in MySQL using self-referencing relationship.
Now, we will see how we can retrieve the data back.
Here, we have manager-employees relationship. One manager has other employees (maybe manager or non-manager) working under him. We will retrieve the whole list of employees under a manager.

SQL Code
SET @id := '2';
SELECT  id, name, managerid, @id
FROM (SELECT * FROM employee ORDER BY managerid, name) E 
WHERE FIND_IN_SET(managerid, @id) > 0
AND @id := CONCAT(@id, ',', id);

Let's assume the managerid to search is "2".
We first need to sort employee table (derived table E) by managerid to make sure that records are in correct order. (This is required as we iterate the record from beginning and add to manager list if conditions matched).
FIND_IN_SET returns the position of a string within a list of strings. (Greater than zero means this employee is under him).
If current record work under this manager(s), CONCAT the id of current record into manager list. (He may have other employees under him).

Thursday, January 10, 2019

How can we store self-referencing entities in MySQL?

Self-referencing entities are one of the database designs we are facing in many applications.
An employee will have direct reporting manager who is also an employee.
Each person has mother who also has her own mother and so on.
We can efficiently store those type of hierarchical data in RDBMS.
This type of relationship is called as recursive association which connect to the same class type.
Well, let's have some hands-on work now.

Following SQL code will create the employee table with self-referencing key.
CREATE TABLE `employee` (
  `name` varchar(45) DEFAULT NULL,
  `managerid` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `index2` (`managerid`),

After creating the table, we will enter the dummy data rows to test.
INSERT INTO employee(name) values('CEO');
INSERT INTO employee(name, managerid) values('Mgr1', 1);
INSERT INTO employee(name, managerid) values('Mgr2', 1);
INSERT INTO employee(name, managerid) values('TL1', 2);
INSERT INTO employee(name, managerid) values('TL2', 3);

Now, we can easily retrieve the values from our self-referencing table using following SQL join query.
SELECT, AS "Employee", AS "Manager"
FROM employee EMP LEFT OUTER JOIN employee MGR
ON EMP.managerID =
ORDER BY EMP.managerid,

Id Employee Manager
1 CEO (null)
2 Mgr1 CEO
3 Mgr2 CEO
4 TL1 Mgr1
5 TL2 Mgr2

Image compression using C#

Sometimes, we need to compress the image files while maintaining the image quality. This can be achieved by the following C# implementation....