Tuesday, December 12, 2017

Electron first try with Active Directory and MSSQL access

electron_0
Electron is a framework base on Chromium and Node.js, it can create cross platform native applications with web technologies run on Mac, Windows, and Linux.

Recently I got a request to make a application to do some automatic stuff on Mac and Windows, after search on google, I think Electron was worth to try. But sadly the project got cut-out few day ago, so I only can share some experience what I got.


Develop on Visual Studio

electron_4
Some people code electron on VS Code, but it can develop on Visual Studio too, just create a new project of TypeScript(or Node.js if you got it), then follow Electron guide or clone electron-quick-start and modify it.

If you want to debug on Visual Studio, you can check Attach visual studio debugger to electron app for more detail, but dunno why I can't debug in VS.

Active Directory

ActiveDirectory for Node is great package if you need using AD on node.js, sample code like this, remember change url and baseDN to your own config.
var ActiveDirectory = require('activedirectory');
var AdConfig = {
    url: 'ldap://died.com.tw',
    baseDN: 'dc=died,dc=com,dc=tw'
}
loginBtn.addEventListener('click',
    function (event) {
        var ad = new ActiveDirectory(AdConfig);
        var username = "[email protected]";
        var password = "password";

        ad.authenticate(username, password, function (err, auth) {
            if (err) {
                console.log('ERROR: ' + JSON.stringify(err));
                return;
            }

            if (auth) {
                console.log('Authenticated!');
            }
            else {
                console.log('Authentication failed!');
            }
        });
    });

Success result.
electron_2

Fail result, error code can check here for more info.
electron_1


MSSQL

To using MSSQL on node.js can install node-mssql package from npm, sample code like this.
const sql = require('mssql');
const config = {
    user: "USERNAME",
    password: "PASSWORD",
    server: "localhost", // You can use 'localhost\\instance' to connect to named instance
    database: 'DBNAME',
    options: {
        encrypt: false // Use this if you're on Windows Azure
    }
}
sql.on('error',
    err => {
        // ... error handler
    });
sqlBtn.addEventListener('click',
    function (event) {
        sql.connect(config).then(pool => {
            // Query
            return pool.request()
                .input('input_parameter', sql.Int, 1) // id=1
                .query('select * from station where id = @input_parameter');
        }).then(result => {
            console.log(result);
        }).catch(err => {
            console.log(err);
        });
    });

And the result.
electron_3

That's all, I think Electron is good thing, hope I have more time to play with it.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...