Writing Complex Queries Using LINQ

I am writing this article based on my recent experience regarding how to write some complex queries using LINQ.

I’m not going to explain why we should use LINQ over lambda or neither Query Syntax vs. Method syntax in LINQ.

Let’s dig in..

LINQ Join column from 2 table:

Just for the demo, I have created Building & Resource classes. Resource having a relationship with Building via BuildingId column.

Now I have to write a query that returns ‘Distinct’ and ‘Active’ resources list i.e: Resource Id & Resource Name- Building Name. Ex: Physics Lab-Building 01. Here ‘Lab’ is the Resource Name and ‘Building 01’ is the Building name.

100Physics Lab-Building 01
101Chemistry Lab-Building 02
var resourcequery = (from resource in DbInstance.Resource
join building in DbInstance.Building on resource.BuildingId equals building.Id
where resource.IsActive == true
select new { resource, building } into t1
select new
Id = t1.resource.Id.ToString(),
Name = t1.resource.Name + "-" + t1.building.Name

Here is the final output:

Difference Between Coding & Programming?

Last week one of my university juniors asked me this question! That, what’s the difference between Coding & Programming?

Then I thought I should write a post about it and try to explain. I believe it’s very important if you are working Software Industry you should know what you actually are!

Most people think both are the same thing! Not at all! There are differences between the two “worlds”. So let’s explore how professionals use them and try to understand the terms first by understanding what they mean.

What’s Coding?

Image courtesy: unsplash

Coding is how we communicate with computers. Code tells a computer what actions to take and writing code is like creating a set of instructions.
In order to become a coder, you need to be able to write code in different programming languages such as Java, C, PHP & so on. With this knowledge, you will be able to provide instructions and information to the computer to execute the programs you or your team creates.

Coding involves writing code for creating a software program or any sort of application, website, game.

What’s Programming?

Image courtesy: pexels.com

There are many definitions of what programming is, but the one I prefer is: “Programming is how you get computers to solve problems.” There are two key phrases here which is important:

  • you: without the programmer (you), the computer is useless. It does what you tell it to do.
  • solve problems: computers are tools. They are complex tools, admittedly, but they are not mysterious or magical: they exist to make tasks easier.

In order to come up with a solution or an application, you will need to carry out a few steps:

  • planning the application
  • designing it
  • testing the features
  • deploying it
  • maintaining it after development is finished

So it’s only fair to say that programming not only deals with coding but also implementing algorithms and much more.

Let me try to explain it in a simpler way so you can get a better understanding.

For example, you can program your watch to wake you up at 7 AM. Also, you can program the AC to come on at the temperature that you have chosen. These devices have code on the backend that works based on a set of instructions given by the user.

The Differences Between Coding and Programming in Brief:

  1. Basic Difference:
    Coding is a part of programming that deals with writing code that a machine can translate. Programming is the process of creating a program that follows certain standards and performs a certain task.
  2. Scope:
    Coding is about translating the requirement logic into machine-understandable code. In contrast, programming demands analysis and conceptualization of different aspects of any program and finding solutions to any issues that may occur during the process. It also involves critical parameters such as debugging, compiling, testing, and implementation.
  3. Tools:
    Coding doesn’t require as many software tools since it’s just an act of code translation to machine-readable form. Just a simple text editor like notepad or WordPad is enough. As a coder, you just need to know the details of the syntax of any programming language.
    Programming requires that you perform document reviews and analysis along with coding that requires extra tools. These tools include code analyzing tools, databases, testing frameworks, compilers, assemblers, debuggers, and modeling algorithms. A programmer needs lots of experience to obtain these skills.
  4. Expertise:
    Coders should have basic knowledge of programming.
    Programmers should have experience in creating algorithms, understanding requirements, processing data, modeling problems, and managing projects – these are just some of the practical skills needed.
  5. Outcome:
    While coding, your expected outcome is part of or the whole project. The code acts as a set of instructions given to the computer.
    On the other hand, programming yields the whole application, software products, or a website that’s ready to use.

So, how both Coding and Programming works together?

Let’s explain this using an example to get a better understanding. Imagine we are creating an app to monitor something like our daily routine for us. How will these two different fields work together?

First the programmer will have to:

  • plan the architechture of the app,
  • list down features of the app
  • designing the app

After the programmer is done with these first steps, they hand it over to the coder.
Now the coder will transform the ideas into code. After this process is done, the completed code is given back to the programmer.

Now the programmer will go through the code do some polishing by debugging, checking for errors, and doing tests before publishing the final product.
Now you can see how these two fields have come across together to work on an idea and produce something that’s usable.

Final Words:

Often people confuse programming & coding; hope by now you agree that they are distinctively different after comparing coding vs. programming with a number of factors.

Coding is the primary step and translates the requirements and codes to convert into a machine-readable syntax. Still, programming deals with the executable programs to produce the mechanical outputs following the inputs and requires the knowledge of the complete software development life cycle.

How to show Store(Vendor) Name on Checkout page in WordPress

So, this was the requirement from the client to show the Vendor Name on the Checkout page. Though the plugin shows the Vendor Name of each product on the right side just after the product name.
N.B: To support multi-vendor in WordPress I’m using Dokan Plugin.


Let’s copy the code from below:

add_action( 'woocommerce_before_checkout_form', 'print_vendor_name_on_checkout_page', 10 );
function print_vendor_name_on_checkout_page()
echo 'Shop: ';
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
$authror_id = $cart_item['data']->post->post_author; // <=== The post author ID
$author = get_user_by( 'id', $authror_id );
$store_info = dokan_get_store_info( $author->ID );
$store_title= $store_info['store_name'];
if ( !empty( $store_title ) ) { ?>
<span class="details">
<?php echo $store_title; ?>
<?php }

That’s all! We’re done!
N.B.: In my case customers are allowed to order from one shop/vendor at once. That’s why I’ve printed the shop name outside the foreach function.

So, what if in your case you allow ordering from multiple stores? Just print the store name inside the foreach!

add_action( 'woocommerce_before_checkout_form', 'print_vendor_name_on_checkout_page', 10 );
function print_vendor_name_on_checkout_page()
echo 'Shop: ';
foreach( WC()->cart->get_cart() as $cart_item_key => $cart_item ){
$authror_id = $cart_item['data']->post->post_author; // <=== The post author ID
$author = get_user_by( 'id', $authror_id );
$store_info = dokan_get_store_info( $author->ID );
$store_title= $store_info['store_name'];
if ( !empty( $store_title ) ) { ?>
<span class="details">
<?php echo $store_title; ?>
<?php }

Done! Pretty simple, isn’t it?

A Deep Dive into CSS Grid

As the title says A Deep Dive into CSS Grid, I’m not gonna explain the basic of CSS grid rather in this post I’ll try to explore almost all features and properties of CSS grid.

Recap: CSS grid allows us to divide a webpage into rows and columns with simple properties to build complex layouts as well as small user interfaces using CSS only, without any change to the HTML.

Let’s dive in detail..

Property: display
To make an element a grid, set its display property to grid.

.to-be-grid {
display: grid;

Doing this makes .to-be-grid a grid container and its children grid items.

Property: grid-template-columns

We can create columns by using the grid-template-columns property. To define columns set this grid-template-columns property to column sizes in the order that you want them in the grid to appear. Let’s have a look:

.grid {
display: grid;
grid-template-columns: 100px 100px 100px;

This defines 3 100px width columns. All grid items will be arranged in order, in these columns. And the row height will be equal to the height of the tallest element in row but this also can be changed with grid-template-rows.

Property: grid-template-rows

It is used to define the number & the size of rows in a grid. It is similar in syntax to grid-template-rows.

.grid {
display: grid;
grid-template-columns: 100px 100px 100px;
grid-template-rows: 100px 100px 100px;

Only the grid-template-rows property without grid-template-columns would result in column width being same as the width of the widest element in that row.

Property: grid-template

Grid is shorthand for three properties: grid-template-rows, grid-template-columns, and grid-template-areas.

You can use it is like this:

.grid {
“header header header” 80px
“nav article article” 600px
/ 100px 1fr;

You define the template areas such as you normally would, place the width of every row on its side then finally place all the column widths after a forward slash. Like before, you’ll place all of it on one line.

Data Type:

The unit “fr” is a newly created unit for CSS Grid Layout. The fr unit helps to create flexible grids without calculating percentages. 1 fr represents one fraction of available space. The available space is divided into total number of fractions defined. So, 3fr 4fr 3fr divides the space into 4+3+4=11 parts and allocates 4, 3 and 4 parts of the available space for the three rows/columns respectively. For example:

.grid {
display: grid;
grid-template-columns: 3fr 4fr 3fr;

If you combine fixed units with flexible units, the available space for the fractions is calculated after subtracting the fixed space. Let’s check out another example:

.grid {
display: grid;
grid-template-columns: 3fr 200px 3fr;

The width of a single fraction is calculated like: (width of .grid – 200px) / (3 + 3). The space of the gutters, if any would have also been subtracted initially from the width of .grid. This is the difference between frs and %s that percentages don’t include the gutter that you define with grid-gap.

Here 3fr 200px 3fr is essentially equal to 1fr 200px 1fr.

Guess, that’s a lot for today :p  Will continue remaining in part two.

C# join tables using IQueryable in LINQ

Yesterday I was struggling with how to Join tables using IQueryable in C# or Asp.Net and return it in List. So, here I’m with the solution. Let’s start..

With the introduction of LINQ the difference between writing code for  accessing a list of data in an external data source like SQL Server is vanishing. With the introduction of .NET Framework 4.0 this has changed.In this post i would like to filter my SQL data employing 2 tables.

In my project I’ve 2 tables. 1: Containing all the basic user data like Full Name, DOB etc and 2nd containing user’s student id, card number and so on.. I’ve needed a Data like this: Full Name [Roll Number]

So, here’s the code

var query = (from a in DbInstance.User_Account
join s in DbInstance.User_Student on a.Id equals s.Id
where s.Status == 1
select new { a, s } into t1
select new
Id = t1.a.Id.ToString(),
Name = string.Concat(t1.a.FullName.ToString(), ” [“, t1.s.RollNumber.ToString(), “]”)

Convert currentTimeMillis to a datetime in JAVA(Spring Boot)

Spring Boot

In this tutorial I’ll show how to save Time Stamp in Database in currentTimeMillis and retrieve in Spring Boot

Want precise time for some purpose? Normally, we can save Time Stamp in Database but what if the data need to be converted into several formats?

Let’s say we need to save “2019-6-27 00:59:59” and then convert it to several formats like ’27/2019/6 00:59:59′ and ’20-JUN-1990 08:03:00′. Though “2019-6-27 00:59:59” can be converted but that’s a little bit tough. The ideal solution is to save the data in millisecond format. In millisecond format “2019-6-27 00:59:59” would be “1564167599000”

I assume you already have the datetime picker data in controller, here’s the conversion code:

String expireTime = model.attribute; //your model attribute or request parameter name
Date date = formatter.parse(expireTime);
Timestamp timestamp = new Timestamp(date.getTime());
String expireTime2 = String.valueOf(timestamp.getTime());
//That's it! We've converted '2019-6-27 00:59:59' to '1564167599000'
//Add your save logic

Now the reading part. User can’t read ‘1564167599000’, right? Let’s convert this to readable format:

String convertedExpireTime = "1564167599000";
//Create a calendar instance
Calendar calendar = Calendar.getInstance();
int mYear = calendar.get(Calendar.YEAR);
int mMonth = calendar.get(Calendar.MONTH);
int mDay = calendar.get(Calendar.DAY_OF_MONTH);
int mHour = calendar.get(Calendar.HOUR_OF_DAY);
int mMin = calendar.get(Calendar.MINUTE);
int mSec = calendar.get(Calendar.SECOND);
String readableFormat = mYear + "-" + mMonth + "-" + mDay + " " + mHour + ":"+ mMin + ":"+ mSec; // The value is now converted to 2019-6-27 0:59:59
//Add some logic

That’s all! We’re done!

If you’ve any confusion please let me know 🙂

How to query data out of the box using Spring data JPA by both Sort and Pageable

Spring Boot

Developing REST API? Clients wants both sort & pagination?

That’s quite simple btw!

Since last few hours was trying to add this simple feature my Spring Boot project. In my project pagination was done using pageable

In this tutorial I’m gonna show how to achieve this.

Let’s copy the code from below:

public List<Model> getAllData(Pageable pageable){
       List<Model> models= new ArrayList<>();
       return models;
//Model = Your Model where you want to implement this feature. 

That’s all! We’re done!
If you’ve any confusion please let me know 🙂

Show data from two JPA entity tables on same page using Spring Boot and Thymeleaf

spring boot thymeleaf bootstrap 4

Let’s say you want to display multiple table contents in Spring Boot project using Thymeleaf, JPA Entity and Model.

In my project I have mapped a relationship between the two entities I need to retrieve data from and am wondering how to display data from the two tables on list page. I’ve ‘category’ table and ‘product’ table like below:

Spring Boot, Thymeleaf Show data from two JPA entity tables on same page using Spring Boot and Thymeleaf

And in my controller I’ve list of both category and product in respective model. Here is the snippet:

model.addAttribute("products", productService.findAll());
model.addAttribute("categories", categoryService.findAll());

So, I’ve all the required data in the model and I can access them from Thymeleaf. Let’s copy the table code from below (N.B: I’ve used bootstrap table):

<table class="table table-striped table-bordered table-responsive" role="grid">
      <tr role="row" class="odd" th:each="product:${products}">
            <p th:each="category : ${categories}" th:if="(${category.id} == ${product.id})" th:text="${category.name}"></p>
         <td th:text="${product.name}">

It’ll produce something like this:

Spring Boot, Thymeleaf: Display data from two JPA entity tables on same page

That’s all! We’re done!
If you’ve any confusion please let me know 🙂