Showing posts with label AngularJS. Show all posts
Showing posts with label AngularJS. Show all posts

Tuesday, July 30, 2019

Angular + ASP.Net WebAPI Application Performance Optimization - Index and Mind map

This is an index of things which needs to be checked, for performance optimization of a simple ASP.Net + Angular application. The simple application refers to application which read and write to SQL Server. If the application uses some other data store, still the points about other aspects are valid.

The details of each item would be either a link to posts in this blog or link to other resources. If someone is struggling to find where to start or struck on an optimization exercise,hope these questions will light a bulb in their brain. Sorry to say that it is very difficult to find an algorithm which applies every performance optimizations.

Browser side

  • Do we need to support desktop and mobile browsers?
  • Any possibility to avoid Internet Explorer and support only modern browsers:)
  • Do we have separate mobile site with URL or same site is controlled via bootstrap or similar display technique
  • Static assets
    • Are those cached? If not can we cache?
    • If those are cached what is the cache expiry?
    • If those are cached how its done? cache-control or Expires header? Is the cache really working?
    • Is the server properly returning http 304?
    • Are they minified and bundled?
    • Are the images optimized to have small foot print? 
    • Are they served from CDN?
  • Angular best practices applied?
  • If it is AngularJS, what is the feasibility to upgrade to Angular

The network

DNS and routing

  • Hows the DNS resolved to IP?
  • Is the application available public or accessed only via enterprise intranet?
  • What is the network connection band width between clients and server? also between web servers and database server(s)

Network devices

  • CDN
    • Any option for warming up cache?
  • Security / Application Gateways which open packets and scan for attacks.
    • What is the time needed for security inspections? Is it fast, if we bye pass gateway for testing?
  • Network load-balancer
    • Do we have load balancer? Are we reached the height of optimization and need scale out or scale up? In Azure, the best practice is to use LB as the machines gets patches and restarts periodically. Also follow the best practices to group machines so that all of those will not be restarted same time.
    • What is the algorithm used for load balancing?
    • Do we have sticky session need?
  • Common
    • Do we have logs available from these devices?
    • Are the logs enough to confirm that the backing web server is taking time to respond?

Web Server machine

  • Does the requirement of project is practical to the server? eg: One quad core, 8GB VM may never support 100,000 concurrent users even if its a simple company static web site
  • Is the machine / hosting infrastructure in Azure or any cloud? If so do all the best practices followed and coded by considering cloud principles such as retry pattern?
  • What is the status of CPU, Memory, Network etc.. during load test or busy hour?

IIS

  • Logging
    • Does the logging (time-taken field) says requests are taking high time? Please note that that time includes server processing + data transfer
    • Are we logging any custom field which are big in size?
    • Are the extra logging such as failed request tracking enabled?
    • During a load test of busy session
      • If we go to IIS worker process screen are we able to see many requests pending?
      • What is the http queue length performance counter shows ?
      • Are we able to identify one or sub set of requests taking high chunk of processing time other than rest of requests? This can be done by analyzing IIS logs.
  • Static assets - Kind of repetition from previous section. 
    • Are they cached properly?
    • Are we using ASP.Net Bundling or compile time bundled? Are they served in minimized form
    • Can we increase cache expiry?
  • Protocols
    • Any possibility to leverage http/2, if not done?
    • Is it using web sockets?
  • Authentication
    • Is it using windows authentication? If so NTML or Kerberos? Kerberos is recommended for better performance
  • AppPool Recycling 
    • What is the AppPool recycling settings? 
    • Is the recycling causing delay?
    • Any ways to run mock requests so that the cache is populated before real user hit application?
  • Throttling / Limiting
    • What is the MaxConnection Setting and other IIS level throttling?
    • Are there any performance counter showing connections getting queued and rejected?
  • Timeouts
    • Is there any manual test and load test attempted by reducing the timeouts to lowest possible settings? Some times high timeouts cause some requests to occupy entire system resources
  • Payload
    • Does the http compression enabled

ASP.Net Application

ASP.Net pipeline till our code

  • What are the throttling settings at different level?
  • Are there any custom HttpModules which may reduce performance? Any unwanted modules?

Our code

  • Are there anything which can be cached instead of going every time to database? eg: any reference tables which change only by deployment.
  • Are there any retries happening and succeeding after lot of attempts? Try reducing retry count to 3.
  • Are there static variable usage and any potential for lock contention and memory leaks?
  • Are the locks applied to lowest possible code section?
  • JSON optimization
    • Can the property names be shortened?
    • Are the default values serialized into JSON?
  • Are we doing any HTML rendering at server and returning as JSON property? Any possibility to make application as pure client rendered SPA?
  • Do we have high amount of reflection?

.Net General

  • Are there high amount of GC collections? This can be found from analyzing performance counters?
  • What is the fragmentation level in LOH?
  • Can we do NGEN?
  • Any memory leaks in the application? eg: open connections, unwanted static things which may hold objects?

Database

  • Does the applications logs showing that the queries are taking time?
  • Does the SQL setup with possible best practices? eg: temp db, flags, connection limiting etc...
  • Are there any subset of SPs always slow?

Mind map

Finally, there is a mind map created using PlantUML for easy reference. Since this is kept textual in GitHub and rendered on demand, this would be living document than the post.

Details on how to get PlantUML working is available in different post including a YouTube video tutorial.

Other similar links

Tuesday, December 4, 2018

AngularJS Sunset

I was in the mood that AngularJS will live for some more time after the introduction of Angular. That came when the team announced that they will monitor the downloads of AngularJS and define the retirement strategy later. 

But now things have changed. Angular team announced a road map to the end of AngularJS with 1.7 version. When they say end, its the end of new releases and official support meaning there won't be any security patches to the AngularJS framework after the currently set LTS period.

What is AngularJS sunset means to us

The period stared from Jun 30, 2018 and it is till June 30, 2021. It doesn't mean they will release patch for each and every thing. The exact criteria is outlined in the announcement. 

https://blog.angular.io/stable-angularjs-and-long-term-support-7e077635ee9c
https://docs.angularjs.org/misc/version-support-status

We can use AngularJS ever after that period but if there are new security holes identified, hackers can exploit that to do whatever they can. So it is better to migrate to Angular from now itself. We have 3 years to get the migration done.

Bye bye AngularJS

Tuesday, August 29, 2017

Azure Application Insights - End to end correlation from Angular to internal WCF services

Azure AppInsights is one of the PaaS offering which can be easily configured to our application and leverage capabilities. And it really works without any changes in our application. But does it helps us more than any other tools? May be yes with default setup. We will really love it if we can get end to end correlation to understand what is happening in our system. Production debugging will be a breeze with correlation. 

This post is talking about how can we correlate activities happening in different tiers of our system and see it in one place. Lets take a scenario where an Angular application is interfacing with users, it calls ReST endpoints to talk to front end services and front end services communicate with other internal services. We can correlate operations originating from client side to related operations happening in the internal services.

Prerequisite

  • Basic knowledge about AngularJS 1.x
  • Knowledge about WCF services.
  • Knowledge about setting up AppInsights service

Sample setup

It is advised to download the sample from below location before reading further. Below goes the structure of sample.

AngularJS application just does one thing. Finding the area of circle if we give radius. For finding area, it calls a ReST web service.
It sends one event during startup. Another one during calculating the area ie when calling the FronEndWCFService. These are custom AppInsights events

FronEndWCFService is a simple WCF service hosted using webHttpBinding to get ReST end points. It calculates the area using the parameter radius. It don't know the value of pi. It dependent on InternalService to get the value of pi. During the calculation it sends some custom events/operations to AppInsights.

InternalService is hosted using net.pipe binding. It has one method which returns the value of Pi. It also sends some custom events to AppInsights.

The above 3 components are hosted inside IIS and enabled with AppInsights for default system events.

Running the sample

  • Make sure the 3 web applications are hosted in IIS.
    • The web application has to net.pipe binding to host InternalService.
    • Try to browse the service Urls.
  • Give the Url of InternalService in the web config of FrontEndWCFService so that it can call.
  • Obtain AppInsights instrumentation key by either creating a new instance in Azure or copy from existing AppInsights instance. Replace this key into web applications. Better use visual studio search and replace and the word to replace with key is {Your Key} .There are 3 files to get the instrumentation key. 
    • /AngularClient/Views/Shared/_Layout.cshtml
    • /FrontEndWCFService/ApplicationInsights.config
    • /InternalService/ApplicationInsights.config
  • Run the AngularClient application in browser.
    • During the application load, it will log "Custom init event from JS"
    • When we give the radius in the text box and click on button it will log "Custom event from JS before service call"

Viewing the AppInsights

It may take some time to get the entries reflected in the AppInsight in the Azure portal. It is better to go to the analytics portal of ApplicationInsight instance and view the results. In the analytics portal, the details can be seen as follows.

The entries highlighted in the name column are the custom events generated by different tiers in the system. Along with custom events the system will generate event if AppInsights collectors are attached to the processes. That can be done by connecting interceptors in the WCF or HttpModules in Web request pipelines.

Understanding correlation results

The operation_id column is the id which really correlate the operations. The id has to be unique and the parent_id can be any id used previously. It can be a tree of related events.

Don't get confused on the term 'events' used here. AppInsight can accept events, operations, traces etc...For easy reference term event is used.

Q&A

How does a web request from Angular gets correlated with servers

When we send web request from Angular or any client if we send http header "Request-Id" it will be treated as operation_id by server side, if we have the AppInsight request interceptors

Why the sample has 2 methods in Angular to write custom AppInsights

When the application is getting initialized, the appInsights object may not have the context ready.If so we have to put into queue. Once the context is initialized, we can use it to set operation_id. At that point the queue will be null.

Should I write any code for intercepting incoming web/WCF requests to read correlation data?

No we just need to use already available nuget packages and setup our web.config appropriately.

Should I write any code for intercepting the out going web/WCF requests to write correlation data?

No we just need to use already available nuget packages and setup our web.config appropriately.

References

https://docs.microsoft.com/en-us/azure/application-insights/application-insights-correlation
https://github.com/Azure/diagnostics-correlation
https://github.com/Microsoft/ApplicationInsights-JS
https://github.com/aspnet/Microsoft.AspNet.TelemetryCorrelation
https://mitra.computa.asia/article/msdn-modifying-and-filtering-telemetry-appinsights-javascript-sdk-telemetry-initializer

Tuesday, May 16, 2017

Protractor - CI with AppVeyor issue on webdriver-manager update

Protractor is a nice tool to do testing of Angular applications. It really shines when used in continuous delivery scenarios because of its end to end testing capabilities. We can simply host the site and run our tests with Protractor. But when we use it with hosted CI solutions there is a chance for getting the below exception in the build process.

(node:1184) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: Failed to make Github request, rate limit reached.

This happens when we issue the below command which we cannot avoid to get it working.

webdriver-manager update

One such failure can be seen here. What is really happening is that during the update, the webdriver-manager is trying to download something from GitHub for Gecko driver. Since most of the hosted CI solutions use same single IP to access outside internet, the GitHub API limits comes into play.

This is already known issue and the only way is to disable Gecko driver for now. Command to disable Gecko driver is as follows.

webdriver-manager update --gecko false

Thanks to the AppVeyor support team.

Tuesday, March 14, 2017

Architecture of JoymonOnline - Serverless

This can be considered as continuation of 3 old posts.


The first post, talks about the architecture of my personal site JoymonOnline.in. Other posts explains about new software architecture trend called Serverless and the conversion of my site towards Serverless architecture. 

This post explains the new architecture.

Architecture of Serverless JoymonOnline.in

Hosting

Hope the diagram is pretty much self explanatory. Its going to be pure client side single page application (SPA). In other words there is no page refresh when user goes to different view. 

The domain is going to be continued with Godaddy. But the hosting will be done inside Github pages, which is free. When we say Github hosting is free, it comes with limitations and quotas. But for my personal site those limits are not going to hit at least for some years :). It clearly tells that for a different person who is really famous the limits will come into play. So Github pages is not the silver bullet for hosting.

Flow

Once the client browser gets the static site(html,js & css) from Github, it becomes active by bootstrapping Angular components. It calls required services present in external systems for data. Most of these external systems are already mentioned in my previous post. After the data retrieval, the JavaScript updates the DOM with the help of AngularJS framework. The Angular JS version is 1.x used and there is a blog post explaining why 1.x is selected when Angular 2 is out.

Future candidates


  • Azure Function - For Github & Blogger API due to anonymous quota limits.

Pros

  • No cost to host web site. Just the domain registration. Most of the services are free.
  • No need to license development tools. For  ASP.Net, Visual Studio community edition don't have much features.

Cons

  • Multiple points of failure - Earlier, if JoymonOnline.in domain was accessible entire site works. But now all the domains of external systems should be accessible from the client machine which is not possible in all places.
  • More dependencies - Has to monitor what changes in external systems and has to maintain accordingly.
  • JavaScript restriction - Some browsers (inside some companies) might be still blocked to download JavaScript and execute.
Note - As of today (14Mar2017), the redirection for the site from Godaddy to Github pages to serve site has not done. But the site is up and running in Github pages joymon.github.io.

Tuesday, January 31, 2017

Serverless JoymonOnline.in - Intermediate update & experience

The Serverless is the new buzzword and it is getting really good attention. It is nothing but an architectural style where developers don't need to worry about servers for deployment, scaling etc... Just write and push the code. It will scale automatically.

In the previous article about Serveless, I had mentioned I am in the process of converting my personal site to Serverless. The decision was purely financial. Why should I give money to GoDaddy for hosting some pages which can be served by GitHub pages for free?

This is just an intermediate update about that effort.

Steps

Below are the steps taken during this effort. It may vary from project to project based on complexity. JoymonOnline.in is just a profile site which don't use any custom modules or handlers.
  1. Avoid server side data rendering
    1. Replace .Net third parties with equivalent JavaScript API
    2. Convert each .aspx page to contain its own Angular application.
    3. Avoid ASP.Net specific skin files and use pure CSS
  2. Client side integration
    1. Replace ASP.Net master page with Angular routing.
    2. Bundling, Minification, CI & CD
  3. Backward compatibility
    1. Links
    2. SEO
Please note that these steps are relevant if the decision is 
  • Not to start a fresh app
  • To ensure that the code base is ready to delivery at any point in time.
If business can keep quite during the migration or the development can be done is separate branch ad later merge, these steps are not required. Just start a new app.

Avoid server side HTML rendering

The current www.JoymonOnline.in site uses ASP.Net web forms technology. In other words it uses server side HTML generation and sends it to the browser. There is no rule that Serverless should not use server side rendering. It can use, provided the server side rendering can scale automatically without doing any extra task. For example a WebAPI service end point can return HTML and it can be rendered at browser with the help of JavaScript. That introduce some kind of client side HTML manipulation. Once we take that decision, there is not much differences between rendering full contents at client side v/s rendering some contents at server and inject it to client side views. So in short Serverless goes hand in hand with client side web apps which we generally call SPA (Single Page application). It can't be done in one step. So sub tasks are as follows.

Replace .Net third party with JS API

If we want to replace the third party .Net API with JS equivalent there are 2 options
  1. Use equivalent JS library
    1. Has to make sure the critical API keys are not exposed. Can do client site authentication or be happy with free quota.
  2. Write a FaaS which uses same .Net API and let it return required data to client.
    1. We have to make sure it is secured and key present only at service and service can only be called from our app.
Coming back to JoymonOnline.in, it uses some third party APIs at server side to get data and render  via ASP.Net. GitHub API, Blogger API are the main third parties. So these calls needs to be done from client machine. For GitHub, it was easy as there is straight JS library. But for Blogger it was little difficult as the Google feed API is discontinued. Finally it worked with blogspot feed url.

But for GitHub, there is a limitation due to the quota for unauthenticated API calls. Since the developer key cannot be exposed to client, it allows only 60 requests / hour / IP address. Since JoymonOnline.in is expecting more than 60 calls from single API it is ok to go with quota. 

Convert each .aspx page to contain its own Angular application

Next step is to convert page by page to Angular. This is to make sure that the application is always in functional condition than like a demolished house before renovation. Convert individual pages to its own angular app and render that app inside the ASPX pages. Let that page be just an angular app host. Noting else. 
In this step we have to identify equivalent third party ASP.Net UI controls, if applicable. For example how to replace Telerik web forms controls with KendoUI.

In case the plan is to first get to ng1 and later to ng2, I would strongly recommend to go with components rather than directives. TypeScript is becoming defacto standard for angular. Use that to avoid debugging time. After this step, we will have ASP.Net application but the functionality working from browser via angular.

Avoid ASP.Net specific skin files and use pure CSS

Next thing to tackle are the styles. If the application is using skin files, we have to get equivalent CSS files. Sometimes we may need to do this along with the previous step. Depends on nature of third parties and our code.

Client side integration

The next big step is to integrate things at client side.

Replace ASP.Net master page with Angular routing.

The main pending thing is to have angular master page and routing. We already have separate components in different apps. Just create new app in index.html and have the routing to load proper components. This steps sound simple but it has many things to do.

Bundling, minification, CI, CD etc...

Now its the time to optimize the site and do integration to build pipeline. Till this point, the expectation is that we are able to use existing build system. Recommended is Webpack for client side activities such as compilation and bundling. CD is always confusing with Continuous Delivery and Continuous Deployment. At least make sure it is Continuous Delivery.

Current, JoymonOnline.in using AppVeyor for CI & CD. Though AppVeyor is mainly intended for Windows development, it supports NodeJS as well. So decided to continue in AppVeyor. At this point the build output will be pushed to \docs folder as staging. GitHub pages recently started supporting serving web pages from \docs folder instead of gh-pages branch.

It is not fun to develop JS based client side app using Visual Studio solution file. After this step we don't need .sln file to work with. Node rules the client side web development world. At some point we have to introduce Node. So why not from the start if it is possible to live with only Node? When it is said 'start', it means the starting of the migrated application. If anyone feels they can live with .sln file without Node, let them continue. But better don't use mix. Comparing Node with .sln is not the right comparison. But the intention is to use Node and its ecosystem such as NPM & package,json etc... 

Backward compatibility

These may be optional depends on scenarios.

Links

This will make sure that the bookmarks saved by users are still valid. The old ASP.Net application could have modified to redirect the .aspx pages to new URLs. But for JoymonOnline.in, this is not done.

SEO

The SEO efforts needs to be put if the application is public facing.

These steps itself needs explanations which will be having contents enough for separate post. At this point, the entire application has converted and available at joymon.github.io . The main pending thing is to change settings in GoDaddy to point JoymonOnline.in records to joymon.github.io.

Tuesday, January 24, 2017

My JavaScript Module experiments - CI & CD

This is second in the series "My JavaScript Module experiments". This post talks about setting up a simple CI & CD pipeline in modularied JavaScript environment using AppVeyor as CI & CD runner.

Other posts in this series below.

1 My JavaScript Module experiments
2 My JavaScript Module experiments - CI & CD

Introduction

This post directly jumps to setting up CI & CD for modularized JavaScript. Here also Webpack is used as module loader as well as to do other operations such as TypeScript transpilation, minification etc...

AppVeyor & GitHub Pages

AppVeyor & GitHub pages are 2 external services used here. AppVeyor provides free CI & CD service for open source projects and GitHub Pages provides free hosting from Github repositories. Basic knowledge about these services are considered as prerequisites.

AppVeyor is mainly targeted to Microsoft .Net stack and it automatically takes care, if there is a Visual Studio solution file. But we can make it work for Node as well by disabling the default build process. That can be done by simple changes inside appveyor.yml file. AppVeyor supports configuring CI & CD activities either in a appveyor.yml file found in the GitHub repo or through their UI. Here we are using the appveyor.yml  file as its easy to understand. Though is a file publicly accessible file in repo, we can include sensitive information inside it with encryption.

Separation of Concerns - What does what

When we look at the technologies used, we can see those can so same tasks. AppVeyor can run normal commands as well as PowerShell and even start NodeJS which in turn starts Webpack. Using normal commands, PowerShell & Node we can do file copy operations. Webpack which can be started as command can also execute code which does file copy. What is the problem if all the technologies can do same task? The problem is lack of clarity on which component does what.

For small projects, it is fine. We can have AppVeyor scripts and Webpack do file copy. But when we think of larger projects we need to have clear distinction on that should do what. Else it would be difficult to maintain in future.

The simple rule can be to assign the dev related tasks such as compilation and bundling  to Webpack and deployment tasks to the AppVeyor scripts such as pushing to GitHub. Ultimately AppVeyor is ruling the environment. So there should be one AppVeyor command which starts Webpack. Summarized duties as follows.
  • AppVeyor
    • Downloads the source code
    • Install proper Node version and setup environment by installing packages.
      • This include the Webpack NPM package too.
    • Starts Webpack
    • Run tests.
    • Collect the artifact and deploy  
  • Webpack
    • Compilation
    • Do minification / Uglify
    • Create bundle
    • Emit the output to \dist folder. (\dist is just a convention. It can be any folder)

The CI & CD workflow

The CI & CD workflow can be simple. After the transpilation &  bundling the output HTML app which includes html, js, images etc...needs to be pushed to the \docs folder of repository. The GitHub repository can be configured to serve web pages from \docs folder.

Sample

It is easy to explain the but there are high possibility for missing steps. So to make it more understandable, please refer sample repo located at below location

  • It does CI & CD on 'TypeScript-Angular1-Adv folder'.Other folders are showing different Webpack samples.
  • Push the output to the \docs folder in same repo. \Docs folder is configured to GitHub pages to serve from.
  • It is little advanced Angular 1 sample done using TypeScript.
  • Node & NPM used as dev technology.
  • AppVeyor.yml has all the CI & CD steps. The GitHub token is encrypted and kept inside it.
  • Since the aim of that folder is to minimally show the webpack features, at this point there are no tests included.

Tuesday, January 10, 2017

My JavaScript Module experiments

Background

After I wrote my post about the selecting Angular 1 for my personal site when Angular 2 is out, I seriously started thinking about myself. Am I too joining the group who hate changes? As mentioned in that post, the main bottleneck is not the concept or syntax of ng2 nor it's performance and stability. The problem was around tools. What are those tools doing? They help us to write modularized JavaScript. They do transpilation, bundling, minification etc...

If we download standard ng2 project starter template, we will get pretty much a good running starter. The tools will be already configured. From there we can simply add our own functionalities. Unless we have crazy requirements, that configuration will work. We just need to add features. Then what is the trouble? The trouble, at least I had was that I am not getting how those tools are doing the magic. I checked with some other people who has problems with ng2. I could see they also have trouble understanding the tool chain. Its very difficult to move ahead in that magic setup especially, if we are coming from little old school who want to know exactly how the software works. For most of the newbies, it doesn't matter. As far as the setup/tool chain is working they can code new features.

Is there a way to survive in web development without knowing bundling? The answer is 'no' as that is the way forward to build huge apps.

So what is the solution. Learn the JavaScript module system from basics with simple samples than  starters which are configured to use features such as transpilation, source map, minification, unit testing, dev & prod  modes etc...

This post explains how I learned module system in my way, though there are tons of tutorials explaining the JavaScript module system. Most of the steps will be pointing to external sites to avoid duplicate content and of course they explain better than me.

What is JavaScript module system

If we have background in Java, it is the equivalent of Java package system. For .Net people, it can be compared to assemblies. Simple as that. But since the JavaScript engines don't have native support for modules, we have to rely on different tools which does the module implementation. To me its like workaround till the browsers or the JS engines know what is module. May be at least in the case of module loading. I am not expecting any JS execution environment will ever help us to create a bundle.

What is the relation to Angular 2 and these module system? Angular 2 uses these module concept and it is good to follow the same for our app as well. So if we download any Angular 2 sample or starter, we can see it uses SystemJS or Webpack. As mentioned earlier, either we can just download a starter and extend it without knowing how the magic works or learn what is the module system from the scratch.

Selecting WebPack

If we google for JavaScript module tools we will see many. Browserify, RequireJS, SystemJS, webpack to name few. We can debate which one is better for days and that itself require one separate post. So for the time being selecting webpack as it is selected by Angular-cli and at least it is not in beta.

NodeJS n NPM are everywhere

It is very difficult now a days to do web development without knowing node and its package management tool NPM. Though Node & NPM doesn't have any role inside browser they are used in tooling side. Webpack also comes as NPM package. So this post assumes reader has knowledge about NodeJS & NPM 

Step 1 Understand via simple ECMA 5

The first thing as JS developer unless we are born to ES6 is to learn how we can modularize ECMA5 or ES5 or simply the traditional JavaScript code. There is no need to write one more tutorial to understand how ES5 can leverage webpack. Just go to 'getting started' tutorial of webpack and try it.

Please try till Section "THE FIRST  LOADER" in the below 'getting started' link.

http://webpack.github.io/docs/tutorials/getting-started/

Before using loader, it is good to know something else. Obviously we should come back to loaders. Because loaders does magic. 

After trying the above, remove the .js extension from require and run. Sample below.

var content = require("./content.js");
to 
var content = require("./content");

We can see still it is working. The file extension is something optional.

Step 2 - webpack.config.js

If we go through any webpack tutorial, we can understand that most of the issues using webpack is because of wrong webpack.config.js. So it is important.

Minimum config

Lets see what is the minimum config required for this webpack.config.js file. Have a look at the below link starting from "Defining a config file" section where it is explained clearly. Read till the "Webpack loaders and preloaders".

Watch mode

This is a useful mode in development. This is explained in the above tutorial.

Dev Server & hot reload

These are again development time features where we can start a light web server which monitors the development changes and reloads for us. This save good amount of time in switching to command window and typing commands. Yet to see what will happen on performance, if there are 100s of files.

The feature is explained in the above tutorial.

Step 3 - Enter TypeScript

A big no to ES6 at this point only because it lacks compile time type system. This is again debatable. If we are dealing with small applications, it is better to be dynamic typed ie pure JavaScript. But for bigger apps, type checking is must. Otherwise it will take a good amount of time  ie time needed for finding out what are the members of objects and what a function accepts and returns.

In this section we are going to see how TypeScript and webpack works together.

The below article below explains TypeScript and how to use TypeScrpt with Webpack. Read from beginning till "Watch Support"
http://www.jbrantly.com/typescript-and-webpack/

Why till "Watch Support". Because it then includes jQuery. Our focus is to understand how webpack can be used to process TypeScript not with jQuery.

Now its time to clone my webpack repo given below. This will be used going forward in this post.
https://github.com/joymon/webpack-starters

It has a folder named ECMA5-TypeScript. Point command line to that folder and run webpack command. We could see it transpiles the logger.ts & tscomponent.ts and output bundle.js along with other ES5 modules. Running the index.html from disk will show some log statements.

"TypeScript Worked !!! - logger module loaded" - Means a ES5 module was able to load TS module.
"TS component which has dependency on JS component worked" - Hope it is self explanatory

Lets see how it worked

Loaders in webpack - ts-loader

Loaders help to process the file, if those are in different formats. For example, today browsers don't know how to read and execute the TypeScript. So the TypeScript needs to be transpiled to JavaScript. That can be done by using the webpack loader mechanism. In this "webpack-starters" repo, ts-loader is used for that purpose. The configuration is present in the webpack.config.js.

After loader does its job, the final bundle.js is created as usual. index.html only knows bundle.js.

TypeScript loading ES5 modules

If we need ES5 code to load a TS module it is easy. Since ES5 don't care about types, we can write any valid js and at runtime only it checks the objects. But if we want to use ES5 module in TS, the first thing is to tell, what is require() function. TypeScript as language don't know what is require(). So to tell TypeScript about require() we have to use nodejs typing. Node typing has the definition for require(). 

To add Node typing the sample is using a package called  @types/node. Refer package.json. 

Please note since this post is not aiming at teaching TypeScript language and what are typing files,  more details on @types/node are omitted.

Step 4 - TypeScript with AngularJS 1.x

Here we are going to next step of using AngularJS 1.x via webpack module mechanism. The sample is present in the TypeScript-Angular1 folder of the "webpack-starters" repo mentioned above. Sample just shows a simple Angular 1 application with one component.

Setting up ng1+TS+webpack from scratch involves multiple steps which are given below
  1. Initial setup of TypeScript+webpack
  2. Include the NPM package for Angular
  3. Include the @types/angular.
  4. A module where angular.module() is called to setup angular. In the sample refer to ngModule.ts
  5. An entry point(bootstrap.ts) module where we can call the above module and add other Angular constructs such as components, services, filters etc...Big sorry for directives for easy conversion to ng2.
  6. Index.html to use required Angular directives.Minimum ng-app.
  7. While adding components export them
Now have a look at the TypeScript-Angular1 folder of the "webpack-starters" if not done already. Below are some questions which might have popped up. The answers are also given along with questions,
  • Why ngmodule.ts? 
    • This is just a class for wrapping the original angular object. This gives us a common place for registering the angular object such as registering components, filters, services etc...This is optional. Just make sure the code which is executing angular.module and other registration functions are getting called.
  • Why bootstrap.ts
    • This acts as entry point for the application. It imports all the other modules which contains the app is ngmodule and all the angular constructs. For simplicity the sample only includes a simple component.
  • How did the require("angular") worked? Who exported the angular library for webpack?
    • This is done by the node_modules\angular\index.js .It exports as angular. If we change this we can see the module is not found.
  • Why webpack-dev-server is needed. Can't we double click and run from the disk?
    • For just ng-app to work, there is no need of web server. But for angular to locate and load the html template, it requires app to be served via url not just from disk. We can even use IIS to serve the folder. Only requirement is to navigate via http protocol.
Any new questions can be asked in the comments which will be included into the post later with answers?

More

This post shows the tip of iceberg. There are many more things which are required to setup a professional application for development and production. With this basic understanding of module system, learning those will be easy.

Some links are given below which are related to JavaScript modules and bundling

Tuesday, January 3, 2017

TypeScripting AngularJS 1.x - Filters

This post is part of TypeScripting AngularJS 1.x series. Other posts are listed below. The sample code is created using Angular 1.5.9, TypeScript 1.8 & angularjs.TypeScript.DefinitelyTyped 6.5.6. 
  1. TypeScripting AngularJS 1.x - Define module
  2. TypeScripting AngularJS 1.x - Define module - improvements for big enterprise apps Improvement
  3. TypeScripting AngularJS 1.x - Using $http 
  4. TypeScripting AngularJS 1.x - Directives
  5. TypeScripting AngularJS 1.x - Filters

Angular Filters in TypeScript

These are small handy reusable functions which can help us to format the data while displaying without modifying the underlying model. Currency and date formatting are excellent examples. We don't need to keep one more property in the model which holds short date of another date object just for displaying. There are many filters built into Angular and it allows us to create new as well.

Below is a code snippet to create custom Angular filter named. HTMLTagRemover using TypeScript. As the name implies it removes any html tags in the string passed to it. 

export class HTMLTagRemover {
    public static filter(): Function {
        return (text: string): string => { 
            return text ? String(text).replace(/<[^>]+>/gm, '') : '' };
    }
} 
AppModule.getInstance().registerFilter("removeTags", HTMLTagRemover.filter);
It is a simple factory function which returns the actual filter function. The last line registers the filter with Angular application. It requires some prior knowledge related to defining Angular module in TypeScript way to understand how to get the AppModule.getInstance() and how it works.

Below is the code of registerFilter() in the AppModule class
registerFilter(name: string,fun:Function) {
    this.app.filter(name, fun);
}
The app is the real Angular object

Dependency injection 

Without dependency injection Angular is never complete. How can we get the dependencies injected into this filter?
export class HTMLTagRemover {
    static $inject: string[] = ['$sce'];
 
    public static filter($sce: ng.ISCEService): Function {
        return (text: string): string => {
            console.log($sce.trustAsHtml(text));
            return text ? String(text).replace(/<[^>]+>/gm, '') : ''
        };
    }
}
This injects $sce which can be used to sanitize data into our filter. Similar to $sce we can inject our own services too.

Complete code can be found in my personal web site source in Github.

Tuesday, December 27, 2016

TypeScripting AngularJS 1.x - Directives

This post is part of TypeScripting AngularJS 1.x series.Other posts are listed below.

  1. TypeScripting AngularJS 1.x - Define module
  2. TypeScripting AngularJS 1.x - Define module - improvements for big enterprise apps Improvement
  3. TypeScripting AngularJS 1.x - Using $http 
  4. TypeScripting AngularJS 1.x - Directives

Angular Directives using TypeScript

Below is a mechanism to create typed Angular directives using TypeScript.

The main thing is that our directive class needs to implement ng.IDirective. After that we can have the corresponding ng.IDirective members. The advantage here is that we don't need to memorize or google for what are the members required for directive. Its all there in ng.IDirective

export class ProjectsDirective implements ng.IDirective {
    public restrict: string;
    public templateUrl: string;
    public controller: any;
    public controllerAs: string;
    public bindToController: boolean | { [boundProperty: string]: string };
    public scope: boolean | { [boundProperty: string]: string };
    constructor() {
        this.restrict = 'E';
        this.templateUrl = 'JS/app/projects.component.html';
        this.controller = "ProjectsController";
        this.controllerAs = "ctrl";
        this.bindToController = true;
    }
}

Above code snippet is taken directly from my personal web site. The members such as bindToController, controller etc... are optional. This is not enough to get the ProjectsDirective available in our application. For that we have to register it with Angular application.

Code snippet below shows the registration.

AppModule.getInstance().registerDirective("projects", () => {
    return new ProjectsDirective() 
});

It gets the instance of the Angular module and calls the registerDirective function. The object here is  a wrapper over real Angular module object. That function in turn calls the real Angular.directive function.

Dependency injection

The dependencies to the directive can be accepted by the directive factory / creation function. That function then can pass those injected objects to the directive constructor. 

Sample code

The code is from my personal web site and it is in GitHub.
Simply clone the repo and compile using Visual Studio 2015. It uses TypeScript 1.8.

Tuesday, December 20, 2016

Why I choose Angular 1.x for www.JoymonOnline.in while Angular2 is out

What is the present tech landscape?

If we look at present web development technologies, we can see everything is revolving around client side HTML generation. The interesting thing at client side web development is that, there are new tools and frameworks getting released every week. It is very difficult to select one and get something out using that. By the time we complete analysis on one tool or framework, the next one will be out by saying its better than the existing. If we keep analyzing, we never will be able to do something useful.

Recently, I decided to convert my personal web site to pure client side solely to avoid hosting cost. It currently is .aspx based server side html generation model. The server side code help me to connect easily with third parties such as Github, Blogger etc...I don't need to worry about whether the viewers network blocks GitHub or Blogger APIs. If I am converting to client side I had to write some JavaScript to do that third party integrations. Hence I have to analyze the client side technology stack. Important thing for me is to convert the app to pure client side app before March 2017 else I have to renew the hosting space again. So its is highly time bound

In short, I selected Angular JS 1.x over other technologies even by avoiding Angular 2. This post talks about my journey towards Angular JS 1.x to do this time bound task over Angular 2.

There is no standard tooling for ng2

We can easily compare the scenario with the US restaurants v/s Indian restaurants.
In India, if we got o middle or lower level restaurants and order Masala Dosa, they will give us a standard Masala Dosa. The standard changes from state to state and district to district. Very less options to customize. But if we are in American restaurant, they will ask so many questions, if we order a sandwich. What type of cheese, what ingredients, type of bread etc...

In Angular 1, things were pretty much like restaurants in India. There are standard tools. Only some confusion comes in the language. Whether to go with JavaScript, TypeScript or CoffeeScript.

But in Angular 2, there are many tools and we have to pick up the combination what works for us. What framework for module loading, how and when to compile TypeScript to JS, how to do packaging.  New tools are popping up frequently too. Though there is official recommended tool chain, I don't think it is working out for many developers. May be they are not productive or are complex which needs more technical knowledge. Else people will never spend time to invent more and more tools.

Though the ng2 framework is kind of mature the tools are not.

This may be controversial statement. There will be many disagreements as some tools works for some and all can find some combinations.

Many tools are in beta

The main tool came along with ng2 is the command line tool called  Angular cli. At the time of writing this post, it is still in beta. They recently switched from SystemJS to WebPack. 

Some tools doesn't mean for Windows

Suppose we take the risk of using a beta tool for doing development, there are still issues. Some are more tailored to OS other than Windows. Though we can mitigate the issues, it eats our time.

Compiling TypeScript in browser is for demos till browsers understand TypeScript

Now a days most of us agree that the compilation of TypeScript needs to be done along with build process. Though there are options available to compile TypeScript in browser, it will reduce the start time of our application. The other group is telling that, some browsers are expected to support TypeScript directly in future so the compilation can be done by detecting the browser.

This is same, if we select ES6 as well. Some says we should compile down to ES5 always the other side argues that it should be done at Browser by detecting the feature support.

Its all good if we are developing a demo to get a project or samples. But for something to be done in a time based manner, we cannot be trapped in these arguments.

Why not code Angular2 in ECMA 5 JS?

Come on...Though there are many good tutorials available which explains writing Angular 2 application using ES 5, I never want to do. There are many reasons. One big reason is going forward, if we struck in an issue the sample snippets or solutions provided will never be in ES5. We have to find out how to convert the ES6 or TS code into ES5.

But we should definitely try writing the Angular 2 code in ES5 for understanding purpose. Else if something goes wrong in our compiled ES5 code, we may not be able to find out.

Why not build a brand new site and switch one morning

This is a famous question we all might have faced during any migration effort. The developers who never tried rewriting a software under proper timelines, will always advocate this strategy. But others never agree on complete rewrite. When we look at any software which is running for long, we can see so many pain points of previous developers and hacks, anti patterns etc...If we just start rewriting,  we will also have to go to the same pain points. So why should we take unwanted risk? Lets always divide and conquer part by part.

In my personal web site scenario, I was the only developer and I am the one who is going to rewrite also. But I had taken so many things from here and there during initial development and unfortunately, I didn't document anywhere even in this blog. Since I use my brain mainly for generating ideas, I don't remember all the pain points now. Hence there is no need to take risk.

Again why should we take same old risks as there will be new risks during the conversion to client side.  By this time I already got an issue related to Angular date formatting in Windows Phone 7. Please don't ask apart from me who else using Window Phone.

The continuous delivery system

I currently use free service from AppVeyor to run continuous delivery of my web site. Since its a Visual Studio solution, AppVeyor detect it, compile the same, run tests, package and deploy to the server. To my best understanding ng2 heavily depends on NPN though there is a nuget package for ng2. AppVeyor can be configured to use NPN, but it is again time consuming.

When is the best time for ng2

None of the tools and technologies are going to be there for ever. The technologies are suitable to the current landscape. There are new cool technologies coming out. Below are some

  • ReactJS (This is already out. Though it is not a full fledged framework like Angular, it is a choice)
  • WebComponents
  • WebAssembly (we may be developing browser apps using C#. Remember the old Silverlight days)
The driving factor in this conversion is the cost to host ASP.Net site. After that based on the situation, there may be pressing situation to convert to any one of the above technologies. But right now, it is impossible to predict.

These are my own views about selection of AngularJS 1.x for a personal/portfolio site. These are not  applicable to all the scenarios. 

Tuesday, May 17, 2016

TypeScripting AngularJS 1.x - using $http

This is a continuation of older posts in TypeScripting AngularJS 1.x series. Here lets see, how we can use the $http service in typed way using TypeScript.

The API

The main TypeScript type, we need to understand here, is the ng.IHttpService. This is the equivalent type of $http object. This comes via the AngularJS typedefinition file which can be downloaded from nuget. The another type is the ng.IHttpPromiseCallbackArg<T>. This is the container which is returned via the Then() method.

Sample

Before coding the client side, lets see the server side code which is going to be called from browser.
public class HomeController : Controller
{
    public ActionResult GetCountryMetaData(string id)
    {
        RegionInfo rInfo = new RegionInfo(id);
        return Json(new
        {
            DisplayName = rInfo.DisplayName,
            Currency = rInfo.CurrencyEnglishName,
            CurrencySymbol=rInfo.CurrencySymbol
        },JsonRequestBehavior.AllowGet);
    }
}

This action method takes id as string and return the country / region details. Anonymous return type has 3 properties which are all strings.
If we host this inside IIS using web application named testapi, we can invoke the API by browsing the below url.

http://localhost/testapi/home/getcountrymetadata/nz
Result will be - 
{"DisplayName":"New Zealand","Currency":"New Zealand Dollar","CurrencySymbol":"$"}

Let's see how this can be invoked from TypeScript without using 'Any' type.
export class CountryController {
        testprop: string;
        emp: Country;
        http: ng.IHttpService;
        Countries: Array<Country> = new Array<Country>();
 
        constructor($scope: any,
            $http: ng.IHttpService,
            this.http = $http;
            $scope.Countries = this.Countries;
        }
        getForChina() {
            this.http
                .get('http://localhost/testapi/home/getcountrymetadata/cn')
                .then((result: ng.IHttpPromiseCallbackArg<Country>) => {
                    this.Countries.push(result.data);
                });
        }
}
class Country {
    DisplayName: string;
    Currency: string;
    CurrencySymbol: string;
    constructor() {
 
    }
}

Casting in TypeScript

The first confusion will happen on the casting of http result to Country object. Where we are telling the return type is Country in TypeScript?

Here is the difference between the real type safe languages such as C# / Java and TypeScript. In TypeScript since its finally running as JavaScript, we can accept values in any type, if that looks similar to the incoming object. Here the output of web request has properties which are matching to properties of Country class so those are just copied. If there are no matching properties still this code compiles but at run-time the properties of result object will be undefined. No exception in any case.

We can make it more TypeSafe by adding generic type to the get method.
this.http
    .get<Country>('http://localhost/testapi/home/getcountrymetadata/cn')
    .then((result: ng.IHttpPromiseCallbackArg<Country>) => {
                    this.Countries.push(result.data);
    });

Passing typed parameters to $http.get()

The get() accepts an optional ng.IRequestShortcutConfig object too. Lets see how that can be passed into the method in type safe way.

var config: ng.IRequestShortcutConfig = {};
            config.cache = true;
            this.http
                .get<Country>('http://localhost/testapi/home/getcountrymetadata/cn',config)
                .then((result: ng.IHttpPromiseCallbackArg<Country>) => {
                    this.Countries.push(result.data);
                });

Interesting thing here in TypeScript is, we don't need to create the implementation class to use the interface. This again is feasible, since it runs in JavaScript engine where there is no type safety. After the compilation everything is JavaScript. We know that, there is nothing called interface in JavaScript runtime.

The {} creates an object just like in JavaScript. After that we can set required properties. Since we have declared the variable as ng.IRequestShortcutConfig, we will get intellisense on the config object. We don't need to remember all the properties, which we need to do in pure JavaScript programming.

Here config.cache.= true tells the $http, to cache the requests using Angular JS cache factory.

Happy TypeScripting...

Tuesday, May 3, 2016

TypeScripting AngularJS 1.x - Define module - improvements for big enterprise apps

Improvements for enterprise apps

We have see that there is a typed way to define modules and setup the Angular constructs such as services, controllers etc...This works great in small apps. But there is a problem, if we are developing an big enterprise app with many developers adding new controllers, directives frequently. In that situation, everybody will be competing for the one app / module file.

Below can be our aim when designing TypeScript Angular module class.
  • No need to repeat the ng-app name in every file.
  • There should be one central place for knowing what are the components registered.
  • Every angular component registered in the system should be testable using dependency injection.

How to fix it?

What if we expose a method in the Module to registerController, Directive etc...Those methods can be called by each file which contains different Angular components to register themselves? The object of Module can be exposed via singleton. Lets see the code below for the Angular module wrapper class.

CountryModule.ts

module CountryApplication {
    "use strict";
    export class CountryModule {
        //Do not expose the property as it is not expected to change from outside.
        private static currentCountryModule: CountryModule;
        public static getInstance(): CountryModule {
            return CountryModule.currentCountryModule;
        }
        private app: ng.IModule;
 
        constructor() {
            this.app = angular.module("CountryApp", []);
            CountryModule.currentCountryModule = this;
        }
        /** Acts as central place for registration. But somebody adds new controller they don't need to edit this file.
        */
        registerService(name: string, serviceConstructor: Function): void {
            this.app.service(name, serviceConstructor);
        }
        registerController(name: string, controllerConstructor: Function): void {
            this.app.controller(name, controllerConstructor);
        }
    }
    var hrApp: CountryModule = new CountryModule();
}

The code is self explanatory. We are just wrapping the actual Angular application inside CoutryModule class. Lets see how services can register to the ng application.

CountryMetadataService.ts

module CountryApplication {
    export class CountryMetaDataService {
        employees: Array<Country> = new Array<Country>(
            { id: 1, DisplayName: "India", Currency: "Indian Rupee", CurrencySymbol: "R" },
            { id: 2, DisplayName: "United States", Currency: "Dollar", CurrencySymbol: "$" }
        );
        GetAll(): Array<Country> {
            return this.employees;
        }
    }
    // Registering with angular app name in every file is difficult to maintain.
    // angular.module('CountryApp').service("CountryMetaDataService", CountryMetaDataService);
    CountryModule.getInstance().registerService("CountryMetaDataService", CountryMetaDataService);
}

An end to end template can be found in Github.com. This will get more scenarios on how to use TypeScript in AngularJS applications in TypeScript way.

Welcome to enterprise web app development.