Friday 6 October 2017

React & Webpack Example


1. React & Webpack Example found from this url: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html


2. Code of React & Webpack Example

import * as React from "react";

class HelloParent extends React.Component<{}, {}> {
    constructor(prop) {
        //call parent class constructor
        super(prop);
    }

    private onNameChange(name) {
        console.log(name);
        //call child method from parent
        this.hellComponet.callByParent("BillTo");
    }
    hellComponet: any;

    render() {
        return (<Hello ref={instance => { this.hellComponet = instance; }} name="Willson" onNameChange={this.onNameChange} />);
    }

}

interface HelloProps {
    name: string;
    onNameChange: (name: string) => void;
}

interface HelloState {
    name: string;
}

class Hello extends React.Component<HelloProps, HelloState> {
    constructor(prop) {
        //call parent class constructor
        super(prop);

        //Define State
        this.state = {
            name: "A"
        }

        //set State
        this.setState({ name: "B" });

        //call parent class method from child
        this.props.onNameChange(this.state.name);

        //Bind the functions
        this.callByParent = this.callByParent.bind(this);
    }

    componentWillMount() {

        //async call by the typescript promise
        let promises: Array<Promise<any>> = [];
        this.getMethod("", "", null, "", null, null, promises);

        //Core js Promise resolve all call.
        Promise.all(promises).then(() => { });

    }

    private getMethod(url: string, baseUrl: string, headers: Array<string>, method: string, body: any, parser: any, promises: Promise<any>[]): void {
        promises.push(
            fetch((url.indexOf("http") == 0 ? url : baseUrl + url), {
                credentials: 'same-origin',
                headers: headers,
                method: method,
                body: typeof body == "string" ? body : JSON.stringify(body)
            }).then(parser)
        );
    }

    public callByParent() {

    }

    render() {
        return <div>Hello, {this.props.name}</div>;
    }

}

export default Hello;









Adal Authentication


var variables = {
  // Domain of Azure AD tenant
  azureAD: "orgname.onmicrosoft.com",
  // ClientId of Azure AD application principal
  clientId: "11111111-1111-1111-1111-111111111111",
  resource: = location.hostname == "localhost" ? "ms crm root url" : location.origin;
}

window.config = {
  tenant: variables.azureAD,
  clientId: variables.clientId,
  postLogoutRedirectUri: window.location.origin,
 endpoints: { orgUri: variables.resource },
  cacheLocation: "localStorage"
};

var authContext = new AuthenticationContext(config);

After the authentication context is created, we make sure the user is authenticated.

var user = authContext.getCachedUser();
if (!user) {
  authContext.login();
}


Now login to application

var token;
var token;
if (user) {
authContext.acquireToken(variables.resource, (message, token) => {
                                                            if (token) {
                                                                        token = token;
                                                                       
                                                            } else {
                                                                        authContext.login();
                                                                       
                                                            }
                                                });
} else {
                           authContext.login();
                     }


jQuery API call

var baseUrl = ' root url ';
var url = '/actionname';

$.ajax({
    type: "GET",
    url: baseUrl + url,
    headers: {
        "Authorization": "Bearer " + token,
        "accept": "application/json;odata=verbose"
    }
}).done(function (response) {
    console.log("Successfully fetched list.");
    var items = response.d.results;
}).fail(function () {
    console.log("Fetching list from SharePoint failed.");
});

Using Typescript Core JS API Call of MS CRM Rest

let baseUrl = 'root url';
let url = '/actionname';
let body = {
            <parameter name>: < parameter name value> || ""
        }
let method = “GET

public restapiCall(baseUrl , url, method, token, body): Promise<any>
{
      
var headers: any = {
    "Accept": "application/json; odata.metadata=none",
    "Content-Type": "application/json",
    "Cache-Control": "no-cache, no-store" //Dont cache values; had an issue that acc status was not updated as and when it changes in CRM.
};

if (token) { headers["Authorization"] = "Bearer " + token; }

let parser: any = function (res: Response) {
    if (res.status == 204) {//No data
        return { value: [], headers: res.headers, status: res.status }
    } else {
        return res.json().then((jsonParsed) => {
            if (!res.ok) throw new Error(jsonParsed.error.message);
            jsonParsed["headers"] = res.headers;
            jsonParsed["status"] = res.status;
            return jsonParsed;
        });
    }
}

return fetch((url.indexOf("http") == 0 ? url : baseUrl + url), {
    credentials: 'same-origin',
    headers: headers,
    method: method,
    body: typeof body == "string" ? body : JSON.stringify(body)
}).then(parser);


}

Typescript references which can use in your project


1.      adal

adal js usefull for sign-in, sign-out, and secure OAuth API calls to your single-page apps using token which is hosted on Azure Active Directory (Azure AD).

For example:         html web resource of MS CRM online.
html web resource is single page application and MS CRM online is azur application.
In this example, without open ms-crm online adal help to loing by token in html web resource.
     
For more information


2.      core-js
Provide core functionality of different types like Promise function, string function, Number function etc…

3.      decimal.js
Provide decimal type support

4.      jQuery
Provide jQuery support

5.      node
Provide node i/o support

6.      bootstrap
Provide bootstrap support
7.      react
Provide react support
8.      react-dom
Provide react with html DOM support

9.      react-bootstrap
Provide bootstrap in react support

10.  react-bootstrap-table
Plug-in of bootstrap-table in react

11.  angular

Provide angular support

Thursday 5 October 2017

Manually setup typescript project in VS 2015



.         1. Download -- Typescript Tools for Microsoft Visual Studio 2015

          2. Install Typescript Tools for Microsoft Visual Studio 2015 in your system.

       3. Create new Project of “HTML Application with Typescript”.




        4. Add folder structure as per below image in your project.

         5. Go to project property and apply configure settings as per following screen Typescript build settings.


           6. Collect your reference library files. There are two way

1.    Download

a.       All Typescript definition files download location is (make sure your browser is internet explorer) https://github.com/DefinitelyTyped/DefinitelyTyped/
b.      From this location download library.
c.       Find your definition file from 

OR

2.    Search
a.       Go to below search URL is (make sure your browser is internet explorer) https://github.com/DefinitelyTyped/DefinitelyTyped/find/master
b.      Type your file location like /types/react 
c.       Open file and get your code.



   
          7. Copy the reference library folder and create reference library folder under the @types folder.
       Copy the reference library files and paste to reference library folder under the @types folder.

        8. Open you reference library file and it must be sure to version of definition file (xxx.d.ts) with Typescript version.



.      9. Now build your project its working now.


Notes:

Error: “Cannot use imports, exports, or module augmentations when '--module' is 'none'”

Solution:

1 Open project properties (right click on your project in the Solution Explorer, and click "Properties").

2 Open the TypeScript tab.

3 Choose AMD in the module system section.

Tuesday 26 September 2017

Function to find all HTML Element Tag from HTML Document which have text

render() 
{
        let partial: any;

        let elements = document.body.getElementsByTagName("*");
        var scripts = document.body.getElementsByTagName("script");
        for (var i = 0; i < elements.length; i++) {
            var flag = true;
            for (var j = 0; j < scripts.length; j++) {
                if (elements[i] == scripts[j]) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                var str = i == 0 ? elements[i].outerHTML : elements[i].innerHTML;
                if (str) {
                    let currElement: Element = elements[i];
                    if (this.readText(str) != "") {
                        currElement.classList.add(".parenteditable");
                        console.log(this.readText(str));
                    }
                }
            }
        }
        return (<div></div>);
    }

    readText = function (str) {
        var a = document.createElement('div');
        a.innerHTML = str;
        var htmlText = "";
        for (var c = a.childNodes, i = c.length; i--;) {
            if (c[i].nodeType == 3 && c[i].textContent)
                htmlText = htmlText + c[i].textContent;
        }
        return htmlText.trim();
    }




Add document/dom level java script event in Type Script

componentDidMount() {
        const dom = ReactDOM.findDOMNode(this);
        dom.addEventListener('mousedown', e => this.handleMouseDown(e));
}

 public handleMouseDown(e: any): void
 {
        alert(e.target.value);
 }


Read external java script library function in Type Script

1. Declare Module

declare var Alert: Alert.IAlertJsStatic;

//javscript file name is alert.js
declare module 'alert' {
    export = Alert;
}

declare namespace Alert {
     
    
    interface IAlertJsConfig {
    }

    interface IAlertJsStatic extends IAlertJsConfig  {
        showLoading(str: string): void;
    }
    
}

2. Read Module in Type Script Code

 Alert.showLoading('');