Graph API implementation for getting AD Users in Office 365 - Show in Grid and set some filtration


Main Functionality :- I want to get all AD Users from Office 365 and display it in grid with some filtration. If there is not login available then it will redirect to login page.

Need to create new Azure Application and get ID of that app to set.
Here is the full code for that. 


<html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">
<head>
</head>
<body>
    <style>
        #myProgress {
            width: 100%;
            background-color: #ddd;
        }

        #myBar {
            width: 00%;
            height: 15px;
            background-color: #C6006F;
            text-align: center;
            line-height: 15px;
            color: black;
        }

        .datagrid table {
            border-collapse: collapse;
            text-align: left;
            width: 100%;
        }

        .datagrid {
            font: normal 12px/150% Arial, Helvetica, sans-serif;
            background: #fff;
            overflow: hidden;
            border: 1px solid #C6006F;
            -webkit-border-radius: 3px;
            -moz-border-radius: 3px;
            border-radius: 3px;
        }

            .datagrid table td, .datagrid table th {
                padding: 3px 10px;
            }

            .datagrid table thead th {
                background: -webkit-gradient( linear, left top, left bottom, color-stop(0.05, #C6006F), color-stop(1, #00557F) );
                background: -moz-linear-gradient( center top, #C6006F 5%, #00557F 100% );
                filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#C6006F', endColorstr='#00557F');
                background-color: #C6006F;
                color: #FFFFFF;
                font-size: 15px;
                font-weight: bold;
                border-left: 1px solid #0070A8;
            }

                .datagrid table thead th:first-child {
                    border: none;
                }

            .datagrid table tbody td {
                color: #00557F;
                border-left: 1px solid #E1EEF4;
                font-size: 12px;
                font-weight: normal;
            }

            .datagrid table tbody .alt td {
                background: #E1EEf4;
                color: #00557F;
            }

            .datagrid table tbody td:first-child {
                border-left: none;
            }

            .datagrid table tbody tr:last-child td {
                border-bottom: none;
            }

        .button4 {
            background-color: #e7e7e7;
            color: black;
        }
        /* Gray */
    </style>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="https://secure.aadcdn.microsoftonline-p.com/lib/1.0.0/js/adal.min.js"></script>
    <script type="text/javascript">
        var graphAPIGlobal = "";
        var tokenGlobal = "";
        var _filterByGlobal = "";
        var _filterTextGlobal = "";


        function move() {
            var elem = document.getElementById("myBar");
            var width = 10;
            var id = setInterval(frame, 15);
            function frame() {
                if (width >= 100) {
                    clearInterval(id);
                } else {
                    width++;
                    elem.style.width = width + '%';
                    elem.innerHTML = width * 1 + '%';
                }
            }
        }

        (function () {
            "use strict";
            // Some samples will use the tenant name here like "tenant.onmicrosoft.com"
            // I prefer to user the subscription Id
            //var subscriptionId = "7ac27593-XXXX-4d98-81bf-XXXXXXXXXXXX";
            // Copy the client ID of your AAD app here once you have registered one, configured the required permissions, and
            // allowed implicit flow https://msdn.microsoft.com/en-us/office/office365/howto/get-started-with-office-365-unified-api
            var clientId = "AZURE APPLICATION ID HERE";

            window.config = {
                // subscriptionId: subscriptionId,
                //tenantName: 'joyalsttl.onmicrosoft.com',
                clientId: clientId,
                postLogoutRedirectUri: window.location.origin,
                endpoints: {
                    graphApiUri: 'https://graph.microsoft.com'
                },
                cacheLocation: 'localStorage' // enable this for IE, as sessionStorage does not work for localhost.
            };

            var authContext = new AuthenticationContext(config);
            // Check For & Handle Redirect From AAD After Login
            var isCallback = authContext.isCallback(window.location.hash);
            authContext.handleWindowCallback();
            if (isCallback && !authContext.getLoginError()) {
                window.location = authContext._getItem(authContext.CONSTANTS.STORAGE.LOGIN_REQUEST);
            }
            // If not logged in force login
            var user = authContext.getCachedUser();
            if (user) {
                // Logged in already
            }
            else {
                // NOTE: you may want to render the page for anonymous users and render
                // a login button which runs the login function upon click.
alert('Login require to get AD users');
                authContext.login();
            }
            // Acquire token for Files resource.
            //alert(config.endpoints.graphApiUri);
            authContext.acquireToken(config.endpoints.graphApiUri, function (error, token) {
                // Handle ADAL Errors.
              /*  if (error || !token) {
                    alert('ADAL error occurred: ' + error);
                    console.log('ADAL error occurred: ' + error);
                    return;
                }
                else {
                    //alert('waiting for response...');
                }*/

                // Execute GET request to Files API.
                graphAPIGlobal = config.endpoints.graphApiUri + "/v1.0/users?&$top=999";
                tokenGlobal = token;
                GetUsers(graphAPIGlobal, tokenGlobal);

            });
        })();

        function btnClicked(e) {
            e.preventDefault();
            var filterBy = $("#filterBY").find(":selected").text();
            var filtertext = $("#filterText").val();
            _filterByGlobal = filterBy;
            _filterTextGlobal = filtertext;
            move();
            GetFilterUsers(graphAPIGlobal, tokenGlobal);
        }

        function handle(e) {
            if (e.keyCode === 13) {
                e.preventDefault(); // Ensure it is only this code that rusn
                var filterBy = $("#filterBY").find(":selected").text();
                var filtertext = $("#filterText").val();
                _filterByGlobal = filterBy;
                _filterTextGlobal = filtertext;
                move();
                GetFilterUsers(graphAPIGlobal, tokenGlobal);
            }
        }

        function GetFilterUsers(api, tokenEnd) {
            var filesUri = api;
if(filesUri != '' && tokenEnd != '')
{
$.ajax({
type: "GET",
url: filesUri,
headers: {
'Authorization': 'Bearer ' + tokenEnd,
},
success: onSuccessFilter,
error: onError
})
}
        }

        function onSuccessFilter(data) {
            try {
                var objItems = data.value;
                var count = 0;
                var tableContent = '<table id="tableUsers" style="width:100%" border="1 px"><thead><tr><th><b>Name</b></th>' + '<th><b>Position</b></th>' + '<th><b>E-Mail</b></th>' + '<th><b>Office</b></th>' + '<th><b>Phone Number</b></th>' + '</tr></thead><tbody>';
                for (var i = 0; i < objItems.length; i++) {
                    if (_filterByGlobal != "Select" && _filterTextGlobal != "") {
                        switch (_filterByGlobal) {
                            case "Name":
                                if (objItems[i].displayName != null) {
                                    if (objItems[i].displayName.toUpperCase().indexOf(_filterTextGlobal.toUpperCase()) >= 0) {

                                        if (i % 2 == 0) {
                                            tableContent += '<tbody><tr id=row' + i + '>';
                                        }
                                        else {
                                            tableContent += '<tbody><tr class="alt" id=row' + i + '>';
                                        }
                                        tableContent += '<td>' + objItems[i].displayName + '</td>';
                                        tableContent += '<td>' + objItems[i].jobTitle + '</td>';
                                        tableContent += '<td>' + objItems[i].userPrincipalName + '</td>';
                                        tableContent += '<td>' + objItems[i].officeLocation + '</td>';
                                        tableContent += '<td>' + objItems[i].mobilePhone + '</td>';
                                        tableContent += '</tr></tbody>';
                                        count++;
                                    }
                                }
                                break;
                            case "Position":
                                if (objItems[i].jobTitle != null) {
                                    if (objItems[i].jobTitle.toUpperCase().indexOf(_filterTextGlobal.toUpperCase()) >= 0) {
                                        if (i % 2 == 0) {
                                            tableContent += '<tbody><tr id=row' + i + '>';
                                        }
                                        else {
                                            tableContent += '<tbody><tr class="alt" id=row' + i + '>';
                                        }
                                        tableContent += '<td>' + objItems[i].displayName + '</td>';
                                        tableContent += '<td>' + objItems[i].jobTitle + '</td>';
                                        tableContent += '<td>' + objItems[i].userPrincipalName + '</td>';
                                        tableContent += '<td>' + objItems[i].officeLocation + '</td>';
                                        tableContent += '<td>' + objItems[i].mobilePhone + '</td>';
                                        tableContent += '</tr></tbody>';
                                        count++;
                                    }
                                }
                                break;
                            case "E-Mail":
                                if (objItems[i].userPrincipalName != null) {
                                    if (objItems[i].userPrincipalName.toUpperCase().indexOf(_filterTextGlobal.toUpperCase()) >= 0) {
                                        if (i % 2 == 0) {
                                            tableContent += '<tbody><tr id=row' + i + '>';
                                        }
                                        else {
                                            tableContent += '<tbody><tr class="alt" id=row' + i + '>';
                                        }
                                        tableContent += '<td>' + objItems[i].displayName + '</td>';
                                        tableContent += '<td>' + objItems[i].jobTitle + '</td>';
                                        tableContent += '<td>' + objItems[i].userPrincipalName + '</td>';
                                        tableContent += '<td>' + objItems[i].officeLocation + '</td>';
                                        tableContent += '<td>' + objItems[i].mobilePhone + '</td>';
                                        tableContent += '</tr></tbody>';
                                        count++;
                                    }
                                }
                                break;
                            case "Office":
                                if (objItems[i].officeLocation != null) {
                                    if (objItems[i].officeLocation.toUpperCase().indexOf(_filterTextGlobal.toUpperCase()) >= 0) {
                                        if (i % 2 == 0) {
                                            tableContent += '<tbody><tr id=row' + i + '>';
                                        }
                                        else {
                                            tableContent += '<tbody><tr class="alt" id=row' + i + '>';
                                        }
                                        tableContent += '<td>' + objItems[i].displayName + '</td>';
                                        tableContent += '<td>' + objItems[i].jobTitle + '</td>';
                                        tableContent += '<td>' + objItems[i].userPrincipalName + '</td>';
                                        tableContent += '<td>' + objItems[i].officeLocation + '</td>';
                                        tableContent += '<td>' + objItems[i].mobilePhone + '</td>';
                                        tableContent += '</tr></tbody>';
                                        count++;
                                    }
                                }
                                break;
                            case "Phone Number":
                                if (objItems[i].mobilePhone != null) {
                                    if (objItems[i].mobilePhone.toUpperCase().indexOf(_filterTextGlobal.toUpperCase()) >= 0) {
                                        if (i % 2 == 0) {
                                            tableContent += '<tbody><tr id=row' + i + '>';
                                        }
                                        else {
                                            tableContent += '<tbody><tr class="alt" id=row' + i + '>';
                                        }
                                        tableContent += '<td>' + objItems[i].displayName + '</td>';
                                        tableContent += '<td>' + objItems[i].jobTitle + '</td>';
                                        tableContent += '<td>' + objItems[i].userPrincipalName + '</td>';
                                        tableContent += '<td>' + objItems[i].officeLocation + '</td>';
                                        tableContent += '<td>' + objItems[i].mobilePhone + '</td>';
                                        tableContent += '</tr></tbody>';
                                        count++;
                                    }
                                }
                                break;
                            default:
                                if (i % 2 == 0) {
                                    tableContent += '<tbody><tr id=row' + i + '>';
                                }
                                else {
                                    tableContent += '<tbody><tr class="alt" id=row' + i + '>';
                                }
                                tableContent += '<td>' + objItems[i].displayName + '</td>';
                                tableContent += '<td>' + objItems[i].jobTitle + '</td>';
                                tableContent += '<td>' + objItems[i].userPrincipalName + '</td>';
                                tableContent += '<td>' + objItems[i].officeLocation + '</td>';
                                tableContent += '<td>' + objItems[i].mobilePhone + '</td>';
                                tableContent += '</tr></tbody>';
                                count++;
                                break;
                        }
                    }
                    else {
                        if (i % 2 == 0) {
                            tableContent += '<tbody><tr id=row' + i + '>';
                        }
                        else {
                            tableContent += '<tbody><tr class="alt" id=row' + i + '>';
                        }
                        tableContent += '<td>' + objItems[i].displayName + '</td>';
                        tableContent += '<td>' + objItems[i].jobTitle + '</td>';
                        tableContent += '<td>' + objItems[i].userPrincipalName + '</td>';
                        tableContent += '<td>' + objItems[i].officeLocation + '</td>';
                        tableContent += '<td>' + objItems[i].mobilePhone + '</td>';
                        tableContent += '</tr></tbody>';
                        count++;
                    }
                }
                $("#totalCount").text("Total Count:- " + count);
                $('#userGrid').html(tableContent);
            }
            catch (e) {
                alert('An error has occurred : onSuccessFilter ' + e.message)
                console.log('An error has occurred : onSuccessFilter ' + e.message)
            }
        }

        function GetUsers(graphAPI, tokenEnd) {
            var filesUri = graphAPI;
if(filesUri != '' && tokenEnd != '')
{
$.ajax({
type: "GET",
url: filesUri,
headers: {
'Authorization': 'Bearer ' + tokenEnd,
},
success: onSuccess
//error: onError
})
}
        }

        function onSuccess(data) {
            try {
                move();
                var objItems = data.value;
                $("#totalCount").text("Total Count:- " + data.value.length);
                var tableContent = '<table id="tableUsers" style="width:100%" border="1 px"><thead><tr><th><b>Name</b></th>' + '<th><b>Position</b></th>' + '<th><b>E-Mail</b></th>' + '<th><b>Office</b></th>' + '<th><b>Phone Number</b></th>' + '</tr></thead><tbody>';
                for (var i = 0; i < objItems.length; i++) {
                    if (i % 2 == 0) {
                        tableContent += ' <tbody><tr>';
                        tableContent += '<td>' + objItems[i].displayName + '</td>';
                        tableContent += '<td>' + objItems[i].jobTitle + '</td>';
                        tableContent += '<td>' + objItems[i].userPrincipalName + '</td>';
                        tableContent += '<td>' + objItems[i].officeLocation + '</td>';
                        tableContent += '<td>' + objItems[i].mobilePhone + '</td>';
                        tableContent += '</tr></tbody>';
                    }
                    else {
                        tableContent += ' <tbody><tr class="alt">';
                        tableContent += '<td>' + objItems[i].displayName + '</td>';
                        tableContent += '<td>' + objItems[i].jobTitle + '</td>';
                        tableContent += '<td>' + objItems[i].userPrincipalName + '</td>';
                        tableContent += '<td>' + objItems[i].officeLocation + '</td>';
                        tableContent += '<td>' + objItems[i].mobilePhone + '</td>';
                        tableContent += '</tr></tbody>';
                    }
                }
                $('#userGrid').html(tableContent);
            }
            catch (e) {
                alert('An error has occurred: onSuccess ' + e.message)
                console.log('An error has occurred : onSuccess ' + e.message)
            }
        }

        function onError(error) {
            alert('Error in Getting Users : ' + error);
        }

        function filterChanged() {
            $("#filterText").val('');
        }

    </script>

    <div id="myProgress">
        <div id="myBar"></div>
    </div>

    <div id="CustomerPanel">
        <table>
            <tr>
                <td>Filter By:</td>
                <td>
                    <select id="filterBY" onchange="filterChanged()">
                        <option value="select">Select</option>
                        <option value="name">Name</option>
                        <option value="position">Position</option>
                        <option value="email">E-Mail</option>
                        <option value="office">Office</option>
                        <option value="phonenumber">Phone Number</option>
                    </select>
                </td>
                <td> <input id="filterText" type="text" name="filterText" onkeypress="handle(event)"><br></td>
                <td><button onclick="btnClicked(event)" onsubmit="btnClicked(event)" class="button4" id="btnSearch">Search</button></td>
            </tr>
        </table>
        <table style="width: 100%;">
            <tr>
                <td align="right">
                    <b> <label id="totalCount"></label></b>
                </td>
            </tr>
        </table>
        <table id='tableUsers' style="width: 100%;">
            <tr>
                <td>
                    <div id="userGrid" class="datagrid"></div>
                </td>
            </tr>
        </table>
    </div>
</body>
</html>

It will look like below Screenshot.

 User Details
User Details

Comments

Popular posts from this blog

Export SharePoint list current View on Button Click

Finding the Addition of Value from numbers of array