Quick Reference – Ionic CLI Commands

In this post we will see some common Ionic CLI commands for Ionic app development.

Install Ionic CLI globally

Install Ionic CLI globally with npm.

npm install -g @ionic/cli

Ionic help

Get Ionic help.

ionic --help
ionic <command> --help
ionic <command> <subcommand> --help

Create a new Ionic Project

ionic start <name> <template> [options]

This command will create a new Ionic project.

Examples

ionic start
ionic start myapp
ionic start myapp tabs --type=angular

Build Ionic Project

ionic build [options]

ionic build will generate web assets for the Ionic project.

Examples

ionic build
ionic build --prod
ionic build --watch

Add Capacitor platform(s) to Ionic project

ionic capacitor add <platform>

ionic capacitor add will add Android or iOS Capacitor platform to the Ionic project.

Examples

Add Android

ionic capacitor add android

Add Ios

ionic capacitor add ios

Ionic Build for Android or iOS

ionic capacitor build <platform> [options]

ionic capacitor build will do the following:

  • Perform ionic build
  • Copy web assets into specified native platform.
  • Open IDE for native project, Xcode for iOS, Android Studio for Android.

Following command will ask user to select platform Android or iOS.

ionic capacitor build

Build for android

ionic capacitor build android

Build for iOS

ionic capacitor build ios

Open project in Android Studio

ionic capacitor open android

Copy web assets to native platforms

ionic capacitor copy [<platform>] [options]

ionic capacitor copy will do the following:

  • Perform ionic build, which compile web assets.
  • Copy web assets to Capacitor native platform(s).
  • This command will not open the IDE for respective platform.

Open IDE for a given native platform

ionic capacitor open <platform> [options]

This command will open the IDE for native project (Xcode for iOS, Android Studio for iOS).

Run Ionic project for platform

ionic capacitor run <platform> [options]

ionic capacitor run will do the following:

  • Build the ionic project.
  • Run the project in emulator (tested for Android).

Build and Copy project and then update native platform

ionic capacitor sync [<platform>] [options]

ionic capacitor sync will do the following:

  • Perform ionic build, which will generate web assets.
  • Copy web assets to Capacitor native platform(s).
  • Update Capacitor native platform(s) and dependecies.
  • Install and discovered Capacitor or Cordova plugins.

Examples:

For android

ionic capacitor sync android

For iOS

ionic capacitor sync ios

Update Capacitor native platforms, install Capacitor/Cordova plugins

ionic capacitor update [<platform>] [options]

ionic capacitor update will do the following:

  • Update Capacitor native platform(s) and dependencies.
  • Install any discovered Capacitor or Cordova plugins.

Generate Icons for Capacitor project

cordova-res <platform> --skip-config --copy

Reference npm package

https://www.npmjs.com/package/cordova-res

Expected project structure

resources/
├── icon.png
└── splash.png
config.xml
  • resources/icon.(png|jpg) must be at least 1024×1024px
  • resources/splash.(png|jpg) must be at least 2732×2732px
  • config.xml is optional. If present, the generated images are registered accordingly

Conclusion

In this tutorial we learned what are the common commands for Ionic project development.

Debug NodeJS TypeScript Using Visual Studio Code

Let’s see how we can configure our NodeJs project with TypeScript in Visual Studio Code for debugging.

Following are the steps:

Create project folder

Create project folder from the command prompt.

mkdir counter

Switch to project.

cd counter

Initialize project with npm package.json

npm init -y

Install TypeScript

npm i typescript --save-dev

Create tsconfig.json file

npx tsc --init --sourceMap --rootDir src --outDir lib

Here our source folder is src and output folder is lib.

Open the project in VS Code.

code .

You will see the project structure like this in VS Code.

and tsconfig.json file with specified options.

Add TypeScript source file

Create source code folder src, we specified the src as root folder in configurations.

And add file index.ts, with some code.

Create tasks.json file

Press Ctrl+Shift+P

Select Tasks: Configure Default Build Task

Then select tsc:watch – tsconfig.json

This will create a tasks.json file in .vscode folder.

Now build project, press Ctrl+Shift+B

This will generate the lib folder, which is our output directory.

and because of watch configuration build will keep running in the background and watch file changes.

Create launch.json file

Click on debug > create a launch.json file.

Choose node.js from options.

This will create a launch.json will

Finally Debug

Now go to your source file you want to debug, and press F9 on line you want to add a breakpoint.

Hit F5, and execution will pause at the breakpoint.

Congrats! you are able to debug your TypeScript now in VS Code.

Shortcut keys for debugging in VS Code.

  • Continue (F5)
  • Step Over (F10)
  • Step Into (F11)
  • Step Out (Shift+F11)
  • Restart (Ctrl+Shift+F5)
  • Stop (Shift + F5)

Conclusion

In this tutorial we learned how we can configure NodeJs TypeScript project in VS Code for easy debugging.

We have also seen what are some of the shortcut keys for quick debugging.

Please share your feedback or any query you have.

Firebase | Testing Firebase Cloud Function Locally with Cloud Function Emulator

Firebase CLI provides a cloud function emulator which can be used to run the Firebase Cloud Function locally before deploying to production. Following are the types of functions which can be emulated.

  • HTTP functions
  • Callable functions
  • Background functions triggered from Authentication, Realtime Database, Cloud Firestore, and Pub/Sub.

We will test a simple http function which we created in the last post.

Creating a Cloud Function Using Firebase CLI and TypeScript.

Following are the steps we will follow:

Install or Update the Firebase CLI

Firebase emulator is included in Firebase CLI, so we need to install it, or update it to the latest version.

npm install -g firebase-tools

Setting Up Admin Credentials for Emulated Functions

If your cloud function requires interaction with Google API or Firebase API via the Firebase Admin SDK then you may need to setup the admin credentials.

Go to the Service Accounts in Google Cloud Platform, under your project.

Select the service account row with Name “App Engine default service account“, and click on Actions button at the right end.

Select Manage Keys.

Click on Add Key drop down button.

Select Create new key.

This will open a modal window.

Choose JSON, from the available key types. This will generate and download the key in json file with key details.

JSON key file will look like following, values are omitted here.

{
  "type": "",
  "project_id": "",
  "private_key_id": "",
  "private_key": "",
  "client_email": "",
  "client_id": "",
  "auth_uri": "",
  "token_uri": "",
  "auth_provider_x509_cert_url": "",
  "client_x509_cert_url": ""
}

Set Google Application Credentials to the JSON file path.

This is required to authenticate to Google API or Firebase API from Firebase Admin SDK.

Execute following from project’s root directory.

set GOOGLE_APPLICATION_CREDENTIALS=path\to\key.json

Run the Firebase Emulator

Now we are ready to start the emulator.

Start the emulator by following command

firebase emulators:start

Emulator will be started and will provide you the function URL.

Call Function URL

Click on provide function URL, and you will receive the response from your function.

Great! We are able to run function locally.

Firebase Emulator UI

You will also be presented with Emulator UI URL.

Open the emulator UI URL in the browser.

In the Emulator screen you will be able to see all the different types of emulators.

You can navigate to Logs, to see any logging by function.

Modify and Test Local Cloud Function

Now let’s update the function.

Change the function response message.

Build the function again, and execute the following from functions folder.

npm run build

Reload the function URL provide by the running emulator and you will see updated response from local function.

When you are happy, you can deploy the function to Firebase as explained in this post.

Firebase | Creating a Cloud Function Using Firebase CLI and TypeScript

Conclusion

The Firebase emulator, which is included in the Firebase CLI, let’s us test the function locally before deploying to the cloud.

In this post we started with installing Firebase CLI and then we setup the Google Account Credential. Google Account Credential requires a JSON file with private key, which was generated in the Google Cloud Platform. Then we started the Firebase emulator and browsed the local function URL and received response from the local function.

Hope you liked this, please share your feedback or any query.

Firebase | Creating a Cloud Function Using Firebase CLI and TypeScript

Overview

Firebase cloud functions let’s you run a piece of code in cloud without managing the servers. This is quite helpful when you just want to manage your code and not to worry about the servers executing the code. This pattern is also known as serverless architecture.

These cloud functions can be triggered by multiple events such as an http request, scheduled time or in response to changes in Realtime Database and perform the intended job.

In this post we will see how we can create a simple Firebase cloud function using Firebase CLI and then deploy it to Firebase. We will use TypeScript to write the function.

Steps for creating the Cloud Function

Let’s create and deploy a Firebase cloud function.

Installing Firebase CLI

Firebase cloud functions are created and deployed using Firebase CLI, so let’s install the Firebase CLI globally. Type following command on command prompt.

npm install -g firebase-tools

Login to Firebase CLI

We need to authenticate to Firebase to create and deploy cloud functions, authenticate to Firebase using following command.

firebase login

This will open a browser window to authenticate.

If you are logged in with another account then you can logout first using following.

firebase logout

Choose the account to login.

Allow, to grant permissions to Firebase CLI.

On Allow following success screen will be presented.

And in command prompt message like following will be logged.

Creating a Firebase Cloud Function Project

Create a directory for the project.

mkdir firebase-function-demo

Change to project directory.

cd firebase-function-demo

Open the directory with Visual Studio code or any other editor.

code .

Initialize Firebase functions project

firebase init functions

Accept the confirmation.

Choose the appropriate option for you. In my case I chose “Use an existing project“, because I have already created the Firebase project.

Next I chose the project from the presented list.

For this example we are going to use the TypeScript, so choose the TypeScript.

Choose Y if you want to use ESLint.

Select Y to install the dependencies.

Your project structure should appear like this so far.

Creating a Cloud Function

We will use the sample helloworld cloud function created by the Firebase CLI for this example.

Open selected index.ts.

index.ts contains commented sample function.

Uncomment the code, and save the file.

File contains one sample http request based cloud function. Which will log following.

"Hello logs!", {structuredData: true}

and return following response.

"Hello from Firebase!"

In the same file more functions can be added, for example we can add another scheduled function like following.

export const scheduledJob = functions.pubsub.schedule("every 5 minutes")
    .onRun(()=>{
      console.log("This will be run every 5 minutes.");
      return null;
    });

This scheduled function will run every five minutes,

cron expression can be added like following to define trigger time for scheduled functions.

export const  scheduledFunctionCrontab = functions.pubsub.schedule('5 11 * * *')
  .timeZone('America/New_York') // Users can choose timezone - default is America/Los_Angeles
  .onRun((context) => {
  console.log('This will be run every day at 11:05 AM Eastern!');
  return null;
});

Deploying cloud function

Let’s deploy the sample code in index.ts to cloud.

Execute the following command on command prompt.

firebase deploy

On successful function deployment, function url will be provided.

Paste the URL in the browser.

and you will get the response like below from cloud function.

Great! Our cloud function is successfully deployed and responding to http request.

Navigate to Firebase project and select functions.

and you should be able to see your cloud function.

You can switch to Logs tab to see the logs of the cloud function.

Congratulations! We have just deployed our first simple cloud function.

Conclusion

In this post we learned how we can create a Firebase Cloud Function and deploy to Firebase. We started with how to install the Firebase CLI globally, and how to authenticate to it. Then we created a template project for cloud function using Firebase CLI and then deployed and tested the cloud function.

Hope you like this!

Please leave your feedback or any query you have.

Authenticating to ASP.NET Core Web Application Using Azure AD B2C

Azure Active Directory B2C enables users to authenticate themselves to applications using local accounts or social accounts such as Google, Facebook or LinkedIn.

The applications leveraging the Azure AD B2C, don’t have to maintain the authentication mechanism. All of that complexity will be handled by Azure AD B2C.

In this post we will see how to configure Azure AD B2C from scratch for ASP.NET Core applications.

We will go through the following topics:

  • Creating a new Azure AD B2C Tenant
  • App registration in Azure AD B2C Tenant
  • Configuring User Flows
  • Creating ASP.NET Core Web application Using Visual Studio 2019 and Configuring Azure AD B2C
  • Creating ASP.NET Core Web application Using .NET CLI and Configuring Azure AD B2C

To configure the Azure AD B2C for the applications first we need to create the Azure AD B2C tenant. Let’s create a new Azure AD B2C tenant.

Creating a New Azure AD B2C Tenant

To create a new Azure AD B2C tenant, login to your Azure portal and click on Create a resource.

In Create a resource page search for Azure Active Directory B2C in the search box, and select the first option available as shown below.

You will be navigated to Azure Active Directory B2C resource page.

Click on Create to create the Azure AD B2C tenant. This will create a separate tenant from your Azure AD tenant.

In the next screen you will be presented with following two options:

  • Create a new Azure AD B2C Tenant.
  • Link an existing Azure AD B2C Tenant to my Azure subscription.

Let’s choose Create a new Azure AD B2C Tenant to create a new tenant.

Next enter the following details for the new tenant.

  • Organization name: provide an organization name.
  • Initial domain name: provide a unique initial subdomain name.
    • Note down this initial domain name, we will need this to update in ASP.NET appsettings.json.
  • Country/Region: Select the country/region closest to your customers.
  • Subscription: Select subscription for your Azure AD B2C tenant.
    • Resource group: Choose resource group to contain Azure AD B2C tenant.

Then click on Review + Create

Validation screen will be presented.

Click on Create

You may encounter the following error.

The subscription is not registered to use namespace ‘Microsoft.AzureActiveDirectory’. See https://aka.ms/rps-not-found for how to register subscriptions. 

If you get this error then check the following post how to fix this error and then continue from here.

The subscription is not registered to use namespace ‘Microsoft.AzureActiveDirectory’

After fixing the error try creating Azure AD B2C Tenant again, and should be successful this time. You should be able to see the status under notifications.

Go to your newly created Azure AD B2C Demo tenant.

App Registration

Any application which needs to authenticate using Azure AD B2C, requires app registration in Azure.

Let’s register an app for our ASP.NET core application.

Click on New registration button inside the App registrations under our newly created Azure AD B2C tenant.

Fill in the details for the app registration

  • The display name: Enter any display name to easily identify the app.
  • Supported account types: choose “Accounts in any identity provider or organizational directory (for authenticating users with user flows)”
  • Redirect URI: Select Web in dropdown and enter following url in text box
https://localhost:5001/signin-oidc

Note the port no. we have provided 5001, you may need to update according to your application port no., we will see later in this post where in ASP.NET core application port can be configured.

Register the application.

In few seconds the app will be registered and you will be redirected to your App.

Note down the Application (client) ID, we will need this to update in ASP.NET core web application’s appsettings.json file.

Authentication options

Next we need to configure the authentications options.

Select the Authentication blade from left menu in registered app and check the two authentication options as shown below and click on Save.

We have successfully configured the app now.

Next we need to configure the User Flows for Sign up/ Sign in forms.

Configuring User Flows

User flows defines the sign up / sign in process for the applications but managed in Azure AD B2C. We can configure what data will be collected from the user and passed to the application.

To configure the User Flows, go back to the Azure AD B2C tenant and click on User Flows in left navigation.

Then click on New user flow

Selecting User Flow Type

In the new User Flow we get multiple options to configure, such as Sign up, Sign in, Profile editing.

Select the Sign up and sign in for this tutorial, this will enable the sign up and sign in experience for our web application.

On selecting Sign up and Sign in, it will enable another two options. Keep default and Click on Create

In the next screen provide a name for the User Flow and select email signup.

We can configure the Multifactor authentication as well, but leave default for now.

Scroll down a bit and select Show more…

On clicking show more, multiple fields will be presented to choose from in two columns Collect Column and Return Column.

Collect Column: Collect column shows what data will be collected from the user.

Return Claim: Return claim show what claims will be passed back to the application.

Select following options for our application and then click OK.

Note we have selected Display Name in collect attribute, during sign up user will be asked for Display Name.

Click on Create.

User Flow will be created and will be available under User flows.

Creating ASP.NET Core Web Application Using Visual Studio 2019 and Configuring Azure AD B2C

Let’s create an ASP.NET core application, and then we will configure it for Azure AD B2C authentication.

Open Visual Studio and select on Create a new project.

Select ASP.NET Core Web App (Model-View-Controller) for this example and click on next.

Provide project name and location, and select Next.

Select Microsoft Identity Platform from Authentication Type and click on create.

You may be presented with following screen to install required components (dotnet msidentity pool), select Finish to install.

ASP.NET application will be created.

Updating Azure AD B2C configurations

Open the appsettings.json you will see the following configurations.

{
/*
The following identity settings need to be configured
before the project can be successfully executed.
For more info see https://aka.ms/dotnet-template-ms-identity-platform 
*/
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "qualified.domain.name",
    "TenantId": "22222222-2222-2222-2222-222222222222",
    "ClientId": "11111111-1111-1111-11111111111111111",
    "CallbackPath": "/signin-oidc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Replace it with following and replace {Initial Domain Name} and {Application (Client) Id} with values we noted earlier.

{
/*
The following identity settings need to be configured
before the project can be successfully executed.
For more info see https://aka.ms/dotnet-template-ms-identity-platform 
*/
  "AzureAd": {
    "Instance": "https://{Initial Domain Name}.b2clogin.com/",
    "ClientId": "{Application (Client) Id}",
    "Domain": "{Initial Domain name}.onmicrosoft.com",
    "SignedOutCallbackPath": "/signout/B2C_1_susi",
    "SignUpSignInPolicyId": "b2c_1_susi",
    "ResetPasswordPolicyId": "b2c_1_reset",
    "EditProfilePolicyId": "b2c_1_edit_profile",
    "CallbackPath": "/signin-oidc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Updating application Port no.

Remember earlier we specified port no. 5001 in Azure for callback Url?

Let’s update this in our ASP.NET project.

Open Properties > launchSettings.json

Update sslPort no. to 5001.

 "sslPort": 5001

If you want to keep another port no. then make sure you update in Azure AD B2C app registration too.

Testing Azure AD B2C

Press F5 and you will be redirected to {orgname}.b2clogin.com for authentication, If not then click on Sign in link on web portal.

Click on Sign up, and you will be asked for sing up details along with Display name we configured earlier in User Flow.

Creating ASP.NET Core Web application Using .NET CLI and Configuring Azure AD B2C

Open command prompt.

Create a directory for the web application.

mkdir AzureADB2CCodeDemo

Switch to the directory just created.

cd AzureADB2CCodeDemo

Create new dotnet mvc application project with Azure AD B2C option, i.e. IndividualB2C

dotnet new mvc --auth IndividualB2C

Open the project with Visual Studio Code.

Code .

Open appsettings.json, you will see similar options as we saw previously with Visual Studio 2019.

{
  "AzureAdB2C": {
    "Instance": "https://login.microsoftonline.com/tfp/",
    "ClientId": "11111111-1111-1111-11111111111111111",
    "Domain": "qualified.domain.name",
    "SignedOutCallbackPath": "/signout/B2C_1_susi",
    "SignUpSignInPolicyId": "b2c_1_susi",
    "ResetPasswordPolicyId": "b2c_1_reset",
    "EditProfilePolicyId": "b2c_1_edit_profile",
    "CallbackPath": "/signin-oidc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Replace it with following and replace {Initial Domain Name} and {Application (Client) Id} with values we noted earlier.

{
/*
The following identity settings need to be configured
before the project can be successfully executed.
For more info see https://aka.ms/dotnet-template-ms-identity-platform 
*/
  "AzureAd": {
    "Instance": "https://{Initial Domain Name}.b2clogin.com/",
    "ClientId": "{Application (Client) Id}",
    "Domain": "{Initial Domain name}.onmicrosoft.com",
    "SignedOutCallbackPath": "/signout/B2C_1_susi",
    "SignUpSignInPolicyId": "b2c_1_susi",
    "ResetPasswordPolicyId": "b2c_1_reset",
    "EditProfilePolicyId": "b2c_1_edit_profile",
    "CallbackPath": "/signin-oidc"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}

Updating application Port no.

Let’s update the port for project generated from .NET CLI.

Open Properties > launchSettings.json

Update sslPort no. to 5001. as highlighted below.

{
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:51430",
      "sslPort": 44315
    }
  },
  "profiles": {
    "AzureADB2CCodeDemo": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:5001;http://localhost:5000",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Run project

dotnet run

And you should see following from b2clogin.com

Conclusion

In this post we learned how to configure Azure AD B2C for ASP.NET Core applications to allow users to authenticate themselves leveraging Azure AD B2C capabilities. Azure AD B2C let’s users to use local account or social accounts such as Google, Facebook or LinkedIn for authentication.

We started by setting up the new Azure AD B2C tenant and registered app for ASP.NET core application. Then we configured User Flow for Sign up and Sign In. Next we configured Azure AD B2C settings in ASP.NET core applications created using Visual Studio 2019 UI and .NET CLI.

Please leave your feedback or any queries you have.

Thanks!