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 {
grid-template:
“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(), “]”)
}).ToList();

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();
calendar.setTimeInMillis(Long.parseLong(convertedExpireTime));
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<>();
       modelRepository.findAllByOrderByIdDesc(pageable).forEach(models::add);
       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">
   <thead>
      <th>Category</th>
      <th>Product</th>
   </thead>
   <tbody>
      <tr role="row" class="odd" th:each="product:${products}">
         <td>
            <p th:each="category : ${categories}" th:if="(${category.id} == ${product.id})" th:text="${category.name}"></p>
         </td>
         <td th:text="${product.name}">
      </tr>
   </tbody>
</table>

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 🙂

Thymeleaf select required not working?

thymeleaf

Since last few days trying to add select “required” attribute in my Thymeleaf project.  Neither of these works in Thymeleaf:

  • <select required=”required”>
  • <select required=’required’>
  • <select required=required>
  • <select required=””>
  • <select required=”>
  • <select required>

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

Let’s copy the code from below:

<select th:name="someName" class="form-control" id="someID" th:required="true">
    <option value="">Select Category</option>
    <option th:each="model: ${someModel}" th:value="${model.id}"
            th:text="${model.Title}"></option>
</select>

Please note that, first/default option value must be set to “” if you put “0” it won’t work!

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

Bootstrap Dynamic Modal with Spring Boot and Thymeleaf

spring boot thymeleaf bootstrap 4

Let’s say you want to dynamically create modal popup in your Spring Boot project using Twitter Bootstrap 4 to show the user a ‘warning popup’ before deleting a data or edit the contents on the fly in same page. Not to mention I’ve used Thymeleaf as my template engine.

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

I assume you have already included required Bootstrap resources and necessary jQuery library in your project and are ready to implement modal popup. Let’s copy the modal code from below:

<div class="modal modal-warning fade in" id="myModal">
 <div class="modal-dialog">
 <div class="modal-content">
 <div class="modal-header">
 <button type="button" class="close" data-dismiss="modal" aria-label="Close">
 <span aria-hidden="true">×</span></button>
 <h5 class="modal-title">Delete User</h5>
 </div>
 <div class="modal-body">
 <h3>Are you sure want to delete this user?</h3>
 </div>
 <div class="modal-footer">
 <button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Close</button>
 <a type="button" class="btn btn-danger"><i class="fa fa-check"></i>&nbsp;Yes</a>
 </div>
 </div>
 </div>
 </div>

It’ll produce something like this:

Bootstrap Dynamic Modal with Spring Boot and Thymeleaf

Now, the next step actually the final step. Make the modal dynamically generate for all the data in table.

I’ve some data in the table like below now I want to delete a user but before that I want that modal to generate dynamically for all data.

Bootstrap Table in Spring boot

On the ‘Red’ delete button the popup will generate.

<a data-toggle="modal" data-target="#modal-warning" th:attr="data-target='#modal-warning'+${user.id }"><span class="glyphicon glyphicon-trash"></span></a>

Here “${user.id}” is my thymeleaf object.

Now, let’s make the modal dynamic with the id:

<div class="modal modal-warning fade in" th:id="modal-warning+${user.id }" >
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span></button>
                <h5 class="modal-title">Delete User</h5>
            </div>
            <div class="modal-body">
                <h3>Are you sure want to delete this user?</h3>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline pull-left" data-dismiss="modal">Close</button>
                <a type="button" class="btn btn-outline" th:href="@{/user/delete/{id}(id=${user.id})}"><i class="fa fa-check"></i>&nbsp;Yes</a>
            </div>
        </div>
    </div>
</div>

Here “th:href=”@{/user/delete/{id}(id=${user.id})}” is your POST URL.
You can also edit any data inside the modal by adding a form.

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

Few Best Alternatives to Github

Being into software development we frequently find ourselves in need to host our code. For the purpose, crowds are blindly following one single medium for this, Github. It can’t be denied that Github users have their choice to use either Git or Subversion for version control. Conjointly there is a facility of unlimited public code repository for all users of Github. Another fascinating feature of Github is that allows to create ‘organizations’, which at its own is a normal account but at least one user account is required to be listed as the owner of the organization.

Apart from providing desktop application for Windows and OSX, Github also offers the facility to its users and organizations to host one website and unlimited project pages for free on the Github’s website.

Choosing a code repository hugely depends on what you require for a repository and how much can it cater to, if not all. Choosing a repository hosting service might not seem like a big deal. But the repo host you choose can have serious consequences for your developers’ productivity and ability to build great products.

1. Bitbucket

Bitbucket

The Bitbucket comes just next to it in terms of usage and global popularity. Bitbucket also provides a free account for the users and organizations as well with limit for five users. Also, it provides access to unlimited private and public repos. One of the features which is noteworthy is its allowance for the users to puch their files using any of the Git client/Git command line.

The domain for your hosted website on Bitbucket will look something like: accountname.bitbucket.org and domain for that of project pages will be like: accountname.bitbucket.org/project. On the other hand Bitbucket also allows its users to use their own domain name for their website.

2. GitLab

GitLab

GitLab’s sub-motto seems to be “Better than GitHub”, ironic for a project that is itself hosted on Github. One if its unique features is that you can install GitLab onto your own server. This gives you the option of using GitLab on a custom domain as well as with a custom host. GitLab also claims to handle large files and repositories better than GitHub. GitLab also lets users have unlimited public AND private repos for free. Also GitLab facilitates its users by providing automated testing and code delivery so that a user can do more work in lesser time without waiting for the tests to pass manually.

3. Beanstalk

Beanstalk

Beanstalk as another good Github alternative but it is not free. It lets you try it out for 2 weeks free of cost, after which you need to pay. Its cheapest package “Bronze” costs $15 and allows up to 5 users, 3 GB storage and a maximum of 10 repositories. Subversion and Git Version Control Systems are supported by Beanstalk.

4. Kiln

Klin

Kiln is a paid source code host developed by Fog Creek, unlike Github Kiln is not a free source to host your software or website. You can try Kiln (with all the bells and whistles) for 30 days trial period, after that users need to upgrade to the premium version (minimum $18 a month) in order to continue working with Kiln. You will need to pay separately for the Code Review Module. Overall, Kiln is more suited for medium to large organizations of 100 -500 people. You will need to pay separately for the Code Review Module. Overall, Kiln is more suited for medium to large organizations of 100 -500 people.
Kiln makes a domain for your company at companyname.kilnhg.com

5. Codeplane


Codeplane is again a paid service, which offers a 30 day free trial.

Codeplane’s VCS -of choice is Git. It allocates 2 GB for your repositories with no limits on users or number of repositories at $9 a month. Suitable for small companies and freelancing teams. Codeplane also automatically takes a backup of your repositories and stores them in the Amazon S3.

 

Comparison Table
Here is a complete comparison of all the features across all 8 source code hosts discussed in this article:

Features Github Bitbucket Gitlab Beanstalk Kiln Codeplane
Pricing* Free Free Free $15/mo $18/mo $9/mo
Private Repo Paid Unlimited, Free Unlimited, Free 10 Paid Unlimited, Paid
Public Repo Unlimited, Free Unlimited, Free Unlimited, Free 10 Paid Unlimited, Paid
Storage Limit 1GB per repo 2GB None 3GB None 2GB
Users Unlimited 5 & Unlimited if public Unlimited 5 5 Unlimited
VCS Git, SVN Git, Hg Git Git, SVN Git, Hg Git
Graphs Yes No Yes No No No
Web Hosting Static sites. Page generator Static sites Static No Yes No
Code Review Yes Yes Yes Yes No No
Wiki Yes Yes Yes No Yes No
Bug Tracking Yes (Login Required) Yes Yes Yes Yes Yes
Discussion Forum No No No $15/mo No No

Scope and this in JavaScript

Today I want to talk a little about “scope” in JavaScript and the this variable. The idea of “scope” is that it’s where certain variables or functions are accessible from in our code, & the context in which they exist & are executed in.

Have you ever seen something like this?

function someFunction() {
	var _this = this;
	something.on("click", function() {
		console.log(_this);
	});
}; And wondered what the var _this=this; is all about, hopefully this article should clear it all up. The first scope is Global Scope. This is very easy to define. If a variable or function is global, it can be got at from anywhere. In a browser, the global scope is the window object. So if in your code you simply have:
var x = 9; You’re actually assigning the property window.x to 9 (when working in a browser). You could type window.x = 9; if you like, but because it’s the global object you don’t have to. Properties on the global object can be accessed from anyplace in our code.

The only other scope we can have is the Local Scope. JavaScript scopes at a function level. For example:

function myFunction() {
	var x = 5;
};
console.log(x); //nothing will show in console

Since x was initialized within myFunction(), it is only accessible within myFunction().

Caution!

If you declare a variable & forget to use var keyword, that variable is automatically made global. So this code will work:

function myFunction() {
	x = 5;
});
console.log(x); //5

This is really a very bad idea. It’s considered bad practice to clutter the global scope. You should add as fewer properties as you possibly can to the global object. That’s why libraries such as jQuery often do this:

(function() {
	var jQuery = { /* all methods go here */ };
	window.jQuery = jQuery.
})();

Wrapping the whole thing in a function which is then immediately invoked means all the variables within that function are bound to the local scope. At the very end you can then expose all your methods by binding the jQuery object to the window, the global object. Although I’ve simplified it hugely, this is in essence however the jQuery source works.

That’s pretty much all there is too it at a basic level. Things get a bit complex once we take a look at the this keyword in JavaScript and how it works. I’m sure we’ve all come across this issue:

$("someLink").on("click", function() {
	console.log(this); //points to someLink(as expected)
	$.ajax({
		//ajax set up
		success: function() {
			console.log(this); //points to the global object. Huh?
		}
	});
});

this is a variable that is automatically set for you once a function is invoked. The value it’s given depends on how a function is invoked. In JavaScript we have limited main ways of invoking functions. I don’t wanna talk about them all today, but just the three ways most people use them; either when a function is called as a method, or on it’s own, or as an event handler. Depending on how a function is invoked, this is set differently:

function bar() {
	console.log(this); //global object
};

myapp = {};
myapp.bar = function() {
	console.log(this); //points to myapp object
}

var link = document.getElementById("someId");
link.addEventListener("click", function() {
	console.log(this); //points to link
}, false);

Those are all fairly obvious. The MDN has a nice explanation for the third & why this happens. Go through!

There are few other ways in which we can invoke functions by explicitly defining what the value of this should be, but as this has already ended up as a quite long article, I’m leaving those for another day. If you have any questions, please do leave a comment & I will get back to you.