Export (0) Print
Expand All

Enumerating Contacts by Using a View

Ff751174.note(en-us,MSDN.10).gifNote:
Current information about Live Connect is now available in the Windows Live Developer Center. The information in the following sections is provided for legacy purposes only.

This topic demonstrates how to enumerate user contacts by using a view. A view enables client-side filtering and pagination so that users see only a subset of a large collection of items at any time.

The View type represents views. A view uses a window to display a subset of the actual item collection. You can move through the collection by using methods of the View type, such as nextPage or previousPage.

The following code example demonstrates how to define a view in the contactsLoaded handler, and how to set the page size of the view.

Ff751174.note(en-us,MSDN.10).gifNote:
The first code example uses a getNextPage event handler to handle the click events of a Next button.
var dataContext;
var contactsCollection;
var contactSelected;

function contactsLoaded(dataLoadCompletedEventArgs) {
    contactsCollection = dataLoadCompletedEventArgs.get_data();
    contactsView = contactsCollection.get_view();
    contactsView.set_pageSize(5);
}

function getNextPage() {
    contactsView.nextPage(function (evtArgs) {
        if (evtArgs.get_resultCode() !== Microsoft.Live.AsyncResultCode.success) {
            alert("No next page");
        }
        else {
            alert("Found next page");
        }
    });
}

To help users find contacts in a list quickly, you can create a filter. Building on the last example, the following code example demonstrates how to define a filter for a contact list by using the filter method of the View class.

var dataContext;
var contactsCollection;
var contactSelected;
// Method invoked by user action.
function searchData() {
    var searchData = $get("txtFilter").value.toLowerCase();
    getFilteredContacts(searchData, contactsView);
}

// Filter method
function getFilteredContacts(textForFilter, contactsViewToSearch) {
    var fixed_name = textForFilter;
    function simpleFilter(aContact) {
        // startsWith is a JavaScript Base Type Extension
        return aContact.get_formattedName().toString().toLowerCase().startsWith(textForFilter);
    }

    contactsViewToSearch.filter(simpleFilter, function () {
        createList(contactsViewToSearch);
    });
}

Ff751174.note(en-us,MSDN.10).gifNote:
Both code examples assume that you already have a data context and an in-memory contact collection. For more information about the contact resource, see Working with Contacts (JavaScript Library). For more information about the data context, see Using the Data Context.

Both of the following code samples create a complete Microsoft ASP.NET-based (.aspx) page that enumerates user contacts. To create and test each sample:

  1. Follow the instructions in Getting Started Sample for ASP.NET.
  2. Add a new ASP.NET page to the project that you created in Getting Started Sample for ASP.NET.
  3. Replace the <html> element in the new ASP.NET page with the code sample.
  4. Ensure that the Web.config file has the required keys in the <wl:app> tag.

The first sample shows how to move through the user's contact collection by using a view.

<%@ Import Namespace="System.Web.Configuration" %>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:wl="http://apis.live.net/js/2010">
<head runat="server">
    <title>Javascript API - Contact View</title>
    <script type="text/javascript" src="http://js.live.net/4.1/loader.js"></script>

    <script type="text/javascript">
        var dataContext;
        var contactsCollection;
        var contactSelected;
        var contactsView;

        function appLoaded(applicationLoadCompletedEventArgs) {
            Microsoft.Live.Core.Namespace.using("wl:Microsoft.Live");
            // Page refresh.
            if (wl.App.get_auth().get_state() === wl.AuthState.authenticated) {
                wl.App.get_dataContext().loadAll(Microsoft.Live.DataType.contacts, contactsLoaded);
            }
            $get('prevButton').disabled = true;
            $get('nextButton').disabled = true;
        }

        function signInCallback(signInCompletedEventArgs) {
            if (signInCompletedEventArgs.get_resultCode() !== Microsoft.Live.AsyncResultCode.success) {
                alert("sign-in failed: " + Microsoft.Live.AsyncResultCode.toString(signInCompletedEventArgs.get_resultCode()));
                return;
            }
            // Get datacontext and load contacts.
            dataContext = Microsoft.Live.App.get_dataContext();
            dataContext.loadAll(Microsoft.Live.DataType.contacts, contactsLoaded);
        }

        function signOutCallback() {
            $get('contactList').innerHTML = '';
            $get('prevButton').disabled = true;
            $get('nextButton').disabled = true;
            $get('txtBox1').value = "";
            $get('txtBox2').value = "";
            $get('txtBox3').value = "";
            $get('txtBox4').value = "";
        }

        function contactsLoaded(dataLoadCompletedEventArgs) {
            if (dataLoadCompletedEventArgs.get_resultCode() !== Microsoft.Live.AsyncResultCode.success) {
                alert("Contacts failed to load...!");
                return;
            }

            contactsCollection = dataLoadCompletedEventArgs.get_data();
            contactsView = contactsCollection.get_view();
            contactsView.set_pageSize(5);

            contactsView.hasNextPage(function (hasNext) {
                if (hasNext) {
                    $get('nextButton').disabled = false;
                    $get('prevButton').disabled = false;
                }
            });

            createList(contactsView);
        }

        // List just "view" of contacts.
        function createList(contactsView) {
            var list = $get('contactList');
            list.innerHTML = '';
            for (var i = 0; i < contactsView.get_pageSize(); i++) {
                if (contactsView.get_data()[i] !== undefined) {
                    var contact = contactsView.get_data()[i]
                    list.innerHTML += "<li><a href='#' onclick='displayContact(\"" + contact.get_id() + "\")'>" + contact.get_formattedName() + "</a></li>";
                }
            }
        }

        // For a contact selected in the dropdown, display its properties in the text boxes.
        function displayContact(id) {
            for (var i = 0; i < contactsView.get_pageSize(); i++) {
                var contact = contactsView.get_data()[i];
                if (contact !== undefined && contact.get_id() === id) {
                    contactSelected = contact;
                    $get('txtBox1').value = contactSelected.get_firstName();
                    $get('txtBox2').value = contactSelected.get_lastName();
                    $get('txtBox3').value = (contactSelected.get_cid() !== undefined) ? contactSelected.get_cid() : "";
                    $get('txtBox4').value = (contactSelected.get_isFriend() === true) ? "true" : "false";
                }
            }
        }
        function getPage(direction) {
            switch (direction) {
                case 'next':
                    contactsView.nextPage(function (evtArgs) {
                        if (evtArgs.get_resultCode() !== Microsoft.Live.AsyncResultCode.success) {
                            alert("No next page");
                        }
                        else {
                            alert("Found next page");
                            createList(contactsView);
                        }
                    });
                    break;
                case 'prev':
                    if (!contactsView.hasPreviousPage()) {
                        alert("No previous page.");
                    }
                    else {
                        alert("Found previous page");
                        contactsView.previousPage();
                        createList(contactsView);
                    }
                    break;
            }
        }
    </script>
    <style type="text/css">
    table { border-collapse: collapse;}
    table td{
    border: 1px solid blue;
    padding: 4px;}
    td.d span {
    display: inline-block;
    min-width: 120px;}
    ul { list-style-type: none;}
    </style>
</head>
<body>
    <div>
        <wl:app channel-url="<%=WebConfigurationManager.AppSettings["wl_wrap_channel_url"]%>"
            callback-url="<%=WebConfigurationManager.AppSettings["wl_wrap_client_callback"]%>?<%=SessionId%>"
            client-id="<%=WebConfigurationManager.AppSettings["wl_wrap_client_id"]%>" scope="WL_Contacts.View"
            onload="appLoaded">
        </wl:app>
        <h1>
           Listing Contact with a View</h1>
        <wl:signin onsignin="{{signInCallback}}" onsignout="{{signOutCallback}}"/>
        <br />
        <hr />
        <table >
            <tr>
                <td>
                    <wl:userinfo/>
                    <br /><br /><br />
                    <ul id="contactList"></ul>
                    <input id="prevButton" type="button" onclick="getPage('prev')" value="Prev Page"/>
                    <input id="nextButton" type="button" onclick="getPage('next')" value="Next Page"/>

                </td>
                <td class="d">
                    <span>FirstName: </span>
                    <input type="text" id="txtBox1" /><br />
                    <span >LastName: </span>
                    <input type="text" id="txtBox2" /><br />
                    <span>CID: </span>
                    <input type="text" disabled="disabled" id="txtBox3"/><br />
                    <span>IsFriend?:</span>
                    <input type="text" id="txtBox4" />
                </td>
            </tr>
        </table>
    </div>
</body>
</html>

The second sample demonstrates how to filter a contact list to limit the number of contacts displayed.

<%@ Import Namespace="System.Web.Configuration" %>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:wl="http://apis.live.net/js/2010">
<head runat="server">
    <title>Javascript API - Contact View With Filter</title>
    <script type="text/javascript" src="http://js.live.net/4.1/loader.js"></script>

    <script type="text/javascript">
        var dataContext;
        var contactsCollection;
        var contactSelected;
        var contactsView;

        function appLoaded(applicationLoadCompletedEventArgs) {
            Microsoft.Live.Core.Namespace.using("wl:Microsoft.Live");
            // Page refresh.
            if (wl.App.get_auth().get_state() === wl.AuthState.authenticated) {
                wl.App.get_dataContext().loadAll(Microsoft.Live.DataType.contacts, contactsLoaded);
            }
            $get('prevButton').disabled = true;
            $get('nextButton').disabled = true;
        }

        function signInCallback(signInCompletedEventArgs) {
            if (signInCompletedEventArgs.get_resultCode() !== Microsoft.Live.AsyncResultCode.success) {
                alert("sign-in failed: " + Microsoft.Live.AsyncResultCode.toString(signInCompletedEventArgs.get_resultCode()));
                return;
            }
            // Get datacontext and load contacts.
            dataContext = Microsoft.Live.App.get_dataContext();
            dataContext.loadAll(Microsoft.Live.DataType.contacts, contactsLoaded);
        }

        function signOutCallback() {
            $get('contactList').innerHTML = '';
            $get('prevButton').disabled = true;
            $get('nextButton').disabled = true;
            $get('txtBox1').value = "";
            $get('txtBox2').value = "";
            $get('txtBox3').value = "";
            $get('txtBox4').value = "";
        }

        function contactsLoaded(dataLoadCompletedEventArgs) {
            if (dataLoadCompletedEventArgs.get_resultCode() !== Microsoft.Live.AsyncResultCode.success) {
                alert("Contacts failed to load...!");
                return;
            }

            contactsCollection = dataLoadCompletedEventArgs.get_data();
            contactsView = contactsCollection.get_view();
            contactsView.set_pageSize(5);

            contactsView.hasNextPage(function (hasNext) {
                if (hasNext) {
                    $get('nextButton').disabled = false;
                    $get('prevButton').disabled = false;
                }
            });

            createList(contactsView);
        }

        // List just "view" of contacts.
        function createList(contactsView) {
            var list = $get('contactList');
            list.innerHTML = '';
            for (var i = 0; i < contactsView.get_pageSize(); i++) {
                if (contactsView.get_data()[i] !== undefined) {
                    var contact = contactsView.get_data()[i]
                    list.innerHTML += "<li><a href='#' onclick='displayContact(\"" + contact.get_id() + "\")'>" + contact.get_formattedName() + "</a></li>";
                }
            }
        }

        // For a contact selected in the dropdown, display its properties in the text boxes.
        function displayContact(id) {
            for (var i = 0; i < contactsView.get_pageSize(); i++) {
                var contact = contactsView.get_data()[i];
                if (contact !== undefined && contact.get_id() === id) {
                    contactSelected = contact;
                    $get('txtBox1').value = contactSelected.get_firstName();
                    $get('txtBox2').value = contactSelected.get_lastName();
                    $get('txtBox3').value = (contactSelected.get_cid() !== undefined) ? contactSelected.get_cid() : "";
                    $get('txtBox4').value = (contactSelected.get_isFriend() === true) ? "true" : "false";
                }
            }
        }
        function getPage(direction) {
            switch (direction) {
                case 'next':
                    contactsView.nextPage(function (evtArgs) {
                        if (evtArgs.get_resultCode() !== Microsoft.Live.AsyncResultCode.success) {
                            alert("No next page");
                        }
                        else {
                            alert("Found next page");
                            createList(contactsView);
                        }
                    });
                    break;
                case 'prev':
                    if (!contactsView.hasPreviousPage()) {
                        alert("No previous page.");
                    }
                    else {
                        alert("Found previous page");
                        contactsView.previousPage();
                        createList(contactsView);
                    }
                    break;
            }
        }
        function filterData() {
            var filterData = $get("txtFilter").value.toLowerCase();
            getFilteredContacts(filterData, contactsView);
        }

        // Filter method.
        function getFilteredContacts(textForFilter, contactsViewToSearch) {
            var fixed_name = textForFilter;
            function simpleFilter(aContact) {
                // startsWith is a JavaScript Base Type Extension
                return aContact.get_formattedName().toString().toLowerCase().startsWith(textForFilter);
            }

            contactsViewToSearch.filter(simpleFilter, function () {
                createList(contactsViewToSearch);
            });
        }

    </script>
    <style type="text/css">
    table { border-collapse: collapse;}
    table td{
    border: 1px solid blue;
    padding: 4px;}
    td.d span {
    display: inline-block;
    min-width: 120px;}
    ul { list-style-type: none;}
    </style>
</head>
<body>
    <div>
        <wl:app channel-url="<%=WebConfigurationManager.AppSettings["wl_wrap_channel_url"]%>"
            callback-url="<%=WebConfigurationManager.AppSettings["wl_wrap_client_callback"]%>?<%=SessionId%>"
            client-id="<%=WebConfigurationManager.AppSettings["wl_wrap_client_id"]%>" scope="WL_Contacts.View"
            onload="appLoaded">
        </wl:app>
        <h1>
           Listing Contact with a View</h1>
        <wl:signin onsignin="{{signInCallback}}" onsignout="{{signOutCallback}}"/>
        <input type="text" id="txtFilter" /> <input type="button" value="Apply Filter" onclick="filterData()" />
        <br />
        <hr />
        <table >
            <tr>
                <td>
                    <wl:userinfo/>
                    <br /><br /><br />
                    <ul id="contactList"></ul>
                    <input id="prevButton" type="button" onclick="getPage('prev')" value="Prev Page"/>
                    <input id="nextButton" type="button" onclick="getPage('next')" value="Next Page"/>

                </td>
                <td class="d">
                    <span>FirstName: </span>
                    <input type="text" id="txtBox1" /><br />
                    <span >LastName: </span>
                    <input type="text" id="txtBox2" /><br />
                    <span>CID: </span>
                    <input type="text" disabled="disabled" id="txtBox3"/><br />
                    <span>IsFriend?:</span>
                    <input type="text" id="txtBox4" />
                </td>
            </tr>
        </table>
    </div>
</body>
</html>

Show:
© 2014 Microsoft