Wednesday, December 13, 2017

Different between Multi Thread and Asynchronous

  • Synchronous: you cook the eggs, then you cook the toast.
  • Asynchronous, single threaded: you start the eggs cooking and set a timer. You start the toast cooking, and set a timer. While they are both cooking, you clean the kitchen. When the timers go off you take the eggs off the heat and the toast out of the toaster and serve them.
  • Asynchronous, multithreaded: you hire two more cooks, one to cook eggs and one to cook toast. Now you have the problem of coordinating the cooks so that they do not conflict with each other in the kitchen when sharing resources. And you have to pay them.
  • Threading is about workers; Asynchronous is about tasks
  • Tasks where some tasks depend on the results of others; as each task completes it invokes the code that schedules the next task that can run, given the results of the just-completed task. But you only need one worker to perform all the tasks, not one worker per task.

async and await

  • async to create asynchronous method.
  • await is wait until the process is complete
  • If windows form has Async, it will show "loading" label and you can move form. 
  • Without Async, the form will hang and unhang when the task is finish.
Task
public async void btnProcess_click()
{
    Task<int> task = new Task<int>(CountChacaracter); //Function
    task.Start();

    lblCount.text = "Loading. Please wait";
    int count = await task; //wait for result
    lblCount.text = count.ToString();
}

Thread
UI thread (main thread) is invoke a new thread, you need to thread join to join back the thread. But It will Block the UI cannot move to wait the result.

public async void btnProcess_click()
{
    int count = 0;
    Thread thread = new Thread(() => { count = CountChacaracter(); });
    thread.Start();

    lblCount.text = "Loading. Please wait";
    thread.Join();
    lblCount.text = count.ToString();

}

With this, you can move the UI, but is not correct way, because only UI thread can modify the control, (it may or may not work, depend on luck)

Thread thread = new Thread(() => 
    count = CountChacaracter(); 
    lblcountText = count.tostring(); 
});

This is correct way, and same result as Task. But code is complicated, so use TASK!!

public async void btnProcess_click()
{
    int count = 0;
    Thread thread = new Thread(() =>
    {
        count = CountChacaracter();
        Action action = new Action(SetLabel(count));
        this.BeginInvoke(action);
    });

    thread.Start(); 
    lblCount.text = "Loading. Please wait";
}

private void SetLabel(int count)
{
    lblCount.text = count.ToString();
}

Tuesday, November 28, 2017

AWS Alexa

Intent - Goal want to achieve (BookHotel), map in Skill Service (Lambda)
Invocation Name - Intent people Said
Sample utterance -  Invoke Intent (book)
Slot - parameter fulfill the intent {City} (New York)

From, Ask, About, Using > Keyword to trigger intent
Open, Talk, Play, Start > Session working with intent (exit, close to stop the session)

Skill Service - Utterances, Slot Types, Intent Schema (Amazon Developer) [Configuration]
Skill Interface - Lambda, HTTP Service

Sunday, November 19, 2017

Web.Config Transform Debug & Release

1) Tool and Extension , Download "Configuration Transform".
2) Your Web or App.config, right click >  "Add Config Transform"
3) Add your changes

<appSettings>

    <add key="WaitSec" value="10" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
</appSettings>

Thursday, October 12, 2017

Cron Job

  1. Create a cron.yaml
  2. Write Code
cron:
- description: Update Today Flight job
  url: /api/Flight/UpdateTodayFlights/KUL

  schedule: every day 02:00
  1. cd yamlfilepath
  2. gcloud app deploy cron.yaml

Firebase Realtime DB vs Firestore


  • Firestore has better querying and more structured data
    • document-model database 
      • store data in Documents, organized into Collection
      • Each document contain a set of key-value pairs.
      • Documents can contain sub collections and nested objects.
    • Search multiple field.
  • Realtime DB better latency
Pricing Model
  • Realtime DB = amount of downloaded and store on DB.
  • Firestore DB = number of reads or write.
  • Traditional App, Request large of data > Firestore
  • Many updates in second > Realtime

Firestore Data Model

  • Similar to JSON
  • Document is record, map value with name
  • name of document is unique (add() will automatically)

Monday, October 9, 2017

Firebase C#

private FirebaseClient Auth()
{
    var firebaseClient = new FirebaseClient(_URL,
        new FirebaseOptions
        {
            AuthTokenAsyncFactory = () => Task.FromResult(_FireBaseApiKey)
        });

    return firebaseClient;
}

public async Task<Dictionary<string, T>> ListLimitLast<T>(string table, string filterKey, string filterValue, int limitLast)
 {
     var firebase = Auth();

     var result = await firebase
         .Child(_Database)
         .Child(table)
         .OrderBy("DriverStaff/UserName")
         .EqualTo(filterValue)
         .LimitToLast(limitLast)
         .OnceSingleAsync<Dictionary<string, T>>();

     return result;

 }

use dictionary because ID is parent, object is child.

Monday, September 25, 2017

Condition Throw Exception

if (list == null || list.Count < 1)

    throw new ApplicationException("Get list Failed.");

Monday, September 11, 2017

Firebase Cloud Function

  • Function for Fire base features (trigger event by firebase)
    • in GCP, not your mobile (light for your mobile app)
    • Logic Centralized , safe, server less
  • Example
    • Write Realtime Database trigger function
    • Upload your storage bucket
    • New user authentication
    • Incoming HTTPS requests
    • Send Message
  1. Install Node.JS
  2. Install Firebase CLI
    • npm install -g firebase-tools
  3. cd to folder (firebase cloud function project)
  4. firebase login
  5. firebase init (Deselect Database and Hosting)

https://www.youtube.com/watch?v=EvV9Vk9iOCQ#t=314.64541


Thursday, August 24, 2017

Google Cloud Web API c#

1. Create Project  > Google Cloud ASP.NET Core Web API C#
2. Choose Google Project ID (can link with FireBase)

If you want run locally you need to add credential


3. Create  json file,
4. Copy this .json file to locally (outside cannot browse)


public Startup(IHostingEnvironment env)
{
      //Here is the Code for Credential
    string credential_path = "CargoTracking-2e89f93ec38b.json";
    Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", credential_path);

------------------------

[GCP Command]
gcloud config list
gcloud auth login
gcloud config set project [myproject]

Wednesday, August 16, 2017

AWS Lambda - Custom Authorization

Lambda Code

Refer

public AuthPolicy Authorization(TokenAuthorizerContext request)
{
    var token = request.AuthorizationToken;

    switch (token.ToLower())
    {
        case "allow":
            return generatePolicy("user", "Allow", request.MethodArn);
        case "deny":
            return generatePolicy("user", "Deny", request.MethodArn);
    }

    return null;
}


At Lambda to Custom Authorization


Add Custom Authorization to API Gateway Method


POSTMAN Test



Monday, August 7, 2017

AWS Lamda

  • Service that lets you run code without managing servers (server-less)
  • Execute your code when needed and scales automatically. (no charge when your code not running)
  • Included Server and OS maintenance, auto scaling,  code monitoring and logging (FOC)
  • Support Node.js, Java, C# and Python.
  • It can run your code in response to events. E.g. Data Processing trigger for Amazon S3 or Amazon DyanamoDB
  • It can build Serverless applications. (only concern your code)
  • Outsider call Lambda thru API Gateway
  • Lambda can be custom authorization  at API Gateway
Step to create Lambda Project in VS2017


1) Need to Install AWS Extension



2) Deployment



3) API Gateway



.NET Core


  • Open Source
  • Cross-platform (Linux, MAC, Windows) framework for building modern cloud-based web applications (UI and API) using .NET
  • ASP.NET Core MVC = MVC + Web API + Web Pages
  • It can run on IIS or Self-hosted


Tuesday, August 1, 2017

Single Sign On (SSO)

ASP.NET Forms Authentication allow to share the same cookie across sites under same domain using configuration key <machineKey>


<machineKey 
  validationKey="21F090935F6E49C2C797F69BBAAD8402ABD2EE0B667A8B44EA7DD4374267A75D" 
  decryptionKey="ABAA84D7EC4BB56D75D217CECFFB9628809BDB8BF91CFCD64568A145BE59719F"
  validation="SHA1" decryption="AES"/>

Why need <machineKey>, because each ASP.NET web application use it own encryption keys for cookie data and others e.g. ViewState for security purpose. So if the same <machineKey>, across all applications under same domain, each will able to read cookie values.

After that, you need to instruct ASP.NET runtime to define the cookie so it can match with the domain name.

<forms name="name" loginUrl="URL" defaultUrl="URL" domain="mydomain.com"/>

ASP.NET is not able to share cookie across different domain.
_______________________________________________________________________________

Work Around (1)

1)User request domain1.com, no authentication cookie, redirect to domain1.com/login.
2) Login
3) domain1.com accept the login credential, verify from database. and Create authentication cookie  and add to the response
4) Response set ReturnURL to domain2.com.
5) domain2.com accept the response with cookie and store in browser.
6) domain2.com redirect to the  ReturnURL address (domain1.com) with reading the cookie value.
7) domain1.com accept the response with cookie and store in browser.

So both domain1.com and domain2.com authenicaton cookie are stored in the browser.

Problem : You need to implement for all the sites (costly and complex). Not recommend for domain more than 2


Basic_SSO_model_overview.png
_______________________________________________________________________________

Work Around (2)

Browser will not store authentication cookies for each site. It will store an authentication cookie for only in a site (sso.com). Every request to any site will redirect to sso.com for setting and checking authentication cookie. If not found, the user redirected to the login page.

1) User request domain1.com, redirect to sso.com to check cookie, with adding a ReturnURL query string paramater to back domain1.com.
2) If no cookie, request to domain1.com with query string has indicate the cookie not found and redirect to domain1.com/login
3) Login in domain1.com/login and invoke web service of sso.com to check user credentials, and return Token.
4) domain1.com mark the user as logged in, redirect to sso.com with Token to set authentication cookie, with ReturnUrl (domain1.com)

https://www.codeproject.com/Articles/106439/Single-Sign-On-SSO-for-cross-domain-ASP-NET-applic
https://www.codeproject.com/Articles/114484/Single-Sign-On-SSO-for-cross-domain-ASP-NET-appl#_articleTop

Wednesday, April 5, 2017

Enable Cors

JS cannot call Web api, it will get block, add code below to Web API web.config to enable cors.

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true" />
  <!--<handlers>
     <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
   </handlers>-->
  <httpProtocol>
    <customHeaders>
      <!--<add name="Access-Control-Allow-Origin" value="*" />
       <add name="Access-Control-Allow-Headers" value="*" />
       <add name="Access-Control-Allow-Methods" value="*" />-->
      <remove name="X-Powered-By" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

Monday, March 27, 2017

Angular JS 2

Need Node.js, NPM and Git


Module
  • The module component is a block of code which can be used to perform a single task
  • You can export the value of something from the code such as a class
  • The Angular apps are called as modules and build your application using many modules. 
  • The basic building block of Angular 2 is a component class which can be exported from a module.
Component 
  • is a controller class with a template which deals with a view and logic on the page. 
  • Component knows how to render itself and configure dependency injection
  • You can associate CSS styles using component inline styles, style urls and template inline styles to a component.
  • To register component, we use @Component annotation and can be used to break up the application into smaller parts. There will be only one component per DOM element.
Template
  • The component's view can be defined by using the template which tells Angular how to display the component.
  • To display the value, you can put template expression {{name}} within the interpolation braces.
Metadata
  • Metadata is a way of processing the class
  • E.g. we have one component called MyComponent which will be a class until we tell Angular that it's a component. You can use metadata to the class to tell Angular that MyComponent is a component. 
  • The metadata can be attached to TypeScript by using the decorator.
Data Binding
  • Data binding is a process of coordinating application data values by declaring bindings between sources and target HTML elements
  • It combines the template parts with components parts and template HTML is bound with markup to connect both sides. 
  • There are four types of data binding:
    • Interpolation: It displays the component value within the div tags.
    • Property Binding: It passes the property from the parent to property of the child.
    • Event Binding: It fires when you click on the components method name.
    • Two-way Binding: This form binds property and event by using the ngModel directive in a single notation.
Service
  • Services are used for reusable data services to access data (Get Data From API / Databases) to from or share by all components.
  • Angular services are injected using Dependency Injection mechanism. (asynchronous
  • So Component only focus for supporting the view.
  • Service includes the value, function or feature which is required by the application. Generally, service is a class which can perform something specific such as logging service, data service, message service, the configuration of application etc. There is nothing much about service in Angular and there is no ServiceBase class, but still services can be treated as fundamental to Angular application.
Directive
  • The directive is a class that represents the metadata. There are three types of directives:
    • Component Directive: It creates custom controller by using view and controller and used as custom HTML element.
    • Decorator Directive: It decorates the elements using additional behavior.
    • Template Directive: It converts HTML into a reusable template.
Dependency Injection
  • Dependency Injection is a design pattern that passes an object as dependencies in different components across the application. It creates new a instance of class along with its required dependencies.
You must remember the below points while using Dependency Injection:
  • The Dependency Injection is stimulated into the framework and can be used everywhere.
  • The injector mechanism maintains service instance and can be created using a provider.
  • The provider is a way of creating a service.
  • You can register the providers along with injectors.

Monday, March 6, 2017

Node.js


  • built on Google Chrome's Javascript Engine. (Written in Javascript)
  • Single thread application but run in concurrency support by callbacks and event.
  • Runtime environment + Javascript Library = Node.js
  • Open Source.
  • Cross platform ( run on OS X, Windows, and Linux)

Features
  • Acronymous and Event Driven 
    • All API's of Node.js Library is Acronymous with non-blocking. (Never wait for API return data)
    • E.g. Server moves to the next API after calling it and a notification mechanism of Events of Node.js helps the server to get a response from the previous API call.
  • Very Fast
  • Single Threaded but Highly Scalable 
    • Use a single threaded model with event looping.
    • Event mechanism helps the server to respond in a non-blocking way and makes the server highly scalable as  not like traditional servers (create limited threads to handle requests)
    • Node.js uses a single threaded program and the same program can provide service to a much larger number of requests than traditional servers like Apache HTTP Server.

Blocking Code

  • The program blocks until it reads the file and then only it proceeds to end the program.

  • Read From File!!!!!
    Program Ended
Non-Blocking Code
  • The program does not wait for file reading and proceeds to print "Program Ended" and at the same time, the program without blocking continues reading the file.

  • Program Ended
    Read From File!!!!

Callback 
  • is an asynchronous equivalent for a function. 
  • is called at the completion of a given task. 
  • Node.js heavy use of callbacks. All the APIs of Node.js are written in such a way that they support callbacks.
  • E.g. a function to read a file may start reading the file and return the control to the execution environment immediately so that the next instruction can be executed. Once file I/O is complete, it will call the callback function while passing the callback function, the content of the file as a parameter. So there is no blocking or wait for File I/O. This makes Node.js highly scalable, as it can process a high number of requests without waiting for any function to return results.
Event-Driven Programming
  • Node.js starts its server, it simply initiates its variables, declares functions and then simply waits for the event to occur.
  • In an event-driven application, there is a main loop that listens for events and then triggers a callback function when one of those events is detected.
  • Node.js uses observer pattern. Node thread keeps an event loop and whenever a task gets completed, it fires the corresponding event which signals the event listener function to execute.
  • Whenever an event gets fired, its listener function starts executing. 
  • Node.js has multiple in-built events (events module and EventEmitter) which used to bind events and event-listeners.
Different Event and Callback
  • Callback functions are called when an asynchronous function return its result.
  • Whereas event handling work on observer pattern.

Thursday, March 2, 2017

Different Between Javascript and AngularJS expression

Angular JS

  • is a Javascript Framework
  • ng-app 
      • root element of Application (Tell HTML to use AngularJS)
  • ng-controller
      • Define Controler.
  • ng-model
      • Bind HTML Control value to App Data.
  • ng-bind
      • Bind App Data to HTML Control Value.
      • {{expression}} = output {{5+5}} = 10 
  • ng-int 
      • Initialize AngularJS app variable (JSON)
  • Service(AJAX) : $http
      •  Read Data from Server side(HTTP Request) / Text File
  •  $scope : parameter passed to the controller
      • Is Model Between Controller and Views
      • $scope.message & $scope.type is to display in HTML page.
  • Validate Data
      • $dirty : value has changed ?
      • $Invalid: value is Invalid ?
      • $error: State exact error.
  • Include
      • Embedding HTML Page
      • Can more than 1 in 1 HTML Page.
      •  For Code Reuse
      • Good For Header/ Footer/ Sidebar
  • ng-view
      • Partial Represent with controller and Route (Page's URL)
      • Only 1 per HTML Page.
      • Good For Content of the page.
      • and Change by URL (Category, PageNum, ID)
  • ng-template
      • Create an html view using Script Tag.
      • It contrain "id", and use &routeProvider to map a view with controller.
  • &routeProvider
      • Key configuration of URL map with HTML or ng-template


Tuesday, February 14, 2017

Stored Prcocedure

 USE [DeviceDB]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[sp_RptNewAccVelocity]
@SubscriberId int,
@ReportLength int = null,
@Order char(30) = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE @SQL_STATEMENT nvarchar(3000);

SET @SQL_STATEMENT = 'SELECT c.CreatedDate AS ''AccCreatedDate'', b.AccountId, c.AccountCode, a.DeviceId FROM dbo.tblTransaction a WITH(NOLOCK) INNER JOIN ( ';

SET @SQL_STATEMENT += 'SELECT MIN(CreatedDate) AS CreatedDate, AccountId FROM dbo. tblTransaction WITH(NOLOCK)';

SET @SQL_STATEMENT += 'WHERE SubscriberId = '+ CAST(@SubscriberId as varchar(20)) + ' ';
   
IF (@ReportLength IS NOT NULL)
SET @SQL_STATEMENT += 'AND CreatedDate >= DATEADD(day, - '+ CAST(@ReportLength as varchar(20))   +', GETUTCDATE()) ';

SET @SQL_STATEMENT += 'GROUP BY AccountId ) b ON a.AccountId = b.AccountId AND a.CreatedDate = b.createdDate ';

SET @SQL_STATEMENT += 'INNER JOIN dbo.tblAccount c WITH(NOLOCK) ON c.AccountId=b.AccountId ';
      
SET @SQL_STATEMENT += 'WHERE a.SubscriberId = '+ CAST(@SubscriberId as varchar(20)) + ' ';
   
IF (@ReportLength IS NOT NULL)
SET @SQL_STATEMENT += 'AND c.CreatedDate >=  DATEADD(day, - '+ CAST(@ReportLength as varchar(20))   +', GETUTCDATE()) ';

IF (@Order IS NOT NULL)
SET @SQL_STATEMENT += 'ORDER BY ' + CAST(@Order as varchar(30)) + ' ';

EXEC sp_executesql @SQL_STATEMENT; // print @SQL_Statement
END