Wednesday, September 28, 2022

Pagination using CSS and JQuery Javascript

Hello everyone, we all know how often we have requirement for implementing pagination in a website. As soon as we have this kind of requirement, we often try to go for either JavaScript or jQuery-based solutions. The most basic solution which we get from internet is using third party plugins to achieve those things. For example, we want to implement pagination when we are having large number of records to display, we can go for jQuery DataTables as it provides flexible and powerful functionality to implement the same. But have you wondered how we can implement the pagination without these third-party plugins by simply using CSS and jQuery?

If not, then please read the blog to see how we can do it.

Let’s go straight to the point and see the implementation for the same. I am using normal HTML, CSS, and jQuery for the same.

Let’s first create the Html structure showing the List of items. We will see the explanation step by step.



       
  • Coffee
  • Tea
  • Milk
  • Protien
  • Shake
  • Juice
  • Coke

As you can see the Html structure. Its plain simple structure where we are having simple some data in list format.

Now let’s move to the next part where we will implement pagination logic using jQuery with help of some CSS classes.

Now to our current html structure lets add some more html and respective classes which will be used in jQuery logic for the implementation part. First let add class = “related-pagination” to all our li elements. Add current html <div id="page_navigation"></div> just before body closing tag. Add attributes class = "parent-pagination-count" id = "current_page" data-count="2" to parent div element of ul tag. Add jQuery reference to head section of the Html. Now updated Html structure will look like below one.


Its time to see the jQuery required for implementing the pagination. Add script section before end of body tag. Let’s see what is there inside our script. There are few important functions which needs some attentions.

showPage(): This function takes care of hiding the runtime created pagination html structure based on number of count on which the pagination will happen. It also takes care of showing the list of elements based on page size defined. Internally this function calls the makePager(page) function which take the page number to create the require pagination html structure runtime. At first load the 1 is pass as page value to showPage() function which assign current_page value as 1.



makePager(page): This function take care of creating all the required html structure for the pagination. It takes the page value as input parameter to create the required html structure for pagination. When someone click on next button or any other pagination button, the corresponding int value is store in current_page. This current_page is the id of the parent div of ul element. The current_page is nothing but the value of the pagination number to hide show the list item respectively.







There are other functions like next, previous, first and last button in pagination. If you see the code for the same, they are internally calling showPage() function which internally call the makePager() function to create the html structure.








The logic is totally based on hide and show of an element. Based on current_page number which gets its value when we click on pagination numbers do the logic of hiding and showing the list content items. The whole component of pagination is created dynamically by jQuery. Once you have included all this code you will get the below html view based on the page-size define. The data-count property hold the page-size.








Below is the full code Snippet for your reference.


         document.addEventListener('DOMContentLoaded', function (event) {
             makePager = function (page) {
         		 var show_per_page = jQuery(".parent-pagination-count").data("count");
                 var number_of_items = jQuery('.related-pagination').length;
                 var number_of_pages = Math.ceil(number_of_items / show_per_page);
                 var number_of_pages_todisplay = number_of_pages;
                 var navigation_html = '';
                 var current_page = page;
                
                 if (current_page != 1) {
                     navigation_html += "<a class='nextbutton' href=\"javascript:first();\">« Start 
                     </a> <a class='nextbutton' href=\"javascript:previous();\">« Prev </a> ";
                 }
                 
                var pages = number_of_pages_todisplay;
         	   for(var i=1;i<= pages;i++)
         	   {
         		  navigation_html += "<a class='" + ((i == current_page) ? "currentPageButton" : "numericButton") + 
                  "' href=\"javascript:showPage(" + i + ")\" longdesc='" + i + "'>" + (i) + "</a> ";
         	   }
         	   if (number_of_pages > current_page){
                     navigation_html += "<a class='nextbutton' href=\"javascript:next()\">Next »</a> 
                     <a class='nextbutton' href=\"javascript:last(" + number_of_pages + ");\">Last »</a>";
                     //navigation_html += "<a class='nextbutton' href=\"javascript:next()\">Next</a>";
                 }
                   jQuery("#page_navigation").html(navigation_html);
             }
             var pageSize = jQuery(".parent-pagination-count").data("count");
             showPage = function (page) {
                 jQuery(".related-pagination").hide();
                 jQuery('#current_page').val(page);
                 jQuery(".related-pagination").each(function (n) {
                         if (n >= pageSize * (page - 1) && n < pageSize * page)
                             jQuery(this).show();
                 });
                 var totalresultcount = jQuery('.related-pagination').length;
                 if (totalresultcount < pageSize) {
                     jQuery("#page_navigation").hide();
                 } else {
                     makePager(page);
                 }
                 
                }
                showPage(1);
                next = function () {
                     new_page = parseInt(jQuery('#current_page').val()) + 1;
                     showPage(new_page);
                 }
                 last = function (number_of_pages) {
                     new_page = number_of_pages;
                     jQuery('#current_page').val(new_page);
                     showPage(new_page);
                 }
                 first = function () {
                     var new_page = "1";
                     jQuery('#current_page').val(new_page);
                     showPage(new_page);    
               }
                 previous = function () {
                     new_page = parseInt(jQuery('#current_page').val()) - 1;
                     jQuery('#current_page').val(new_page);
                     showPage(new_page);
               }
         	  
         });

Note: This is only intended for learning purpose. For large number of list item this is not recommended one as the pagination logic should happen at backend system instead of handling at front-end level.

Thanks everyone and please feel free to comment. See you in next blog with something new.

Happy learning.

Sunday, October 15, 2017

RestFul Web Service

Hello Everyone, I am back with a new blog on REST services and how we can make a restful service with prior knowledge of WCF service in .Net.
Lets try to understand what is REST service and how it is better than WCF service

Overview:
REST stands for Representational State Transfer is an architectural style of building services that can support a large number of network based applications. It uses HTTP verbs to perform CRUD operations. As it follows HTTP protocol it is stateless in nature.

Following are the HTTP verbs used in REST architecture:
1. GET : It retrieves the collection of resources. It is similar to READ operation
2. POST :  It create a collection of resources. It is similar to CREATE operation
3. PUT : It replaces the entire collection of resources with new one
4. PATCH: It replaces the specified resources in the collection. It is similar to UPDATE operation
5.DELETE: It removes the resource from collection. It is similar to DELETE operation

So let's see how we can use WCF knowledge to build a REST service

Step 1:
Go to Visual Studio-->File-->New Project-->WCF Service Application
Once you selected the template give it a name  it will generate a Project for you. In this case i have given a name of Demo Service

Step 2:
Once the project is created it will generate 2 file as
1. IService.cs
2. Service.svc.cs

Let's see What is IService.cs file
IService.cs : This is the interface file that has all the operation contracts that a service is going to exposed to its clients. It means that it exposes all the methods that the service offers to its end users.


As we can see, our operation contract has some extra attributes on it. Let's try to understand what this attributes are:
1. WebInvoke : This attribute specifies how your service will expect service calling from clients to perform operations on resources, It has several parameter and we will discuss them one by one

  • Method: What type of HTTP verb it is expecting i.e. GET,POST,PUT,PATCH or DELETE
  • RequestFormat: The format of the request made to the service. It can be either JSON or XML 
  • ResponseFormat: The format of the response from the service to end user. It can be either JSON or XML
  • UriTemplate: The Uniform Resource identifier i.e. the identifier of the operation contracts. If URI is initialized then the calling URL must contain the URI initialized string 
Note: This attribute is present in System.ServiceModel.web namespace and it is must to be used in REST service

2. WebGet: This attribute is only used for retrieving any resource

Step 3:
Service.svc.cs file:
This file contain the actual implementation of our operations contracts. This file implements the IService.cs file


In this demo Service we are returning a employee resource whenever a GET call is received. 

Step 4:
Web.config file:

Here the binding that is used is WebHttp binding . Almost everything is similar to WCF service configuration except Binding. 

Once completed just right click the Service.svc.cs file and click browse option. Below are the screenshot after browsing


WSDL document


Output:

JSON Format:


XML Format:

Hoping everyone must have understood how we can use WCF service template to make a REST service.
Thanks everyone and Happy coding!!!!



Saturday, May 13, 2017

RSA With Certificates

Hello everyone.In last blog we have seen how RSA encryption technique practically works. We generated the public-private key pair from CryptoServiceProvider class present in .Net framework but in real world we never use the key generated from this class. The reason behind this is every time whenever your application using RSA implementation is fired, there will be a new pair of key generated and it will not use old key pair. Imagine a scenario where the public key need to be stored in database.In such case every time a new key pair is generated you have to store that in database overriding the previous one. Also generating keys from this class has some drawbacks.

Drawbacks:
1. Overhead of overriding the newly generated key-pair in database each time the application is fired
2. Padding problem
3. If using cross platform encryption-decryption (e.g. encryption in .Net and decryption in java or vice-versa) then encoding,padding,mode etc are the issues which can be encountered.

To avoid this one should always use Certificates for generating public-private key pair. It has lots of advantages as compared to old mechanism.
Consider a real world scenario where you want to make a payment through Credit card. The client need to pass Credit card details along with some other information to the application that will make the payment. The client application is built in .Net and the receiver application is built in Java. As we all know that credit card details are vulnerable to be hacked so we will protect them using some mechanism while passing it through network. We might use any encryption technique to hide the original details or masking the value. In such case if we are using RSA encryption technique then cross platform encryption decryption becomes a serious problem as we have discussed above.

So to overcome this type of scenario one can install certificates on both client and receiver machine. This will automatically adjust all padding, mode and encoding related issue while using cross platform encryption decryption process.

In this blog, we will discuss that the receiver has the public private key pair generated from Certificates.He is providing the public key in string format so that we can easily stored that key in database and whenever required we can access that public key from our database and can use it for encryption.

But as we seen in last blog that to use encrypt inbuilt function one has to convert the key in string format to key in XML string format. After that only we can pass that key for encryption purpose.

So we will see how to convert a key in string format to key in xml string format through code:

For local use of RSA encryption we can use key generated from .Net inbuilt class. If you this key is stored in string format in database and you need to convert it to XML string format then use below code



Similarly if the key is generated from certificate and you want to convert it to XML string format then use below function












Note: To use above function for certificate import below namespace in your code:

  • System.Security.Cryptography.X509Certificates
And rest of the procedure is similar to encrypt and decrypt as seen in previous blog.

RSA implementation : RSA-Implementaion
Thanks for reading and feel free to leave your feedback.

Friday, May 5, 2017

RSA-Implementation

Hello everyone. Here I am back with my second blog. In last blog we discussed what is Asymmetric encryption and what are it's type. We discussed RSA encryption technique with its mathematical computation in detail. So in today's blog, we will discussed how to use RSA encryption technique in real world.

I will use VS 2012 with .Net framework 4.5 to demonstrate the code.

I am going to make a windows form application for demonstrating purpose. Follow below steps to make windows form application:
1. Open VS 2012
2. Select a new windows application project i.e.(File->New project -> Windows application template) and give it a meaning full name.

Add a class file to the solution and name it as encryption
Import below namespaces in Form.cs and encryption.cs file
  • System.Security.Cryptography: This class will provide us the access to utilize inbuilt RSA encryption function.
Now add two buttons and three text boxes to the form. Below is the design of the form












In Form.cs file declare the variables that are required. Please refer below code




Now to generate the public-private key pair use below code. Place this code in encryption.cs file










Let us look at above code what it's exact functionality:
  • rsaEncryptionPadding: This is used to specify whether we required padding in the data which we need to encrypt.We will see the significance of this Boolean variable below.
  • RSACryptoServiceProvider: This class is present inside System.Security namespace. This class help us to generate both public and private key.
  • keySize: This is size of the key defined by the user. It can be 128 or 256 bytes.We will see below what maximum key size can be assign to RSACryptoServiceProvider class
  • publicKey: This variable is used to hold the public key in xml string format
  • privateKey: This variable is used to hold the private key in xml string format.
We will discuss why it is in xml string format below ?

 Public key:












Private Key:











In code behind file of encryption button paste below code:







In above code we are just taking the input from the user and storing it in plaintext variable. Then we are calling GenerateKeys method by passing it the above shown parameters. This method generates the public-private key for us. Then with the help of public key we are calling the Encrypt function present in encryption.cs file.

Note: You can place all these code inside the form.cs file also. I have separated it to make code more understandable.

Encryption Functionality:

Place the below code in encryption.cs file
















Let us take a look at above code:
GetMaxDataLength(): This function is used to check the length of the data after it is converted into bytes. The maximum bytes which RSA support is 245 bytes if padding is not applied or else 215 bytes if padding is applied. We have specified above the padding variable.

IsKeySizeValid(): This function is used to check whether the key size specified by the user is valid or not.
It is a good practice to use both these functions whenever you are using RSA encryption.

















RSACryptoServiceProvider.Encrypt(): This is the .net inbuilt encryption method to encrypt plain text. This method takes the public key in xml string format only. This was the reason why we converted our public-private key into xml format.To this method we pass the data along with specifying padding or not. Always keep in mind that this method accepts data in byte format.

Decryption functionality:

In code behind file of decrypt button place below code






And in encryption.cs file place below code















The logic is same as encryption but we are using private key for decryption purpose.

Output:















So guys, hopefully you have understood how to code RSA encryption programmatically. In my next blog we will discuss how to use a key generated from Certificate. We will also cover how to convert that generated key into xml string format. Have a nice day.
Bye!!!!!

Sunday, April 30, 2017

Asymmetric Encryption

Hello Guys. This is my first blog and I am really excited and looking forward to it. As we all know that, it is a need of IT world to protect their confidential data from malicious users while passing it through network.
There are many techniques which prevents the data from malicious users. One of the way which we are going to discuss in this blog is using Encryption technique.

Basic Overview:
Encryption : Encryption is the process of converting a simple text into some-kind of text(i.e Cipher text) that an unauthorized person will not be able to figure out the real text.

There are two types of encryption techniques:
1. Asymmetric Encryption
2. Symmetric Encryption

We are mostly going to discuss Asymmetric encryption technique in great detail.

Asymmetric Encryption:
It is the encryption technique which use a pair of public-private key. The sender will encrypt the data using public key and the receiver will decrypt the encrypt text using the private key.




We are going to use RSA encryption technique which is one of the asymmetric encryption technique for encrypting the text. RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman who first publicly described it in 1978. The algorithm was named after these three scientist.

The mathematical computation for RSA algorithm:
1. Choose two prime number p and q
2. Multiply both prime number and assign it to n
3. Now compute  φ(n)= (p-1)*(q-1)
4. Choose e such that it should satisfy the expression 1<e<φ(n) and e and φ(n) are co-prime
5. Compute d such that (d*e) % φ(n) = 1
6. Public key is (e,n)
7. Private key is (d,n)
8. Let m be the message to be encrypted
    Cipher text C = (m^e) % n
9. Decipher Text m= (C^d) % n

Example:
Let two prime number be p=3 and q=11
n= p*q = 3*11=33
φ(n) = (p-1)*(q-1)=(2)*(10)=20
let e = 7 which co-prime to  φ(n)
let d=3 which satisfy the equation (d*e) % φ(n) = 1 i.e.[ (3*7) % 20 = 1]
Public key is (e,n) = (7,33)
Private key is (d,n) = (3,33)
Let m = 2 be the message to be encrypted.
Let C be the cipher text
Encrypted message C =  (2^7) % 33 = 29
Decrypted message m = (29^3) % 33 = 2

So guys, hopefully you have understood how RSA encryption algorithm computationally works. In next blog i will try to demonstrate how it is practically use in real world.

Pagination using CSS and JQuery Javascript

Hello everyone, we all know how often we have requirement for implementing pagination in a website. As soon as we have this kind of requirem...