Showing posts with label Eathan Spark. Show all posts
Showing posts with label Eathan Spark. Show all posts

Monday, February 6, 2023

How to Change - Jupyter Notebook (Anaconda3) Startup Directory / Folder - Windows

Jupyter Notebook has default startup directory, In most of the case after installation it's starting directory is under the user folder. If you want to change this default location to any user defined folder in any drive like "D:/MyAllNotebook/" you can follow the below easy steps too change it.

Step 1:

Click on start menu and type "Jupyter", you will see the jupyter App icon like below -

Step 2:

Right Click on Jupyter App Icon and choose "Open file location", It will open file explorer below

Step 3:

Select Jupyter Notebook file and right click and select property option. It will open property dialog box.

In target edit box you can see the text like "%USERPROFILE%/"

Replace this "%USERPROFILE%/" text to your desire path like this "D:/MyAllNotebook/"

Step 4:

Restart Jupyter Notebook App again - Now it will land to your specified location like below

Saturday, January 21, 2023

.Net Core Console Application As Windows Service - Background Activity

We can convert our .Net Core Console Application into regular Windows Service by using third party library like TopShelf, Quartz and for logging  we can utilize NLog.

Windows Service is mainly used when you want a regular running process in the background that do some activity behind the seen. 

Lets try to convert .Net Core Console Application to Windows Service. 


Open Visula Studio 2019 - > Go to New Project -> Select .Net Core(Console) template and Create project

We have to include maily two library

  • Topshelf
  • Quartz

Topshelf

Topshelf is use to initialies HostFactory Like Below

	
        var services = ServiceDependency.ConfigureServices();
        var serviceProvider = services.BuildServiceProvider();

        var rc = HostFactory.Run(x =>
        {
            x.Service(s =>
            {
                s.ConstructUsing(name => serviceProvider.GetService());
                s.WhenStarted(tc => tc.Start());
                s.WhenStopped(tc => tc.Stop());
            });
            x.RunAsLocalSystem();

            x.SetDescription("Windows Service Demo");
            x.SetDisplayName("WinServiceDemo");
            x.SetServiceName("WinServiceDemo");
        });

        var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
        Environment.ExitCode = exitCode;

	

Quartz

Quart Library is used to Schedule services like below

	
           public JobTrigger GetCommonJob()
    {

        ReportProcessorJobKey = JobKey.Create("CommonJob", "CommonJob");

        var job = JobBuilder.Create().WithIdentity("CommonJob", "CommonJob").Build();
        int ConfigFrequency;
        int frequency = int.TryParse(ConfigurationManager.AppSettings["CommonJobFrequencyInSecond"], out ConfigFrequency) ? ConfigFrequency : 5;
        var jobTrigger = TriggerBuilder.Create()
            .WithSimpleSchedule(x => x.WithIntervalInSeconds(frequency).RepeatForever())
            .Build();

        return new JobTrigger { Job = job, Trigger = jobTrigger };
    }

	

For Source Code : You can follow the below Link

The Complete Source Code Example is availabe on below link ..

Download

Tuesday, December 27, 2022

Triggering/Calling Azure Data Factory Pipeline from Console/Windows Application (C#/.Net)

Azure data Factory has proper way of calling/triggering pipeline through different types of triggers like http, scheduled on specific time, event base trigger

message base trigger, manual trigger from Azure Portal. But in some scenario we required to call ADF pipeline as on demand basis through your application.

In that scenario Microsoft Azure has provided rich libraries in different language to achieve same activity.

Here I am presenting very easy way to trigger Azure data factory pipeline through code (C#/Net)

Prerequisite

Azure Details

.Net Supporting Library

  • Microsoft.Azure.Management.DataFactory;
  • Microsoft.Rest;
  • Microsoft.IdentityModel.Clients.ActiveDirectory;
  • System.Threading.Tasks;

AzureDataFactoryModel.cs


using System;
using System.Collections.Generic;
using System.Text;

namespace TriggerADFPipeline
{
    public class AzureDataFactoryModel
    {

        public AzureDataFactoryModel()
        {
            if (Parameters == null)
            {
                Parameters = new Dictionary();
            }
        }
        public Dictionary Parameters { get; set; }

        public string ResourceGroupName { get; set; }
        public string FactoryName { get; set; }
        public string PipeLineName { get; set; }

    }
}

ADFHelper.cs


using Microsoft.Azure.Management.DataFactory;
using Microsoft.Rest;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Threading.Tasks;

namespace TriggerADFPipeline
{
    public class ADFHelper
    {
        private TokenCredentials _tokenCredential;
        private DataFactoryManagementClient _dataFactoryClient;

        private readonly string tenantId = "xxxx";
        private readonly string clientId = "xxxx";
        private readonly string clientSecret = "xxxx";
        private readonly string subscriptionId = "xxxx";
        private readonly string windowsManagementUri = "https://management.core.windows.net/";
        private readonly string activeDirectoryEndpoint = "https://login.windows.net/";
        public ADFHelper()
        {
            AuthenticateUser();
            SetupClient();
        }

        private void AuthenticateUser()
        {
            var authority = new Uri(new Uri(activeDirectoryEndpoint), this.tenantId);
            var context = new AuthenticationContext(authority.AbsoluteUri);
            var credential = new ClientCredential(this.clientId, this.clientSecret);

            _tokenCredential = new TokenCredentials(context.AcquireTokenAsync(windowsManagementUri, credential).Result.AccessToken);
        }
        private void SetupClient()
        {
            _dataFactoryClient = new DataFactoryManagementClient(_tokenCredential) { SubscriptionId = subscriptionId };
        }

        
        public async Task TriggerAdfAsync(AzureDataFactoryModel azureDataFactoryModel)
        {
            try
            {
                
                var runResponse = await _dataFactoryClient.Pipelines.CreateRunWithHttpMessagesAsync(
                                                           azureDataFactoryModel.ResourceGroupName,
                                                           azureDataFactoryModel.FactoryName,
                                                          azureDataFactoryModel.PipeLineName,
                                                           parameters: azureDataFactoryModel.Parameters
                ).ConfigureAwait(false);
              
                return runResponse.Body.RunId;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }

    }
}

Program.cs


using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace TriggerADFPipeline
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello I am Calling ADF pipeline from C#....");
            ADFHelper _azureDataFactory = new ADFHelper();
            AzureDataFactoryModel azureDataFactoryModel = new AzureDataFactoryModel();
            azureDataFactoryModel.ResourceGroupName = "xxxx";
            azureDataFactoryModel.FactoryName = "xxxx";
            azureDataFactoryModel.PipeLineName = "xxxx";
            azureDataFactoryModel.Parameters = new Dictionary<string, object>
            {
                { "P1", "parameter 1"},
                { "P2", "parameter 2"},
                { "P3", "parameter 3"}
            };
            var runId = _azureDataFactory.TriggerAdfAsync(azureDataFactoryModel).ConfigureAwait(false);
            Console.WriteLine($"Run Id : {runId}");
        }

    }
}

Download Source Code

ADF Trigger

How to Delete your Blog from Blogger - Permanently

If you want to delete your blog permanently, follow the steps

Login to you blogger account select blog which you want to delete from


Go to setting menu



Scroll down to Manage Blog section



There you find "Remove your blog" option , Click on this link it will give you a warning pop up like this



 

If you want to take backup of your content click on Download Blog Link.

For deleting blog Click on Delete ..

It will redirect to next page ..

 



From here you can delete permanently or undelete.                     

Once click on Permanent delete, it will prompt another warning like this



Click on permanent delete and you are done


Tuesday, July 2, 2019

Azure Service Bus - Message-based Communication Workflows

Introduction

Application being develop frequently  now a days which consist of different parts executing on separate computers and devices, which are in different location around the world. The main concern with these distributed application is how to communicate reliably between the components of a distributed application. we can use azure messaging to deliver the same.

Azure Service bus is a type of messaging system. Its main function is to provide interaction between application and services. It is a multi-tenant cloud messaging service.

In this blog we gonna learn how Azure Service Bus can help build an application that stays reliable during high demand.

Common Messaging Scenarios

  • Messaging: transfer business data, such as sales or purchase orders, journals, or inventory movements.
  • Decouple applications: improve reliability and scalability of applications and services (client and service do not have to be online at the same time).
  • Topics and subscriptions: enable 1:n relationships between publishers and subscribers.
  • Message sessions: implement workflows that require message ordering or message deferral.

Azure Messaging Services Selections

Azure provides three type of messaging service for delivering event messages throughout the solutions.
  • Event Grid
  • Event Hubs
  • Service Bus

Event Grid

It uses a publish-subscribe model. Publishers emit events, but have no expectation about which events are handled. Subscribers decide which events they want to handle. Event Grid isn't a data pipeline, and doesn't deliver the actual object that was updated.

Characteristics:
  • Dynamically scalable
  • Low cost
  • Serverless
  • At least once delivery

Event Hubs

Azure Event Hubs is a big data pipeline. It provides services to capture, retention, replay of telemetry and event stream data. The data can come from many concurrent sources. Event Hubs allows telemetry and event data to be made available to a variety of stream-processing infrastructures and analytics services. It is available either as data streams or bundled event batches. This service provides a single solution that enables rapid data retrieval for real-time processing as well as repeated replay of stored raw data. It can capture the streaming data into a file for processing and analysis.

Characteristics:
  • Low latency
  • Capable of receiving and processing millions of events per second
  • At least once delivery

Service Bus

Service Bus enables cloud-native applications to provide reliable state transition management for business processes. When handling high-value messages that cannot be lost or duplicated, use Azure Service Bus. Service Bus also facilitates highly secure communication across hybrid cloud solutions and can connect existing on-premises systems to cloud solutions.

Service Bus is a brokered messaging system. It stores messages in a "broker" (for example, a queue) until the consuming party is ready to receive the messages.

Characteristics:
  • Reliable asynchronous message delivery (enterprise messaging as a service) that requires polling
  • Advanced messaging features like FIFO, batching/sessions, transactions, dead-lettering, temporal control, routing and filtering, and duplicate detection
  • At least once delivery
  • Optional in-order delivery

Service Bus Learning objectives

  • Choose whether to use Service Bus queues, topics, or relays to communicate in a distributed application
  • Create a Service Bus queue and use it to send and receive messages
  • Create a Service Bus topic and use it to send and receive messages

Service Bus topics, queues, and relays

Azure Service Bus can exchange messages in three different ways: queues, topics, and relays.

Queue:

A queue is a simple temporary storage location for messages. A sending component adds a message to the queue. A destination component picks up the message at the front of the queue. Under ordinary circumstances, each message is received by only one receiver.

image url

During peak times, messages may come in faster than destination components can handle them. Because source components have no direct connection to the destination, the source is unaffected and the queue will grow. Destination components will remove messages from the queue as they are able to handle them. When demand drops, destination components can catch up and the queue shortens.

Topic:

A topic is similar to a queue but can have multiple subscriptions. This means that multiple destination components can subscribe to a single topic, so each message is delivered to multiple receivers. Subscriptions can also filter the messages in the topic to receive only messages that are relevant. Subscriptions provide the same decoupled communications as queues and respond to high demand in the same way. Use a topic if you want each message to be delivered to more than one destination component.
image url

Relay:

A relay is an object that performs synchronous, two-way communication between applications. Unlike queues and topics, it is not a temporary storage location for messages. Instead, it provides bidirectional, unbuffered connections across network boundaries such as firewalls. Use a relay when you want direct communications between components as if they were located on the same network segment but separated by network security devices.

Send messages to the queue

Launch Visual Studio and create a new Console App (.NET Core) project.

Add the Service Bus NuGet package

  1. Right-click the newly created project and select Manage NuGet Packages.
  2. Click the Browse tab, search for Microsoft.Azure.ServiceBus, and then select the Microsoft.Azure.ServiceBus item. Click Install to complete the installation, then close this dialog box.
image url

Write code to send messages to the queue

 
 namespace CoreSenderApp
{
    using System;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.ServiceBus;

    class Program
    {
        // Connection String for the namespace can be obtained from the Azure portal under the 
        // 'Shared Access policies' section.
        const string ServiceBusConnectionString = "";
        const string QueueName = "";
        static IQueueClient queueClient;

        static void Main(string[] args)
        {
            MainAsync().GetAwaiter().GetResult();
        }

        static async Task MainAsync()
        {
            const int numberOfMessages = 10;
            queueClient = new QueueClient(ServiceBusConnectionString, QueueName);

            Console.WriteLine("======================================================");
            Console.WriteLine("Press ENTER key to exit after sending all the messages.");
            Console.WriteLine("======================================================");

            // Send Messages
            await SendMessagesAsync(numberOfMessages);

            Console.ReadKey();

            await queueClient.CloseAsync();
        }

        static async Task SendMessagesAsync(int numberOfMessagesToSend)
        {
            try
            {
                for (var i = 0; i < numberOfMessagesToSend; i++)
                {
                    // Create a new message to send to the queue
                    string messageBody = $"Message {i}";
                    var message = new Message(Encoding.UTF8.GetBytes(messageBody));

                    // Write the body of the message to the console
                    Console.WriteLine($"Sending message: {messageBody}");

                    // Send the message to the queue
                    await queueClient.SendAsync(message);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
            }
        }
    }
}
 
 

Receive messages from the queue

To receive the messages you sent, create another .NET Core console application and install the Microsoft.Azure.ServiceBus NuGet package, similar to the previous sender application.

namespace CoreReceiverApp
{
    using System;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.ServiceBus;

    class Program
    {
        // Connection String for the namespace can be obtained from the Azure portal under the
        // 'Shared Access policies' section.
        const string ServiceBusConnectionString = "";
        const string QueueName = "";
        static IQueueClient queueClient;

        static void Main(string[] args)
        {
            MainAsync().GetAwaiter().GetResult();
        }

        static async Task MainAsync()
        {
            queueClient = new QueueClient(ServiceBusConnectionString, QueueName);

            Console.WriteLine("======================================================");
            Console.WriteLine("Press ENTER key to exit after receiving all the messages.");
            Console.WriteLine("======================================================");

            // Register QueueClient's MessageHandler and receive messages in a loop
            RegisterOnMessageHandlerAndReceiveMessages();

            Console.ReadKey();

            await queueClient.CloseAsync();
        }

        static void RegisterOnMessageHandlerAndReceiveMessages()
        {
         
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
             
                MaxConcurrentCalls = 1,             
                AutoComplete = false
            };

            // Register the function that will process messages
            queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
        }

        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            // Process the message
            Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
         
            await queueClient.CompleteAsync(message.SystemProperties.LockToken);
       
        }

        static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
        {
            Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
            var context = exceptionReceivedEventArgs.ExceptionReceivedContext;
            Console.WriteLine("Exception context for troubleshooting:");
            Console.WriteLine($"- Endpoint: {context.Endpoint}");
            Console.WriteLine($"- Entity Path: {context.EntityPath}");
            Console.WriteLine($"- Executing Action: {context.Action}");
            return Task.CompletedTask;
        }
    }
}


Send messages to the topic

Launch Visual Studio and create a new Console App (.NET Core) project.

Add the Service Bus NuGet package


  • Right-click the newly created project and select Manage NuGet Packages.
  • Click the Browse tab, search for Microsoft.Azure.ServiceBus, and then select the Microsoft.Azure.ServiceBus item. Click Install to complete the installation, then close this dialog box.

image url

Write code to send messages to the topic


namespace CoreSenderApp
{
    using System;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.ServiceBus;

    class Program
    {
        const string ServiceBusConnectionString = "";
        const string TopicName = "";
        static ITopicClient topicClient;

        static void Main(string[] args)
        {
            MainAsync().GetAwaiter().GetResult();
        }

        static async Task MainAsync()
        {
            const int numberOfMessages = 10;
            topicClient = new TopicClient(ServiceBusConnectionString, TopicName);

            Console.WriteLine("======================================================");
            Console.WriteLine("Press ENTER key to exit after sending all the messages.");
            Console.WriteLine("======================================================");

            // Send messages.
            await SendMessagesAsync(numberOfMessages);

            Console.ReadKey();

            await topicClient.CloseAsync();
        }

        static async Task SendMessagesAsync(int numberOfMessagesToSend)
        {
            try
            {
                for (var i = 0; i < numberOfMessagesToSend; i++)
                {
                    // Create a new message to send to the topic
                    string messageBody = $"Message {i}";
                    var message = new Message(Encoding.UTF8.GetBytes(messageBody));

                    // Write the body of the message to the console
                    Console.WriteLine($"Sending message: {messageBody}");

                    // Send the message to the topic
                    await topicClient.SendAsync(message);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine($"{DateTime.Now} :: Exception: {exception.Message}");
            }
        }
    }
}

Receive messages from the subscription

To receive the messages you sent, create another .NET Core console application and install the Microsoft.Azure.ServiceBus NuGet package, similar to the previous sender application.

Write code to receive messages from the subscription


namespace CoreReceiverApp
{
    using System;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.Azure.ServiceBus;

    class Program
    {
        const string ServiceBusConnectionString = "";
        const string TopicName = "";
        const string SubscriptionName = "";
        static ISubscriptionClient subscriptionClient;

        static void Main(string[] args)
        {
            MainAsync().GetAwaiter().GetResult();
        }

        static async Task MainAsync()
        {
            subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName);

            Console.WriteLine("======================================================");
            Console.WriteLine("Press ENTER key to exit after receiving all the messages.");
            Console.WriteLine("======================================================");

            // Register subscription message handler and receive messages in a loop.
            RegisterOnMessageHandlerAndReceiveMessages();

            Console.ReadKey();

            await subscriptionClient.CloseAsync();
        }

        static void RegisterOnMessageHandlerAndReceiveMessages()
        {
          
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                MaxConcurrentCalls = 1,
                AutoComplete = false
            };

            // Register the function that processes messages.
            subscriptionClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
        }

        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            // Process the message.
            Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
           
            await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);

        }

        static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
        {
            Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
            var context = exceptionReceivedEventArgs.ExceptionReceivedContext;
            Console.WriteLine("Exception context for troubleshooting:");
            Console.WriteLine($"- Endpoint: {context.Endpoint}");
            Console.WriteLine($"- Entity Path: {context.EntityPath}");
            Console.WriteLine($"- Executing Action: {context.Action}");
            return Task.CompletedTask;
        }
    }
}

Tuesday, June 25, 2019

What are Microservices?-Azure

Ref: https://docs.microsoft.com/en-us/azure/architecture/microservices/

Microservices are a popular architectural style for building applications that are resilient, highly scalable, independently deployable, and able to evolve quickly. 

Microservices are a software architecture style in which applications are composed of small, independent modules that communicate with each other using well-defined API contracts. These service modules are highly decoupled building blocks that are small enough to implement a single functionality.

The purpose of microservices architectures is to make it easier to develop and scale applications. Microservice architectures foster collaboration between autonomous teams and enable them to bring new functionalities to market faster.


Why use microservices?

Build services independently

Microservices-based applications are built as a collection of highly decoupled services that handle a single action. Teams can independently build, verify, deploy and monitor each service.

Scale services autonomously

Independent services can be scaled based on their respective demands without impacting the overall performance, rather than scaling the entire app up or down.

Use the best approach

Development teams gain the flexibility to use the best deployment approach, language, platform and programming model for each service.

Isolate points of failure

By isolating potential problem areas to individual services, microservices architectures improve security and reliability. Services can be replaced or retired without affecting the overall structure.

Deliver value faster

Teams can deploy small, independent modules quickly. Several teams can work on different services at the same time and put new features into production faster.

Advantage with microservices in Azure

Simplify your application lifecycle

Boost agility and collaboration and reduce time to market by using Azure managed services and development tools.

Rely on a trusted platform

Develop secure and reliable applications on a compliance-certified platform.

Scale to your needs

Improve overall performance by enabling automated and fully managed scaling on demand.

Gain flexibility

Adapt faster to business needs by choosing the best approach and technology for each service.


Best approach for building microservices in Azure

Service Fabric

Get automatic scaling, rolling upgrades and self-healing from faults with a custom-built microservices framework.

Azure Kubernetes Service (AKS)

Use a fully managed Kubernetes service to handle provisioning, upgrading and scaling cluster resources on demand.

Azure Functions

Build apps with simple, serverless functions that scale on demand based on the number of executions—without managing infrastructure.

API Management

Expose and publish specific parts of your applications as an API no matter where the implementation is hosted.

Friday, January 11, 2019

Angular Concepts : Complete Angular Guide


Introduction:

Angular is a platform and framework for building client applications in HTML and TypeScript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your apps. Angular is not a higher version AngularJs but it is completely rewritten. It has lot of improvements when compared with AngularJs like "Performance, Mobile support, Component based development, More language choice".

Why Angular:

  • Angular is 5 times faster than AngularJs. Angular has faster initial loads, change detection and improved rendering times.
  • Mobile Support:  With angular we can build a single application that can run on mobile and desktop devices.
  • Component Based Development:In Angular everything is component. Components are the building block of Angular application.
  • More language choices: 
    • ECMAScript 5
    • ECMAScript 6 (also called ES 2015)
    • TypeScript
    • PureScript etc

What is Type Script:

TypeScript is a free and open-source programming language developed by Microsoft. It is a superset of JavaScript and compiles to JavaScript through a process called transpilation. Using TypeScript to build angular applications provides several benefits.

  1. Intellisense
  2. Autocompletion
  3. Code navigation
  4. Advanced refactoring
  5. Strong Typing
  6. Supports ES 2015 (also called ES 6) features like classes, interfaces and inheritance.

Because of all these benefits writing, maintaining and refactoring applications can be an enjoyable experience. So obviously TypeScript has become the number one choice of many developers for developing Angular applications. Besides Visual Studio, TypeScript is supported by several other editors like

  1. Visual Studio Code
  2. Eclipse
  3. WebStorm
  4. Atom
  5. Sublime Text etc.

Main Building Blocks of an Angular application:

  • Modules
  • Components
    • Templates, directives, Pipe and data binding
  • Services and dependency injection
    • Routing

What Is A Modules:

In simple terms an Angular Module is a class decorated with @NgModule decorator. An Angular Module is a mechanism to group components, directives, pipes and services that are related to a feature area of an angular application.

For example, if you are building an application to manage employees, you might have the following features in your application.

Application Feature Description
Employee Feature Deals with creating, reading, updating and deleting employees
Login Feature Deals with login, logout, authenticate and authorize users
Report Feature Deals with generating employee reports like total number of employees by department, top 10 best employees etc

To group the components, directives, pipes and services related to a specific feature area, we create a module for each feature area. These modules are called feature modules.

Every Angular app has at least one NgModule class, the root module, which is conventionally named AppModule and resides in a file named app.module.ts. You launch your app by bootstrapping the root NgModule.

In addition to feature modules, an Angular application also contains the following modules.

  • Root Module: Every Angular application has at least one module, the root module. By default, this root application module is called AppModule. We bootstrap this root module to launch the application.
  • Core Module: The most important use of this module is to include the providers of http services. Services in Angular are usually singletons. So to ensure that, only one instance of a given service is created across the entire application, we include all our singleton service providers in the core module. In most cases, a CoreModule is a pure services module with no declarations. The core module is then imported into the root module (AppModule) only. CoreModule should never be imported in any other module.
  • Shared Module: This module contains reusable components, directives, and pipes that we want to use across our application. The Shared module is then imported into specific Feature Modules as needed.
  • Routing Module: An angular application may also have one or more routing modules for application level routes and feature module routes.

Advantage of Angular Module:

  • Organizing Angular Application
  • Code Reuse
  • Code Maintenance
  • Performance

NgModule metadata/@NgModule Decorator:

The @NgModule() decorator is a function that takes a single metadata object, whose properties describe the module. The most important properties are as follows.

  • declarations: The components, directives, and pipes that belong to this NgModule.
  • exports: The subset of declarations that should be visible and usable in the component templates of other NgModules.
  • imports: Other modules whose exported classes are needed by component templates declared in this NgModule.
  • providers: Creators of services that this NgModule contributes to the global collection of services; they become accessible in all parts of the app. (You can also specify providers at the component level, which is often preferred.)
  • bootstrap: The main application view, called the root component, which hosts all other app views. Only the root NgModule should set the bootstrap property.
What Is A Component:
Component defines a class that contains application data and logic and is associated with an HTML template that defines a view to be displayed in a target environment.
A component in Angular is a class with a template and a decorator. So, in simple terms a component in Angular is composed of these 3 things

·         Template - Defines the user interface. Contains the HTML, directives and bindings.
·         Class - Contains the code required for template. Just like a class in any object-oriented programming language like C# or Java, a class in angular c an contain methods and properties. Properties contain the data that we want to display in the view template and methods contain the logic for the view. We use TypeScript to create the class.
·         Decorator - Decorators are functions that modify JavaScript classes. We use the Component decorator provided by Angular to add metadata to the class. A class becomes an Angular component, when it is decorated with the Component decorator.
Example:
        

Template:
It defines the user interface that contains the HTML, directives and bindings. We can define template in two different way.
1.      With an Inline template: For inline template we need to use template property for writing html in single/multi line. Angular recommends using templateUrl property when you have html of more than three line.
Use special Char pair “  `  `  ” for multiline like below
            `<h1>
                        Hello
</h1>`
a.      We lose visual studio editor intellisense, code completion and formatting features
b.      TypeScript code is not easier to read and understand when it is mixed with inline html template.
2.      With an external view template: We write html view in external html file with .html and use templateUrl property to set the location of html file. Location is relative to index.html
a.      We have visual studio editor intellisense, code completion and formatting features
b.      Code is clean and easier to read and understand
Styling Angular Components:
·         Styles in external stylesheet - Styles.css 
·         Styles inline in the component html file
·         Styles in the component html file using <style> tag
·         Specify the styles in the component TypeScript file using the @component decorator Styles property
·         Specify the styles in the component TypeScript file using the @component decorator StyleUrls property
·        
What is A Directives:
A directive is a custom HTML element that is used to extend the power of HTML. A directive is a class with a @Directive() decorator.
There are three kinds of directives in an Angular 2 application.
1.      Components: Angular Component also refers to a directive with a template which deals with View of the Application and also contains the business logic. It is very useful to divide your Application into smaller parts. In other words, we can say that Components are directives that are always associated with the template directly.
2.      Structural directives: Structural directives are able to change the behavior of DOM by adding and removing DOM elements. The directive NgFor, NgSwitch, and NgIf is the best example of structural directives.
3.      Attribute directives: Attribute directives are able to change the behavior of DOM. The directive NgStyle is an example of Attribute directives which are used to change styles elements at the same time.
Example Attribute directive:
Note: Angular does not allow to use more than one structural directive in single element that’s why we need container component.
What is A Pipe:
Angular pipes let you declare display-value transformations in your template HTML. A class with the @Pipe decorator defines a function that transforms input values to output values for display in a view.
Transform data before display. Built in pipes include lowercase, uppercase, decimal, date, percent, currency etc
To apply a pipe on a bound property, use the pipe character " | "
We can also chain pipes
Pass parameters to pipe using colon ": "


Pure and Impure Pipe:
There are two categories of pipes: pure and impure. Pipes are pure by default. You make a pipe impure by setting its pure flag to false.
Pure pipes:
Angular executes a pure pipe only when it detects a pure change to the input value. A pure change is either a change to a primitive input value (String, Number, Boolean, Symbol) or a changed object reference (Date, Array, Function, Object).
Angular ignores changes within (composite) objects. It won't call a pure pipe if you change an input month, add to an input array, or update an input object property.
Impure pipes:
Angular executes an impure pipe during every component change detection cycle. An impure pipe is called often, as often as every keystroke or mouse-move.
With that concern in mind, implement an impure pipe with great care. An expensive, long-running pipe could destroy the user experience.

Angular custom pipe:

Step 1: Create a custom pipe called employeeTitlePipe as employeeTitle.pipe.ts file. 

Step 2: Register "EmployeeTitlePipe" in the angular module.
Step 3: In "employeeList.component.html" use the "EmployeeTitlePipe" as shown below. 

What is Data binding:
Data binding is a core concept in Angular and allows to define communication between a component and the DOM, making it very easy to define interactive applications without worrying about pushing and pulling data.
There are four forms of data binding and they differ in the way the data is flowing.
From the Component to the DOM
·         Interpolation: {{ value }} : This adds the value of a property from the component:
<li>Name: {{ user.name }}</li> <li>Email: {{ user.email }}</li>
·         Property binding: [property]="value": With property binding, the value is passed from the component to the specified property, which can often be a simple html attribute:
<input type="email" [value]="user.email">
Here are two more examples, one that applies a background-color from the value of selectedColor in the component and one that applies a class name if isSelected evaluates to true:
<div [style.background-color]="selectedColor">
<div [class.selected]="isSelected">
We can also use the alternate syntax with bind- prefix. This is known as canonical form
<button bind-disabled='isDisabled'>Click me</button>
From the DOM to the Component
·         Event binding: (event)="function": When a specific DOM event happens (eg.: click, change, keyup), call the specified specified method in the component. In the example below, the cookBacon() method from the component is called when the button is clicked:
<button (click)="cookBacon()"></button>
we can also use the on- prefix alternative as shown below. This is known as the canonical form
<button on-click="onClick()">Click me</button>
Two-Way
·         Two-way data binding: [(ngModel)]="value": Using what’s called the banana in a box syntax, two-way data binding allows to have the data flow both ways. In this example, the user.email data property is used as the value for the input, but if the user changes the value, the component property gets updated automatically to the new value:

<input type="email" [(ngModel)]="user.email">
What is the difference between HTML element attribute and DOM property
  • Attributes are defined by HTML, whereas properties are defined by the DOM.
  • Attributes initialize DOM properties. Once the initialization complete, the attributes job is done.
  • Property values can change, whereas attribute values can't.

What is a container and nested component:
In the example below, we have 2 components, One of the component displays the list of employees. We have already built this component in our previous videos in this series. We named this component EmployeeListComponent.
The other component displays the radio buttons and the count of employees. We have not created this component yet. We will create it in this video. We will call this component EmployeeCountComponent.
We will nest EmployeeCountComponent in EmployeeListComponent. So EmployeeCountComponent becomes the nested component or child component and EmployeeListComponent becomes the container component or parent component.

Understanding @Input, @Output and EventEmitter:
A tool to exchange data
First of all, the idea of Input and Output is to exchange data between components. They are a mechanism to send/receive data from one component to another. Input is used to receive data in whereas Output is used to send data out. Output sends data out by exposing event producers, usually EventEmitter objects. So, when you see code like this
that means hey, I am expecting data being sent to me. I will receive it and store it into my item property by the way, I will produce and send data out via the onChange property.

@Input in action:
Decorating a property with @Input() decorator makes the property an input property. 
Passing data from the parent component (EmployeeListComponent) to the child component (EmployeeCountComponet):
 
Note: In the filter method we are using tripple equals (===) instead of double equals (==). The table below explains single, double and tripple equals in TypeScript. 

Operator
Use to
=
Assign a value
==
Compare two values
===
Compare two values and their types

@Output and EventEmitter:
Decorating a property with @Output() decorator makes the property an output property.


Child Component (EmployeeCountComponent)

 

Parent Component (EmployeeListComponent)

 


An Interface in TypeScript:
An interface is an abstract type. It only contains declarations of properties, methods and events. The implementation for the interface members is provided by a class that implements the interface. If a class that implements the interface fails to provide implementation for all the interface members, the language compiler raises an error alerting the developer that something has been missed.
1.      Use interface keyword to create an interface
2.      It is common to prefix the interface name with capital letter "I". However, some interfaces in Angular does not have the prefix "I". For example, OnInit interface
3.      Interface members are public by default and does not require explicit access modifiers. It is a compile time error to include an explicit access modifier. You will see an error message like - public modifier cannot appear on a type member.
4.      A class that implements an interface must provide implementation for all the interface members unless the members are marked as optional using the ? operator
5.      Use the implements keyword to make a class implement an interface
6.      TypeScript interfaces exist for developer convenience and are not used by Angular at runtime. During transpilation, no JavaScript code is generated for an interface. It is only used by Typescript for type checking during development.
7.      To reduce the amount of code you have to write, consider using short-hand syntax to initialise class properties with constructor parameters

Angular Component lifecycle hooks:
In Angular, every component has a life-cycle, a number of different stages it goes through from initializing to destroying. There are 8 different stages in the component lifecycle. Every stage is called life cycle hook events. 
Constructor:
The constructor of the component class is called before any other component lifecycle hook. If our component is based on any dependencies, the constructor is the best place to inject those dependencies.

ngOnChanges:
The ngOnChanges will be called first when the value of a bound property changes. It executes, every time the value of an input property changes. It will receive a changes map, containing the current and previous values of the binding, wrapped in a SimpleChange.

{"brand":{"previousValue":"","currentValue":"BMW"}}

In the case above, one change to the input property brand is reported. The value of this property has been changed from an empty string to the string “BMW”.


ngOnInit:
The ngOnInit method of a component is called directly after the constructor and after the ngOnChange is triggered for the first time. It is the perfect place for initialization work.
Invoked when given component has been initialized. This hook is only called once after     the first ngOnChanges
Use ngOnInit() for two main reasons:
1.      To perform complex initializations shortly after construction.
2.      To set up the component after Angular sets the input properties.
An ngOnInit() is a good place for a component to fetch its initial data.
Note: Remember also that a directive's data-bound input properties are not set until after construction. That's a problem if you need to initialize the directive based on those properties. They'll have been set when ngOnInit() runs.

ngDoCheck:
Invoked when the change detector of the given component is invoked. It allows us to implement our own change detection algorithm for the given component.

ngDoCheck and ngOnChanges should not be implemented together on the same component.
Use the DoCheck hook to detect and act upon changes that Angular doesn't catch on its own.
If you have a object with some property and internal property getting in that case ngOnChange() event will not fire to over come these issue we need custom change detection, it this scenario this is required.

 

ngAfterContentInit:

The ngAfterContentInit lifecycle hook is called after ngOnInit when the component or directive’s content has been initialised; basically when all the bindings of the component have been checked for the first time.

 

ngAfterContentChecked:

Called after every check of the component or directive’s content, effectively when all the bindings of the components have been checked; even if they haven’t changed.

 

ngAfterViewInit:

Called after ngAfterContentInit when the component’s view has been initialised. Applies to components only.

 

ngAfterViewChecked:

Called after every check of the component’s view. Applies to components only. When all the bindings of the children directives have been checked; even if they haven’t changed. It can be useful if the component is waiting for something coming from its child components.

 

ngOnDestroy:

This method will be invoked just before Angular destroys the component.
Use this hook to unsubscribe observables and detach event handlers to avoid memory leaks.
Put cleanup logic in ngOnDestroy(), the logic that must run before Angular destroys the directive.

Angular Services:
A service in Angular is generally used when you need to reuse data or logic across multiple components. Using a service ensures we are not violating one of the Software principles - DRY ((Don't repeat yourself). The logic or data access is implemented once in a service, and the service can be used across all the components in our application. @Injectable() decorator is used to create a service.
Without the service you would have to repeat your code in each component. Imagine the overhead in terms of time and effort required to develop, debug, test and maintain the duplicated code across multiple places instead of having that duplicated code at one central place like a service and reusing that service where required.
 




Providing services:
1.      Root (Singleton): root/userModule
2.      Module:
3.      Component:

Dependency Injection:
It's a coding pattern in which a class receives its dependencies from an external source rather than creating them itself.  A dependency in Angular can be a class, referred as a service or even a simple object. Angular’s Dependency Injection is based on providers, injectors, and tokens.
Every Angular module has an injector associated with it. The injector is responsible to create the dependencies and inject them when needed. Dependencies are added to the injector using the providers property of the module metadata.
Every dependency is a key-value pair, where the key is a token and the value is the object of the dependency. For Services, Angular creates the tokens by itself. For objects, we need to create the tokens.
When a dependency is injected into another block (viz., a component, directive or service), the injector resolves the object from its list of dependencies using the token.
         

The DI in Angular basically consists of three things:
·         Injector - The injector object that exposes APIs to us to create instances of dependencies.
·         Provider - A provider is like a recipe that tells the injector how to create an instance of a dependency. A provider takes a token and maps that to a factory function that creates an object.
·         Dependency - A dependency is the type of which an object should be created.

Angular Injector:
The injector object that exposes APIs to us to create instances of dependencies. In Angular we have one injector at the application root level and hierarchical injectors that parallel an application's component tree. This means in Angular 2, we have one root injector plus an injector at every component level
If a service is registered with the root injector, then that service is available for all components in our entire application including the components in lazy loaded modules. We will discuss lazy loaded modules in a later video in this series.
If a service is registered with the injector at the Application Root component level, then that service is available for all the components in the application except the components in lazy loaded modules.
If a service is registered with a specific component injector, then that service is available for that component and any of it's children. For example, if we register a service with Component X injector, then that service is available for Components X, Y & Z but not for Component A. Similarly, if a we register a service with Component A injector, then that service is available only for Component A but not for Components X, Y & Z



Popular Articles