Posts

Showing posts from 2018

Getting started with Angular universal

There are many blogs that offers tutorial on angular universal. However, most of it has some issues. You can clone entire sample from here. Build and run instruction are given as well.

To get it working from scratch, my app is called webapp


ng new webapp --routing

cd webapp

ng g universal --client-project webapp

# New Render Engine
npm install @nguniversal/express-engine

# If using lazy loading
npm install @nguniversal/module-map-ngfactory-loader

npm install --save-dev express webpack ts-loader
# If using Firebase
npm install --save-dev ws xmlhttprequest


src/app/app.module.ts


import { BrowserModule, BrowserTransferStateModule } from'@angular/platform-browser'; import { NgModule } from'@angular/core';
import { AppRoutingModule } from'./app-routing.module'; import { AppComponent } from'./app.component';
@NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule.withServerTransition({ appId:'serverApp' }), AppRoutingModule, BrowserTransferStateModule ]…

angular universal - TSC cannot find name of Global Object

Typescript was complaint about this issue, and manage to resolve this by editing tsconfig.app.json with the following content :


"compilerOptions": { "outDir": "../out-tsc/app", "types": ["node"] },

microsoft extension configuration gotchas

Image
Important nuget packages


In case you're using Microsoft.Extensions.Configuration and unable to call methods like "AddJsonFile" or AddCommandLine, then you might be missing some nuget packages.













Once you added your nuget package, you can access those methods.


Getting results back (wait for all results) after firing async task

I think this is a very common scenario where a method would fire off several async tasks and then waits for result to result somewhere down the line.

var task1 =DoWorkAsync();var task2 =DoMoreWorkAsync();//then somewhere down the line await Task.WhenAll(task1, task2);

Exam 40-475 Content

Batch processing and design
Ingest data for batch and interactive processingIngest from cloud-born or on-premises data, store data in Microsoft Azure Data Lake, store data in Azure BLOB Storage, perform a one-time bulk data transfer, perform routine small writes on a continuous basisDesign and provision compute clustersSelect compute cluster type, estimate cluster size based on workloadDesign for data securityProtect personally identifiable information (PII) data in Azure, encrypt and mask data, implement role-based security, implement row-based securityDesign for batch processing


Real time processing and design 


Ingest data for real-time processingSelect data ingestion technology, design partitioning scheme, design row key of event tables in HBaseDesign and provision compute resourcesSelect streaming technology in Azure, select real-time event processing technology, select real-time event storage technology, select streaming units, configure cluster size, select the right technology for…

Some basic Android work

Android walking through the following content :-

Testing and debuggingWrite and execute local JVM unit testsWrite and execute Android UI testsUse the system log to output debug informationDebug and fix issues with an app's functional behavior and usability User interface (UI) and app functionalityCreate an Activity that displays a layoutConstruct a UI with ConstraintLayoutCreate a custom view class and add it to a layoutAdd accessibility hooks to a custom viewApply content descriptions to views for accessibilityImplement a custom app themeDisplay items in a RecyclerViewBind local data to a RecyclerView list using the paging libraryImplement menu-based or drawer navigationLocalize the appDisplay notifications, toasts, and snackbar messagesSchedule a background task using JobSchedulerEfficiently run jobs in the background App data and filesDefine data using Room entitiesAccess Room database with data access object (DAO)Observe and respond to changing data using LiveDataUse a Reposi…

.netcore figuring out if a assembly is supported.

Just go to this site and start typing out your assembly.
It will show you if, that assembly still support / exist in dotnet core, dotnet framework.
You should really look for "Dotnet core label" - it is pretty explicit. If you don't see it, that means. it is not supported.

https://apisof.net/

modern angular development

This are some quick tutorial and code samples about Angular

Basics

User input button click (stackblitz example)

Displaying user properties (stackblitz example)

Creating  component that uses @Input as input property.

Ngfor

NgIf

Server side rendering

Service worker


Working with viewchild for native componet

Working with viewchild for regular angular component / directive

Working with viewchildren

Working with contentChild - pretty much the same with viewchild.

Bootstrapping

Angular platform -

Understanding platfom

Angular directive with regular html element - stackblitz example

Angular directive complex example - html element and component. stackblitz example.


Advance custom directive

lazy loading of module

Infinite scrolling

Understanding route

Angular schematics

Localisation


Cli command 
-


Unit test 

Using jester to do Angular unit test

add

build

config

e2e

generate

lint

new


Renderer / Renderer2 

If you understand why we have platform (server-platform, browser-platform) then you will un…

typescript - intersection type

If you want to defined your type which contains intersection of properties but nothing else then you can use & operator.

In this example we define, CrazyMix which must defined bread, crust, size properties.
If we introduce another property, then we will get an error.



interfaceIPizza { crust : string, size : number }
interfaceISandwich { bread : string size : number }
typeMixFood = IPizza & ISandwich
constCrazyMix : MixFood = { bread :'i want ', crust :'test', size :100 }

constCrazyMix : MixFood = { bread :'i want ', crust :'test', size :100 rating : 10 // ERROR }










typescript discriminated union type

Discriminated union - what this means is you get to say i want certain properties if my type is defined in a certain way.

// discriminated union
interfaceIPizza { foodtype : 'pizza' crust : string }
interfaceISandwich { foodtype : 'sandwich' bread : string }
typeFood = IPizza | ISandwich

constmyfood : Food = { foodtype :'pizza', crust :'thin' }
constsandwich : Food = { foodtype :'sandwich', bread :'wholemeal' }


If i tried to define foodtype that is of 'pizza' to contain 'bread' property, i will get an error



constmyfood : Food = { foodtype :'pizza', bread :'thin' // error }

introducing strong typing over window document or other browser apis

This is just a demo but it shows how to introduce strong typing over browser api like document or even service worker api.

Anyways, lets use document as our example : In this example, we trying to create a simple TestBrowser class which uses interface BrowserDoc (for windows document type). 

In the BrowserDoc interface we can define all the browser interface like alert, queryElement, in this case, it is just write.

Then we initialize our TestBrowser and slot in our window.document.



classTestBrowser{
constructor(document :BrowerDoc){ document.write('test'); } }
interfaceBrowerDoc{ write(s :string):void; }
var a =newTestBrowser(window.document);

gatsbyjs serving up assets

Assets like javascript or css files are served up from static directory. You do not have to specify it.

For example,  if you place your javascript file in "static/js/worker.js", then you only need to specify it as '/js/worker.js' in your react components.

----static
   ----js
     --- worker.js

Well it can takes a couple of minutes to figure this out.





Gatsby : Cannot find module 'uglifyjs-webpack-plugin'

Bump into this issue the other day, gatsbyjs gatsby-plugin-netlify-cms requires this component which are not necessarily installed by default.

You might have to do it manually.Just run

npm install --save gatsby-plugin-netlify-cms


That should solves it.

Node.js: what is ENOSPC error and how to solve?

Ran into this issue trying to run gatsbyjs on ubuntu. and you guess it, it is a nodejs problem. To resolve this

echo fs.inotify.max_user_watches=524288| sudo tee -a /etc/sysctl.conf && sudo sysctl -p

and then


sysctl --system

gatsbyjs adding offline support to your site

To help making your site more resilient to network connectivity issue, gatsby js provides an awesome plugin that cache pix and js of your site.


It is really simple. Just two steps.

npm install --save gatsby-plugin-offline


Add this to your gatsby-config.js

plugins:[`gatsby-plugin-offline`]


Restart your app and browse to a page. You will be able to see that we can still hit our site.



gatsby js footer

In Gatsbyjs, layout are shared across pages. I was trying to find where is the footer. After some hard look, i was able to locate where it is.... src\layout -> which then use a component called Navigation and then footer. Phew !


C# - Trying not to repeat initializing child external dependencies with parents

Let's say you have a parent which uses dependencies like so,




And you also noticed we have an interface called 'IDropEndpoint'. Let's say this dependencies also uses whatever the parent uses, in this case ISession and IEndpoint.


It is common to use DI, to bind all these together. But instead of doing this, would it be easier to have a method that accepts ISession and IEndpoint instead?




No complexity and code repeat.






Window Docker container network not working

Image
For some reason, when i run my container, i can't connect to the network. After looking at my network configuration using "ipconfig", notice the configuration is completely out. 

So what i did was, enable this guy down here and that's all it takes. 



graphql debugging query snippet

Think this is a great way to see if there's data coming back from a client side query component.

It could look like this. I copied from Apollo site. :)

client .query({ query: gql` { rates(currency: "USD") { currency } } `}).then(result => console.log(result));

Angular Inline component css

Image
Angular does provide support for inline css, probably not 100% as provided by specialized library like emotionjs or styled-components.

But essentially Angular does it throught ViewEncapsulation.  4 options supported which are :-

a) None - Css are placed in head section like normal css.





b) Native - Depending on your browser support, it tries to use ShadowDom if it can.





c) ShadowDom - uses browser shadow dom for component rendering.





d) Emulated - Css are placed in head section (and the names are awkward) and only accessible by component query selector.

How do you do it?


import{Component,ViewEncapsulation}from'@angular/core';
This is how you configure it on your angular components.





Pretty straight-forward. :)



apollo server - getting started

To get started using apollo server to support graphql query that will expose all your data to a web client, you just need to install the following dependencies.

npm install --save apollo-server graphql
Now lets expose some  data in our server. 

const books =[{ title:'Harry Potter and the Chamber of Secrets', author:'J.K. Rowling',},{ title:'Jurassic Park', author:'Michael Crichton',},];// Type definitions define the "shape" of your data and specify// which ways the data can be fetched from the GraphQL server.const typeDefs = gql` # Comments in GraphQL are defined with the hash (#) symbol. # This "Book" type can be used in other type declarations. type Book { title: String author: String } # The "Query" type is the root of all GraphQL queries. # (A "Mutation" type will be covered later on.) type Query { books: [Book] } `;// Resolvers define the technique for fetching th…

Getting started with apollo client

$ npx create-react-app react-graphql $ cd react-graphql $ npm start

npminstall apollo-boost react-apollo graphql --save
Copy and paste this in your app.js and you're good to go.


importReact, { Component } from'react'; importlogofrom'./logo.svg'; import'./App.css'; import { ApolloProvider } from"react-apollo"; importApolloClientfrom"apollo-boost"; importgqlfrom"graphql-tag"
constclient = newApolloClient({ uri:"http://localhost:4000" });
client .query({ query:gql` { books { title author } } ` }) .then(result=>console.log(result));

classAppextendsComponent { render() { return ( <divclassName="App"> <ApolloProviderclient={client}> <headerclassName="App-header"> <imgsrc={logo}className="App-logo"alt="logo"/> <p> Edit <code>src/App.js</code> and save to reload. </p> <a className="App-link" href="…

Gatsbyjs Working with images

Let's say we have an image called 1.jpg located in our folder called "assets". We would normally display it using



Easy enough.

Why do you want to use gatsby image sharp plugin, that's because we want to 'size' our image for different screen resolution settings.  For example, you might want to target mobile devices or desktop, you don't have to create multiple images.

Now if you work with Gatsby, normally we use graphql.  First we need to install a plugin called "gatsby-source-filesystem".

resolve:"gatsby-source-filesystem", options: { name:"assets", path:`${__dirname}/static/assets/` }



Our image reside in this folder "static/assets". If you have a 1.jpg in here, go to http://localhost:8000/___graphql


Paste the following code :-

query {
  imageMain: file(relativePath: {eq: "1.jpg"}) {
    childImageSharp {
      fluid(maxWidth: 1000) {
        base64
        tracedSVG
        aspectRatio
        src
        sr…