Jul 12, 2019

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share this details with Client Applications which can be either PHP, HTML JavaScript, Angular, etc...

For This JWT (Jason Web Token) comes in handy as a Token to share with client and server. You can read more about JWT in there Website.

You can use below Jquery code to decode the given JWT Token and access the details in it.



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html>
<head>
    <title>JWT Token Decode Using Jquery</title>
    <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
</head>
<body>
    <h3> JWT Token Decode Using Jquery</h3>
    <form>
       <textarea rows="2" cols="50" id="token"></textarea>
       <br/>
       <input type="button" name="Decode" id="btnDecode" value="Decode">
       <br/>
       <textarea rows="10" cols="50" id="txtDecode"></textarea>
    </form>
 
    <script>
       $(document).ready(function(){
          $("#btnDecode").click(function(event){
             var token = $('#token').val();
             if(token == ""){
                $("#txtDecode").val("Please insert the Token");
             }else{
                var decodedToken = parseJwt(token);
                $("#txtDecode").val(JSON.stringify(decodedToken));
             }
          });
        });
  
        function parseJwt (token) {
           var base64Url = token.split('.')[1];
           var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
           var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
             return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
             }).join(''));

           return JSON.parse(jsonPayload);
        };
  
    </script>
</body>
</html>

I have used the below token to test this code.

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJNZW1iZXJJZCI6IjEiLCJNZW1iZXJOYW1lIjoi2YbZitmB2KfZhCDZhtiy2KfYsSIsIk1lbWJlckVtYWlsIjoiYWR2b3F1ZXNAZ21haWwuY29tIiwibmJmIjoxNTYyODU5MDcwLCJleHAiOjE1NjI5MzEwNzAsImlzcyI6IlN1a25hIiwiYXVkIjoiU3VrbmEifQ.A-v4D1u4HE1sKBDiZBTQ79WAkLVNnAcKrURRDkLv7bQ

This how it looks like. Hope you also got it correct.




Jul 11, 2019

Adding Content Pickers To Umbraco 8

In my previous article I setup the Umbraco CMS. Lets see how we can add content pickers. So we can give clients to change content as they wish. 

Things I'm going to do in this articles.
1. Add a Text Field to get the First Name
2. Add a Numeric Field to get the Age
3. Add a Media Picker to get the Profile Image

Login to the Umbraco and click on "Settings" on the top menu.

Step 1
Create a Document Type. You can read more in Umbraco Documentation.
In the side menu you will see Document Types.
Right click on it and select first option "Document Type".
Click on "Add Property".
Give a name for the property.
Click on "Add editor".
Select a editor as you want.
Then click save.



Step 2
You will there is a template created for home. Now lets see how we can access the document type in it.



Step 3
Lets create a page for home.
Click on Content on the top menu.
Move the mouse to top of Content.
Click on the three dots(...).





Step 4
Select the Home template. Then you will get the content form. Fill it as you wish. Then click Save and Publish.





Step 6
Lets design the home page.
Add the below code.






 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
@inherits Umbraco.Web.Mvc.UmbracoViewPage<ContentModels.Home>
@using ContentModels = Umbraco.Web.PublishedModels;
@{
 Layout = null;
 var profileImage = Model.Value<IPublishedContent>("profileImage").Url;
}

<h4>My Profile</h4>
<img src="@profileImage">
<br/>
First Name : @Model.Value("firstName")
<br/>
Age : @Model.Value("age")
<br/>

Lets see what we get in the browser.




Setting Up Umbraco 8 Using NuGet Package Manager

Umbraco is the leading Open Source Microsoft ASP.NET Content Management System. I'm not going to explain about Umbraco here, because you are reading this article after knowing Umbraco. If not please refer this link to Umbraco Web Site.

In order to set up Umbraco you need to Visual Studio. If you have not installed already download and install Visual Studio Community Edition.  It's free.

Lets get into work.


Step 01
Open Visual Studio and Create a New ASP .NET Web Application. Make sure you select the Framework as .NET Framework 4.7.2. This is latest framework version  is supporting right now in July 2019 for Umbraco 8. Give any name as you wish for the Project name. In my case I'm naming it as MyWebiste.



Step 02
Select the Template as Empty, because we don't need anything, even authentication.




Step 03
Right click the project file and click on the Manage NuGet Packages option. You will prompt to below screen. type "UmbracoCms" in the Browse section and click the install button.




Step 04
You will get the below prompt and ask to Accept the license. Click on I Accept as we want to install these packages.





Step 05
It will take sometime to install the umbraco cms to our project. If all went well you will get the below screen with success message.





Step 06
Now click on the run button on the visual studio. Then you will get the below prompt asking the Debugging mode or not. Initially we don't need any debugging because we are not planing to do so. Press OK. then you will get the Umbraco Set Up page in browser.





Step 07
Fill these details as you wish. Then click Customize button. We need to customize few things.





Step 08
Next is you will get below screen. Click on "I don't want a custom Machine Key".





Step 09
Click continue. In my case I'm not going to point to any external database.  It's going to SQL Server Compact by default.





Step 10
After that you will get below screen. Click "No Thanks ..."





Step 11
Now give the Email and Password, which you gave in the first page.





Step 12
Now Everything is okay. Your Umbraco CMS is ready to use.






Hope everything went well. Check my next article adding content pickers.


Jan 29, 2019

C# Convert 24 hour format to 12 hour format in English and Arabic

I was writing a Web API to return a Time in both English and Arabic. My expectation was really simple. In my database table I had time as 24 hour format. So I wanted to return it in 12 hour format both in English and Arabic. Lets see what it looks like.

Start Time in 24 hour format(Database): 1130
End Time in 24 hour format(Database): 1430
12 hour format in English : 11:30 AM - 02:30 PM
12 hour format in Arabic:  Ù… 02:30 - ص 11:30

To Convert to English is very straight forward.


1
2
3
4
5
6
7
private string Convert24To12HourInEnglish(string pStartTime, string pEndTime)
{
    DateTime startTime = new DateTime(2018, 1, 1, int.Parse(pStartTime.Substring(0, 2)), int.Parse(pStartTime.Substring(2, 2)), 0);
    DateTime endTime = new DateTime(2018, 1, 1, int.Parse(pEndTime.Substring(0, 2)), int.Parse(pEndTime.Substring(2, 2)), 0);

    return startTime.ToString("hh:mm tt") + " - " + endTime.ToString("hh:mm tt");
}


But when it comes to Arabic you need to format little. because when you add an Arabic text its automatically format to Right to Left(That's how Arabic language reads). 

We need to tell the string that we concatenate Left to Right using ((Char)0x200E).ToString()

Lets see how we can achieve that.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
private string Convert24To12HourInArabic(string pStartTime, string pEndTime)
{
    DateTime startTime = new DateTime(2018, 1, 1, int.Parse(pStartTime.Substring(0, 2)), int.Parse(pStartTime.Substring(2, 2)), 0);
    DateTime endTime = new DateTime(2018, 1, 1, int.Parse(pEndTime.Substring(0, 2)), int.Parse(pEndTime.Substring(2, 2)), 0);

    pStartTime = startTime.ToString("hh:mm tt");
    pEndTime = endTime.ToString("hh:mm tt");

    var lefttoright = ((Char)0x200E).ToString();
    string formattedText = (pEndTime.IndexOf("AM") > 0 ? "ص" : "م") + lefttoright + endTime.ToString("hh:mm") + " - " + (pStartTime.IndexOf("AM") > 0 ? "ص" : "م") + lefttoright + startTime.ToString("hh:mm");

    return formattedText;
}


That's it. now you have the two methods to Convert 24 Hour format time to 12 Hour format time in both English and Arabic.

Aug 12, 2018

Ionic 4 Working With Modal Popup


In this article I'm going to show you guys, how we can open a Modal Popup in an Ionic Application and How we can pass values to that popup.

Lets start it with a Ionic Blank Application. 


1
Ionic start AppModal blank

This is the current folder hierarchy.




Now lets add a text field and button to home screen. The text we enter to the text field will pass to the Modal Popup when we click the button. Lets  add this simple html code to create the UI. I have button click event "onShowGreetingsClicked()" to open the popup.


home.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<ion-header>
  <ion-navbar>
    <ion-title>
      Easy Code Stuff
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <ion-label floating>
      First Name
    </ion-label>
    <ion-input type="text" [(ngModel)]="firstName"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label floating>
      Last Name
    </ion-label>
    <ion-input type="text" [(ngModel)]="lastName"></ion-input>
  </ion-item>
  <ion-item>
    <button ion-button full color="primary" type="button" (click)="onShowGreetingsClicked()">
      <ion-icon name="checkmark"></ion-icon>&nbsp;&nbsp;Show Greetings</button>
  </ion-item>
</ion-content>


home.ts
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  firstName: string = '';
  lastName: string = '';

  constructor(public navCtrl: NavController) {

  }

  onShowGreetingsClicked(): void {
    console.log('clicked');
  }

}


Lets see how out application looks like using below command. 


1
Ionic Serve



Now lets add Page Called ModalGreeting using Ionic CLI.


1
ionic generate page ModalGreeting --no-module


Now this is the current folder hierarchy.




This is the sample code I'm getting it when I generate the page form Ionic CLI.

modal-greeting.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<ion-header>

  <ion-navbar>
    <ion-title>ModalGreeting</ion-title>
  </ion-navbar>

</ion-header>

<ion-content padding>

</ion-content>





modal-greeting.ts

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

@Component({
  selector: 'page-modal-greeting',
  templateUrl: 'modal-greeting.html',
})
export class ModalGreetingPage {

  constructor(public navCtrl: NavController, public navParams: NavParams) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ModalGreetingPage');
  }

}


Now lets pass the First Name and Last Name values to the Modal Popup and show it when we click the button.

Now lets see how our final code looks like.


app-module.ts
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ModalGreetingPage } from '../pages/modal-greeting/modal-greeting';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    ModalGreetingPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    ModalGreetingPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

home.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<ion-header>
  <ion-navbar>
    <ion-title>
      Easy Code Stuff
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-item>
    <ion-label floating>
      First Name
    </ion-label>
    <ion-input type="text" [(ngModel)]="firstName"></ion-input>
  </ion-item>
  <ion-item>
    <ion-label floating>
      Last Name
    </ion-label>
    <ion-input type="text" [(ngModel)]="lastName"></ion-input>
  </ion-item>
  <ion-item>
    <button ion-button full color="primary" type="button" (click)="onShowGreetingsClicked()">
      <ion-icon name="checkmark"></ion-icon>&nbsp;&nbsp;Show Greetings</button>
  </ion-item>
</ion-content>


home.ts
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import { Component } from '@angular/core';
import { NavController, NavParams, ModalController } from "ionic-angular";
import { ModalGreetingPage } from '../modal-greeting/modal-greeting';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  firstName: string = '';
  lastName: string = '';

  constructor(
    public navCtrl: NavController,
    public navParams: NavParams,
    public modalCtrl: ModalController
  ) {

  }

  onShowGreetingsClicked(): void {
    let modal = this.modalCtrl.create(ModalGreetingPage, {firstName: this.firstName, lastName: this.lastName});
    modal.present();
  }

}


modal-greeting.html
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<ion-header>

  <ion-navbar>
    <ion-title>Easy Code Stuff Greeting</ion-title>
  </ion-navbar>

</ion-header>

<ion-content padding>
  Hello {{firstName}} {{lastName}}
</ion-content>


modal-greeting.ts
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

@Component({
  selector: 'page-modal-greeting',
  templateUrl: 'modal-greeting.html',
})
export class ModalGreetingPage {
  firstName: string = '';
  lastName: string = '';

  constructor(public navCtrl: NavController, public navParams: NavParams) {
    this.firstName = navParams.get("firstName");
    this.lastName = navParams.get("lastName");
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad ModalGreetingPage');
  }

}


Now lets see how our application looks like.








Hope you follow it up. See you again on next article.

Running Ionic 4 Application On Android Device

Hi Guys, hope you all followed my previous article about Getting Started With Ionic. Lets see how we can test this simple application in an Android Device.

First of all what you have to do is setup the environment. 

Step 1 : Install Java Development Kit. I have an bit old article about setting up the java environment.


Step 2 : We should install the Android SDK. You can simply download and install Android Studio.


Step 3 : In order to test and configure it on Android Device, you may need to configure Gradle Daemon. Without going into much details or over confusing you can simple achieve this by creating a sample android project in Android Studio and adding few target SDks.


Step 4 : Run the below command to add the android platform.


1
ionic cordova platform add android

This command will take few minutes depending on your internet connection. if everything goes correct you will get below output.



Step 5 : Lets build it for Android using below command.


1
ionic cordova build android

If everything goes correct you will get below output.






Step 6 : That's all you have to do. Copy the APK file to Mobile Device from the folder location shown in the output. 


Step 7 : Click on the APK file in the mobile device. You will get the below message, because we are trying install an APK which is not fully trusted APK with google agreements. For now we only need to run this on our device. In my case I'm trying it on my Samsung Galaxy S6.





Step 8 : Click Settings.





Step 9 : Then click on the Unknown Source Toggle button.





Step 10 : Then press OK




Step 11 : Then Press Install



If everything went well you will get the following message.


Step 12 : Then click open. You will see your application in mobile.



Hope you follow it up. Read my next article about Working With Ionic Modal Popup.

JWT Token Decode Using Jquery

When it come to authentication we use many mechanism. Ones the user authenticated we must keep these details somewhere safe. So we can share...