Posts

Showing posts from 2018

windows - upgrading nodejs

Ok, not really sure why or how i missed this but the best way to upgrade nodejs without using an installer on windows is to :

Just run the code below :-

Set-ExecutionPolicyUnrestricted-ScopeCurrentUser-Force npm install -g npm-windows-upgrade npm-windows-upgrade

mssql restore using tsql

To restore your Mssql BAK database, you need to use the restore command and often you need to move your mdf / ldf files to folders. How do you find out what's the mdf/ldf files in a .Bak file?






BrowserModule in angular

If you wonder what is the use of BrowserModule, well it is export of CommonModule ( which consist of angular directory, ngIf, pipe, ngFor) and ApplicationModule (root injector for bootstraping application)

angular - breaking application into smaller modules

The following codes shows example how we can make use of angular module and break it down into submodules.
This is the router 



Sample customer moduile. 

Sample item module 















Dockerfile CMD - There can only be one.

Regardless of current or previously configure docker image, CMD can only be executed once.

For example, let's say you use image PARENT_IMAGE_DOCKER and it uses a CMD to build this image. If you build on top of PARENT_IMAGE_DOCKER  and call it CHILD_IMAGE_DOCKER, you are still stuck with running / configuring a single CMD.

Image builder needs to be careful. The work around for this is to use a script (mountdb.script) which gets called and the runs whatever scripts that PARENT_IMAGE_DOCKER requires.

You can see some samples here (Notice on line 36, I called .\start.ps1 - which is what the image used to run.



powershell to download file from sftp site

Here is a sample powershell script to download files from a sftp site using WinScp's dll.





docker - creating an image that restore database from .bak files.

Microsoft host a mssql docker image that use 'attach' method to mount database - this assume you have .mdf / ldf files available.

To deal with .bak files, it can be tricky. Hence i have created the following docker image and powershell scripts.

The docker file.



This is not possible without "mountdb.ps1".  This scripts generate and runs restore command




This scripts runs "Invoke-SqlCmd" to execute scripts and doesn't really required login.

It then runs, start.ps1 which change sa's password base on your environment settings.


Git repo can be found here.


angular 6 - working with key material schematics

Image
Angular 6 comes with a feature called schematics for creating material applications easier. First you need to install angular material using the following commands :-

ng add @angular/material We assume that you have installed the latest angular cli tools, if not please install it using the following instructions



Some common schematics uses are :-
ng generate @angular/material:materialNav --name=main-nav

ng generate @angular/material:materialtable --name=main-nav

ng generate @angular/material:material-dashboard --name mydashboard



Let'st take dashboard as an example. After executing it, the following files will be added for you.





Update your app.component.html with the following codes (app-mydashboard is the selector defined in app-mydashboard.ts component.


<li> <h2><atarget="_blank"rel="noopener"href="https://angular.io/tutorial">Tour of Heroes</a></h2> </li> <li> <h2><atarget="_blank"rel="no…

Angular 6 - upgrading the the latest cli tools

You can upgrade to the latest cli tools using the following command :-  npm install @angular/cli@latest -g

To upgrade existing project, just run the following commands  ng update @angular/cli


@() mean in Powershell

@ in powershell means array and @() means create an empty array.


mssql docker windows container

Image
The best way to setup docker for mssql server (developer edition) is using the following image and it can be as simple as this. Please note that this image supports database mounting (it comes for free).

FROM microsoft/mssql-server-windows-developer
ENV SA_PASSWORD=Password1! ENV ACCEPT_EULA=Y
To build it.


docker build -t mssql:v1 .

To mount database with your local directory, just run the following command :-

docker run -d  -p 1400:1433 -v C:/mssqldata/:C:/mssqldata/ -e attach_dbs="[{'dbName': 'PTS','dbFiles': ['C:\\mssqldata\\pts.mdf','C:\\mssqldata\\pts_log.ldf']}]" mssql:v1

Noticed i am mounting my local folder called c:\mssqldata and specify environment settings called attach_dbs and it is in json format.

After running it, fire up your, connect to your localhost 127.0.0.1,1400 port and you will see your mounted database.





If you have multiple database, it can be in this format :-



[ {      'dbName': 'PTS',      '…

c# expression body for working with multiple item.

Many times you need to work with constructor assignment of multiple value for body expression
The following code show how we can do it.

publicclassPerson{publicstringName{ get;}publicintAge{ get;}public

redux saga - proper return from fetch

Let's say you have the following saga code to call and put a http request.

exportfunction*fetchUser(action) { try { constusers = yieldcall(getUsers); yieldput({type:USER_FETCH_SUCCEEDED, users:users }); } catch (e) { yieldput({type:USER_FETCH_ERROR, message:e.message}); } }

Here we call getUser which needs to be correctly handle, otherwise you get alots of weird handling issue downstream.

For example, you might return a promise like so,


functiongetUsers() {

returnfetch(FETCH_USER_URL); }



Or even as follows :-


functiongetUsers() {
returnfetch(FETCH_USER_URL).then(response=>response.json()) }



The proper way is to do as follows Why? Because this will return an array of plain objects instead of Promise(). which you cannot call more than once. Why do you call this more than once? In react lifecycle, your function will get call more than once.




functiongetUsers() {
returnfetch(FETCH_USER_URL).then(response=>response.json())
.then(json=>json);
}


c# when action is not void

Imagine that we're passing have a method that accept Action as a parameter.


publicvoidInvoke(Action action){ /*Code Here */} And if we pass something like this 

publicvoidInvoke(Action action){/*Code Here */}

docker run weirdness

For some reason we need to have the port parameter up first like so,

docker run -p 8000:27017 mongodb-xdb


I tried  running it

docker run mongodb-xdb -p 8000:27017


And I get some error. So weird.

Difference between set vs setx

The difference between SET and SETX are

SETX - setting the environment variable is made permanent

SET - setting the environment variable temporarily.

Activation function -

Image
Here are some activation function that i found and think it is pretty useful.




To understand better, lets take a look at this classification problem from tensorflow :-
model = keras.Sequential([     keras.layers.Flatten(input_shape=(28,28)),     keras.layers.Dense(128, activation=tf.nn.relu),     keras.layers.Dense(10, activation=tf.nn.softmax)]) We're building a sequential model, CNN.

a) Flatten -> will convert 28 x 28 to a 784 pixel.

b) Dense - relu activation function - which is a fully connected 128 layers.

c) Softmax - configure to return probability of 10 different possibility. 10 possible outcome with highest probability.

Something like this :-

array([1.0268966e-05, 4.5652584e-07, 2.2796411e-07, 2.6025206e-09, 4.2522177e-07, 4.1701975e-03, 1.1740666e-05, 2.8226489e-02, 4.3704877e-06, 9.6757573e-01], dtype=float32)
Normally you will take the high value to get probability of matches.




Common import mistake with typescript vs javascript

I really need to get this right, once and for all. Seems to be making simple mistakes when it comes to typescripts import vs javascript import.


For example,

The javascript way
import=rendererfrom'react-test-renderer'; The typescript way, 
import*asrendererfrom'react-test-renderer';

jester js for typescript testing

If you are writing your code in typescript and decided to use jesterjs then this is the right blog to read. Jesterjs works well with .js files. If you're using typescript, you need to ts-jest.

To setup,


npm install --save-dev jest typescript ts-jest react-test-renderer

Then you need to configure file presets :-

npx ts-jest config:init Then you can follow sample code as given by Jesterjs here, https://jestjs.io/docs/en/tutorial-react

Hope this helps to add test to your project, faster



Uncaught TypeError: Cannot read property 'tagName' of null

If you encounter this error, this means that you have use to wrong file name for your purpose. Try changing ts to tsx.

This will help.


react native login screen and redirect to a main navigation - bottom tab

Normally, you would create all the necessary screen under a main navigation. That's fine until you introduce your 'Login' screen. The only problem with that is, your user would be able to switch to other screen via bottom tab (for example)


Introducing createSwitchNavigator   which allows us to create individual section of our screen.


An example code would looks something like this

importReactfrom'react'; import { createSwitchNavigator, createStackNavigator } from'react-navigation';
importMainTabNavigatorfrom'./MainTabNavigator'; importLoginScreenfrom'../screens/LoginScreen';
exportdefaultcreateSwitchNavigator({ // You could add another route here for authentication. // Read more at https://reactnavigation.org/docs/en/auth-flow.html Main:MainTabNavigator, Login :LoginScreen }, { initialRouteName:'Login', });

This allow us to show Login screen as a separate screen and independent from other screen.

Please consult reference here for more infor…

splitting saga into multiple files..

What a efficient multiple saga would look like ..... (this is copy from here)


// foo.jsexportconstfooSagas= [ takeEvery("FOO_A", fooASaga), takeEvery("FOO_B", fooBSaga), ] // bar.jsexportconstbarSagas= [ takeEvery("BAR_A", barASaga), takeEvery("BAR_B", barBSaga), ]; // index.jsimport { fooSagas } from'./foo'; import { barSagas } from'./bar'; exportdefaultfunction*rootSaga() { yieldall([ ...fooSagas, ...barSagas ]) }

Getting value from resolved promise in redux saga

Image
Redux saga normally return promised from fetch api and sometimes you need to resolve those promises to pass it as data to other components.

Given that you have the following item,




To work with actual data, you can try to use the following code :-



Promise.resolve(state.sysadmin).then(function(value) { console.log('promising promising ', value); });

debugging nodejs application

Image
Run your nodejs application using

"node --inspect server.js" (for example), you just need the --inspect switch.


Next, goto Chrome and click on DevTools for Nodejs. (the green button below) and then you're good to go.


Switch over to "source" tab and then set your breakpoint accordingly.



Returning HttpResponse Message the right way

Working with HttpResponseMessage can be tricky. How do you return HttpResponseMessage as string or HttpResponseMessage as Json message.


returnnewHttpResponseMessage(HttpStatusCode.OK ){Content=newStringContent("Your message here")};
As for Json message