Showing posts from 2018

typescript 2.8 - Conditional Type

Conditional Type

Which basically trying to say if  type A kinda like B type, then we can just use C type.

interface Car {
drive():void; } interfaceFerarriextendsCar { drivefaster():void; } // Foo becomes numbertypeFoo=Ferarri extendsCar ? number : string;

Learning flutter quick and dirty guide

I find it easier to go through :-

1. Widget catalog - to check out what are the widget available in flutter. Basically their capabilities.

2. Cook book - All the code you need to quickly spin out a UI element. Pretty limited but you get an idea.

3. Code labs - is so much better compare to "Writing your first app" write up.

Hope this helps.

flutter : no connected devices available / configure.

Please make sure you have clone flutter sdk from here

and run

flutter doctor --android-licenses

Check to ensure you have install the following :-

Android SDK, Android SDK Platform-Tools, and Android SDK Build-Tools, Images are installed

Then from the toolbar make sure you set to a "device", in my case Nexus 6 API P emulator. This will fire it up and once it is up and running, click on the play button.

It is a bit weird but .......that's how it works. 

Flutter package repository

Flutter package repository can be found here.

Flutter : unable to locate development device

Face this issue trying to run Flutter using Android studio. This simple means you need to configure your platform tools.  Go to File->Project Structure->Configure your Platform Sdk as shown below :- Try to set to Android 27 (or as recent version of Android SDK as you could).

Then fire away. Once you have it configure, your application bar - Flutter Hot Reload -> Should be enabled.

That's a big

EF Core 2.0.1 - Entity framework migration specific update - minus out initial database update

Wow, this title is pretty long.

Let's say you already have an existing database and right now you wanted to use EF Core to help migrate specific DML updates to your target database - which could be creating a new View or creating additional table minus out the initial database structure.

Note : Sometimes when you do an upgrade, you might get error message saying "your database has already been updated".

All rite, to be honest, you ca't do specific migration, example you can say "apply ABC Migration".

It is all based on the migration class that you've setup in your project,  meaning you get to type "Update-Database" without any parameter.

Anyways, please setup your project and all in the required EF nugets.

Next create the following class.

Then you specific what needs to be done. In this case, we are creating a view called "AppTesrtView".

Goto "package manager console" and then run "Update-Database". Please note y…

EF core hosting database migration on a separate project.

Project is available on Github.

Create a NEW project and then ensure you have installed all the nuget packages. The next important task that you need to do is to add a reference to your DbContext entities, if you have it separately from the main project

In your Startup.cs please ensure you have the following codes (which links directly to "Alphacert.Acc.Ods.Entities.Migrations".

services.AddDbContextPool(o => o.UseSqlServer(connectionString, x => x.MigrationsAssembly("Alphacert.Acc.Ods.Entities.Migrations")))

Using MsgPack in your core webapi

MsgPack (here) is reportedly faster then msgpack-cli in terms of performance. To get your excited, check out the diagram below :-

Yes, it is ridiculously fast and beat protobuf in many ways. I was gonna put on my hardworking cap and write up some formatters but this way is easier to do :-

Client code 

Client side code to de-serialized it.


Install it through nuget using the following command :-

Install-Package WebApiContrib.Core.Formatter.MessagePack -Version 2.0.0

Next, you gotta decorate your objects with the correct attributes.

And then somewhere in your controller, you can serialize your object as bytes and push it through using code below :-

Anaconda3 - Getting the environment installation of your library packages

How do you get the path where all your "pip install" packages are stored?

Fire up your python shell and run the following command :-

import os; print(os.path.dirname(os.__file__) + '/site-packages')

For me, i get the following output :-


Where CNTK is my current active environment and all the goodies that comes with it.

EF core using views

To access database view using DbContext, you just need to :

1. POCO - Create your POCO using code shown below. Please note that you need to match exactly the POCO to your views but not necessary all the fields. Let's say you have 10 fields but you can just defined 3 that is of interest to you :

2. Add your DbSet - You need to open up your DBContext and add in your DbSet Manually.

  public virtual DbSet VwValuations { get; set; }

3.OnModelCreating - in your DbContext, add your valuations data as shown below :

The data type used depends on your view.

That should be all the changes you need to make.

Cannot access a disposed object in ASP.NET Core working with DbContext

Bump into this error and found out the reason you cannot spin up a task to run a injected DbContext which normally injected by WebAPI dependency injection of a DbContext.


Create your dbcontext manually using code below (instead of using DbContext passed in the controller)

WebAPI support for File based Partial Content 206

Image core support for partial content is far out easier than i imagine. For example, if your application delivering a huge file, 100 Megabytes for example. then you might want to request these data as chunks

Some notes : this only works for File result and not with JSON which might fetch some data from the table. For example, you have a huge json (about 2M) and defining range 30-1000 will not change returned data.

Sample controller to handle partial content :- Yeap this is all you need.

Next, fire up your post and and you can see some of the results that i'm getting. Oh before anything else, please ensure you place a large txt file a folder.

As you can see from Postman. i create a request with Range : 30 - 1000 and the response is shown here too.

A couple of things to notice :-

Return result is 206. (Http Partial Content) 

Content-Length is 2500 ( which is the total file size we have) 

EF Net Core does not support nvarchar

I got this problem earlier today and i could swore it only happens for .net core 2.0. The message looks something like this :-

Data type 'nvarchar' is not supported in this form" after scaffolding from database 

After my model is binded or built, it throws this exception. I change

entity.Property(e => e.Comments).HasColumnName("Comments").HasColumnType("nvarchar");// No size specifier to


What is CNTK dynamic axis?

CNTK has static and dynamic axis. Static axis remains the same throughout the whole life cycle of the model. Dynamic axis has the following characteristics :-

a) varies from instance to instance
b) typically unknown
c) maybe ordered.

Sounds like a minibatch

Taken directly from Microsoft website :-

To make this more concrete, let’s consider two examples. First, let’s see how a minibatch of short video clips is represented in CNTK. Suppose that the video clips are all 640x480 in resolution and they are shot in color which is typically encoded with three channels. This means that our minibatch has three static axes of length 640, 480, and 3 respectively. It also has two dynamic axes: the length of the video and the minibatch axis. So a minibatch of 16 videos each of which is 240 frames long would be represented as a 16 x 240 x 3 x 640 x 480 tensor.

Dynamic axis in this case are video length (240 frames) and a total of 16 videos.

kubernetes dashbboard

Kubernetes dashboard is a UI driven approach to view and get us working with Kubernetes fasters.

Accessing the dashboard run :-

kubectl proxy

And you might get : Starting to serve on

So browse to : localhost:8001/ui

The nice dashboard of Kubernetes appears.

That's it.

kubernetes working with deployments : quick and easy

Do your deployment 

kubectl run connectcd --image=kepung/dotnetapp-prod --port=5050

Check your deployment is deployed 

kubectl get deployments

Get the pods spin up by your deployments and look for the labels :-

kubectl describe deployment/connectcd

kubectl get pods -l run=connectcd

NAME                         READY     STATUS    RESTARTS   AGE
connectcd-545c87f8d8-j4fsv   1/1       Running   0          27s

connectcd-545c87f8d8-j4fsv is our pods

Get all the pods in all namespace

kubectl get pods --all-namespaces

elastic search docker image that works

It has been challenging to find the images that works for ELK stack. Finally settle with the following images from elastic co version 6.2.2

Elastic Search

run the following image to get elastic search

docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node"

Then browse to the following site :-



Kubernetes 101 - Basic stuff

When working with Kubernetes there are a few stuff that we need to be aware of,

1. images are often download from registry that lies somewhere in the cloud

2. kubernetes are organized into namespace. "default" namespace is the default. If you type kubectl get pods, you will get pods listed under this namespace by default.

webapi versioning the easy way

Turn out that doing webapi service versioning is relatively easy in core. First off, please install the following nuget package :-

Install-Package Microsoft.AspNetCore.Mvc.Versioning -Version 2.0.0

Next up, is to organize your controllers into folders. I prefer to use folder (namespace) as a way to do it, so i can have the same controller name versioned differently, as shown below :-

--->V1-->Controller-->HelloController(version 1)

-->V2 -->Controller-->HelloController (version 2)

Next we just need to decorate our HelloController with the proper attribute.

Version 1 Controller.

Version 2 Controller

webapi logging - log level

Just to clarify, if you set log level to Debug ( LogLevel = 1) then your logging will shows any log above it.

Here is the definition for log level,

 Trace = 0,
 Debug = 1,
 Information = 2,
 Warning = 3,
 Error = 4,
 Critical = 5,
 None = 6

Given we define LogLevel = Debug, any logs value bigger than 1 will appear.
If you want to scale down details of your logging, try setting your log level higher to Warning, for example.

You might want to change your logging method call too.

CNTK - Simple linear regression

The following are sample code to create a linear regression to work with car data.

CNTK : Different mini-batch size detected

Size of your test data and train data differs. Try making it the same before running your code again.

angular2 - working with reactiveform with json data

I guess one of the best way to debug angular reactive form issue is with the following code. Gives an interactive view of what user is adding into the form.

<pstyle="width:800px">Form value: {{ personForm.value | json }}</p>

Number to words typescript implementations

Here is a modified copy of a code that converts number to words.

Issue with : Unable to start Kestrel. System.AggregateException: One or more errors occurred. (Unable to load DLL 'libuv': The specified module or one of its dependencies could not be found.

When i was building my project for a docker container i bump into this problem

"Unable to start Kestrel. System.AggregateException: One or more errors occurred. (Unable to load DLL 'libuv': The specified module or one of its dependencies could not be found."

I just use install the nuget package and it works

Install-Package Libuv -Version 1.10.0

Testing angular component - having a hard look at it

A typical unit test for Angular looks like this :-

We need to understand

a) A component or fixture represent our angular component which might include a single or more markups.

b) DebugElement are basically specific html markup like span or div that we would like to find after it is our component rendered.

So, in our test it is important to know what we've already initialized our component using code below :-

Next we get an instance of our component and check if it contains certain markups as shown below :-

Cannot find module '@angular-devkit/core'

Oh my, surprising enuff, I had this happened to me, write. Unable to find module @angular-devkit/core.

npm install @angular-devkit/core --save-dev
Facebook Bot


What we are doing here is to serve up an nodejs app which handles messages that users or customer post to facebook. This gives us an opportunity to add various service like Luis or Wit.Ai to handle NLP. Surprising Wit.Ai is very similiar to Luis.

Getting started with sample code 

Downloading sample app with Facebook messenger test drive.

Follow the instruction here.

Running it 

Running using 2 different processes.

Process #1.

Kicks it off using "node app.js" - default port is 5000 but you can always  change it.

Process #2 (tunneling to Facebook)
Runs the following command -  lt --port 5060


Open your messenger and start sending messages to it. You can see your local (command prompt) node app displaying text messages from the user.

FluentD Logging with .Net Core

You can install the NLog plugin to logging to a Fluentd node.  Fluentd is a unified logging layer and if you're wondering if we're talking about the same logger, check it out here. There is a difference between fluentd and fluentbit. Fluentd is targeted for servers with larger processing capacity while fluentbt is for IOT devices with small memory footprint.

Getting your project ready with the following nuget

Install-Package NLog.Targets.Fluentd -Version 1.0.4

Install-Package NLog -Version 2.1.0

Install-Package System.Configuration.ConfigurationManager -Version 4.4.1

Setting up Fluentd Docker

This is the docker command to setup Fluentd as an endpoint to gather all your log.

docker run -d -p 24224:24224 -p 24224:24224/udp -v /data:/fluentd/log fluent/fluentd

This will start your docker container with fluentd.

Then we will use the following code to write to docker container :-

You can see your log as shown below when you connect to your docker container.

Swagger UI - Getting better documentation and playing around with your REST service

We so used to building REST or micro service. Now it makes sense to build better REST based services.

Better documentation with Swashbuckle.AspNetCore

It is always good to have SwaggerUI in your system as it gives you auto-generated, nicely layout way of documenting and interacting with your REST service.

Install-Package Swashbuckle.AspNetCore

Next, configure your startup.cs

Remember to browse to your swagger UI by :- http://localhost:5050/swagger/

CNTK : Working with MNIST dataset using logistic regression

Here is the code to download MNIST dataset.

Just run python

Next you would like to try out logistic regression with this dataset.

Kubernetes - deploying to a cluster (real cluster)

Surprisingly deploying to a cluster is pretty straight forward.

To run or deploy your application to cluster, issue the following command :-

kubectl run --kubeconfig connect_config.txt connectcd --image=kepung/dotnetapp-prod --port=5050

The only different is --kubeconfig - which is a file storing your cluster info including access.

Next, to ensure, we expose our port with a service, using command below :-

kubectl --kubeconfig connect_config.txt expose deployment/connectcd --type="LoadBalancer" --port=5050 --name=connectcd-http

That's pretty much it.

To get the service url for your pod, you can use the following command :-

kubectl --kubeconfig connect_config.txt get service connectcd-http -o yaml

You will see the following output and it contains the DNS of the newly deployed service. Please wait for a few seconds for AWS DNS to have it registered in there.

Working with Microsoft bot adaptive card

When working with Microsoft Bot, you there are a few gotchas when working with adaptive cards.

Nuget package

You need to install "Microsoft.AdaptiveCards" nuget package


If you have data in a property called  "DataJson", it needs to be in Json format, otherwise your layout will not be rendered.

Formally written C# new features

CNTK - working with linear regression

The code sample below gives

creating fast forward network using CNTK

Here is a good example of how you can create and evolve your simple fast forward network for a simple classification problem

sigmoid vs softmax

If outcome is in a binary form, e.g true or false, or 1 or 0 then use sigmoid

Otherwise use softmax where outcome can be more than 2 possible states.

CNTK - A ML framework from Microsoft for large scale processing

CNTK is suppose to be a large scale corporate development of ML. You can call it via C#.
Similar to tensorflow, it is designed as a graph based ML development framework.

A couple of interesting things i find out

Installation CNTK 

To install CNTK on Windows. If you're installing for different platform, you can refer to documentation here.

pip install

Get started 

The best place to get started is following instruction here.

Using CNTK with C#

Yeap, you can use CNTK with C#.

Light RNN


Docker image 

You can find the docker image here.

docker pull microsoft/cntk

Microsoft REST guidelines

Microsoft's guidelines for building REST based services can be found here.

primeng datatable refresh

When you change individual rows in primeng datatable, datatable will not be refreshed automatically,  for example

this.rows[i]['gender'] = 'Female' In order to refresh table, you need to do a manual, shallow copy using code below :-

this.rows[i]['gender'] = 'Female'this.rows = [...this.rows]; // refresh manually here ..

Getting javascript object property and values

Here are some common functions to discover properties and values of an object using properties.

a) Object.keys - Get all the keys of an object

b) Object.values

c) Object.getOwnPropertyDescriptors

The following code snippet demonstrate how to work with these methods.

angular data bindings - further look

There are 3 different types of bindings in Angular

a) Source to View bindings

The following syntax are valid 




b) View to source binginds

The following syntax are valid 



c) Two way bindings

The following syntax are valid 



Pushing docker image to ECS (Elastic Container Service)

In order to push to Amazon's ECS registry you need to setup and configure your account.

First of all you need to setup aws and docker.

Goto AWS console to create a repository and follow the instructions. If you needed a sample project, please clone one here.

To summarize, the steps, do the following. (i assume you created a repository called "jeremy".

Get a docker login command (setup your credential) by running the following command :-

aws ecr get-login --no-include-email --region ap-southeast-2
Then build your image

docker build -t dotnetapp-prod .

docker tag dotnetapp-prod

And push your image to Amazon

docker push

To browse your ECS repository, please go here.

Possible error message :-

Can't push image to Amazon ECR - fails with “no basic auth credentials” - This means you didn't setup your aws credential - please set or …

kubernetes pods keeps restarting

I had this situation whereby kubernetes pods keep on restarting even if I tried deleting it.
As soon as it gets deleted, two new instance get created again.

So i tried looking for what causes it. For my case, it is the replicationcontroller.

kubectl get replicationcontroller

kubectl delete replicationcontroller "connectcd"

And this solves it! :)

Setting up your simple .net core application using kubernetes

This is a simple guide how to deploy .net core docker image to kubernetes (minikube).
You need to setup your minikube, docker. Once you have done that, we're ready to go.

Summary of tasks :-

a) setup Docker image

b) push to Docker registry

c) run your application on Kubernetes and scale it

1. Setup Docker image

Our .netcore service exposes /hello/index url which returns "Hello World!".

The complete source code is available here. Once you have clone the git repo, we just need to build our docker image. This is a multistage docker image which means it uses .netcore sdk for building and then deploy built binaries to a .netcore production image.

Go to ConnectCD-NetCoreWebApi, then run the following command :-

docker build -t dotnetapp-prod .

If you want to test your application locally (using DOCKER),

docker run -d -p 5050:5050 dotnetapp-prod

2. Push to Docker registry

Use the following command to push your built image to Docker registry (kepung) is my user id. You should chan…

Pushing your own image to docker registry (over the cloud)

I am doing this because well, i needed to use kubernetes to run my docker image. It's a harder to setup a local docker image, so this is easier.

First you need to create a free user account in docker.

Login to docker and provide your username and password

docker login
Next tag your image (kepung/my_image) where kepung is the name of my user.

docker tag my_image kepung/my_image
Push it

$ docker push kepung/my_image
To see your docker images on the web, go to

All rite, some FAQ.

If you rebuild your docker image and tag it say "hello-world", existing image gets overwritten

If you push the image with the same tag name, your image on the web, gets over-written too.

Pretty straight forward.

An assembly specified in the application dependencies manifest was not found:

This error comes up when you try to run a .net core application without specifying target build environment output. You need to specify the "-r linux-x64" parameter and that will generate a list of all the assemblies required to run the dotnet core app in target environment.

RUN dotnet publish -c Release -r linux-x64 -o out

Dockerfile - build and deploy your .net using the right image

I just love this docker approach which use sdk image to build and then deploy to a prod in a single file, which looks like code below :-

There are more to it to Dockerfile COPY command than meets the eye.

Http REST request, usage and their payload

Here we would like to figure out how to work with different HTTP request methods -

A complete list of methods available are :-

a) HEAD - same as GET, except it does not accept payload

b) GET - access a resource

c) POST - submit data with the intention of modifying a resource or adding to a resource

d) PUT - modify a resource

e) DELETE - remove a resource

f) TRACE - Echo back the received resource forms server.

g) OPTIONS - Returns what the HTTP server supports. For health check for instance to check if a server is online, I think this would be the method to use. Not because it is light or doesn't have a payload but it makes sense. P.S. There is no semantic usage at the moment from HTTP governing body.

h) CONNECT - Convert request connection to a transparent TCP/IP tunnel. Not supported

i) PATCH - partial response to a resources request.

CONNECT and TRACE are the only options not supported by .Net core.

Angular5 - specifying css or javascript asset for bundling to deployed offline

Say you have a bunch of css and javascript files which you need to deploy as offline asset. Meaning the target server does not have access to internet. What do you do?

You can change your ".angular-cli.json" file and under the section "styles", update path to your assets in src folder. Yeap, it starts looking in your src folder and you can tell I have a folder called "assets".

"index": "index.html", "main": "main.ts", "polyfills": "polyfills.ts", "test": "test.ts", "tsconfig": "", "testTsconfig": "tsconfig.spec.json", "prefix": "app", "styles": [ "styles.css", "assets/bootstrap.css" ], "scripts": ["assets/jquery-3.2.1.slim.min.js", "assets/popper.min.js", "assets/bootstrap.min.js"], "environmentSource": "environments/envi…

typescript rest and spread

Rest properties supported by Typescript are shown below :-

Spread example

Shallow Copy object

sqlserver connection timeout is NOT query timeout

I hit a problem of query timeout. This is a freaking old problem but just that we need to understand differences between connect timeout and query time out. If you don't you find yourself setting a connection string and getting exception over and over again.

The main different is message your get as shown here :-

Connection time out and its exception message.

System.Data.SqlClient.SqlException: Connection Timeout Expired. The timeout period elapsed while … To solve this you can change the connection string which is pretty straight forward; 
'Connection timeout=3600'

Query timeout and its exception message
System.Data.SqlClient.SqlException: Timeout expired. The timeout period elapsed prior …
With this, you can use Command.Timeout or if it is a SQL statement execute statement, you can pass in the connection timeout value.

angular5 - deploy your app to production

The easier way is to do this

ng build --prod
Copy everything from your folder called 'dist' over.
If your target host machine are not able to access CDNs for javascript or css, you can copy and save into a style.css and run this command, which essentially will generate javascripts and css files.