Welcome!

XML Authors: Stefan Bernbo, Carmen Gonzalez, David Dossot, Yeshim Deniz, Elizabeth White

Blog Feed Post

How to: Query List Items from the Host Web in a Client Web Part of a SharePoint Hosted app

That’s a mouthful, but I wanted to make sure that people knew exactly what this post is for.  The problem I am seeing out there already is that while there is a lot of code samples, they aren’t clear for what type of app the sample is for.  If you are doing a provider hosted app for example, the way you query list items is different (using the Cross-Domain Library).  Today’s topic boggled me though because while I found plenty of samples on how to query list items using CSOM from an app, they were all in-fact incorrect for a SharePoint hosted app.  The article I linked is great by the way.  It has many of the things you need to know how to do via CSOM in an app so be sure and check it out.

Now to get on to the scenario I want to help you with today.  If you are building a Client Web Part, you may have stumbled upon my previous articles on the topic (JavaScript and Getting Started).  These are great articles to get you started, however, it turns out I left out the details on how to query list items from a SharePoint hosted app.  Like many things, it’s not as simple as I thought it was.  I thought it was just a matter of passing another URL into get_web().  I was wrong.  I then saw some examples and thought I just need to pass the URL into a new SPContext object.  Also wrong.  While, you can do that, once you make the call to get your list items, you’ll quickly find yourself with an Access Denied error coming from MicrosoftAjax.js.  I gave up and posted something to the forums and luckily Elisabeth Olson from MSFT came through with the answer.  In my solution, I start with some global variable declarations.

var context;

var web;

var user;

var spHostUrl;

var parentContext

Then the code looks similar to that from my article on SP.js.  In the document ready function, I get the spHostUrl with the following line of code.  You can get that getQueryStringParameter method from my previous article as well.  Remember, the SPHostUrl comes from the {StandardTokens} parameter in your Client Web Part’s elements.xml file.

spHostUrl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));

Now, we set up our context and here is where things are a bit different.  First, we get our context object using SP.ClientContext.get_current() as usual.  However, we have to get a new context by using SP.AppContextSite and passing in the current context along with the Host Url.

context = new SP.ClientContext.get_current();

parentContext = new SP.AppContextSite(context, spHostUrl);

After that, we just need to get our SPWeb object using the parentContext.

web = parentContext.get_web();

At this point, it’s business as usual to do our queries.  Get the list, set a CAML query, load the getItems call, and then execute the query.

var list = web.get_lists().getByTitle("My List"));

 

var camlQuery = new SP.CamlQuery();

camlQuery.set_viewXml("");

 

this.listItems = list.getItems(camlQuery);

context.load(listItems);

 

context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),

    Function.createDelegate(this, this.onQueryFailed));

My success and failure functions are pretty standard in this case.  I just manually iterate through the results and return the Title and Id.  Otherwise, I display the reason for failure.

function onQuerySucceeded() {

    $("#results").empty();

    var listInfo = '';

    var listEnumerator = listItems.getEnumerator();

 

    listInfo += "<table><tr><th>Id</th><th>Title</th></tr>";

 

    while (listEnumerator.moveNext()) {

        var listItem = listEnumerator.get_current();

        listInfo += '<tr><td>' + listItem.get_item('ID') + '</td>'

            + '<td>' + listItem.get_item('Title') + '</td>'

            + '</tr>\n';

    }

 

    listInfo += '</table>';

 

    $("#results").html(listInfo);

}

 

function onQueryFailed(sender, args) {

    $("#results").empty();

    $("#results").text('Request failed. ' + args.get_message() +

        '\n' + args.get_stackTrace());

}

This threw me for a loop for a while, so hopefully this post helps you get started quicker when you build your app.

Follow me on twitter, @coreyroth, if you have any questions and come see me at SPC if you are going.

Read the original blog entry...

More Stories By Corey Roth

Corey Roth, a SharePoint Server MVP, is a consultant at Hitachi Consulting specializing in SharePoint and Office 365 for clients in the energy sector. He has more than ten years of experience delivering solutions in the energy, travel, advertising and consumer electronics verticals.

Corey specializes in delivering ECM and search solutions to clients using SharePoint. Corey has always focused on rapid adoption of new Microsoft technologies including Visual Studio 2013, Office 365, and SharePoint.

He is a member of the .NET Mafia (www.dotnetmafia.com) where he blogs about the latest technology and SharePoint. He is dedicated to the community and speaks regularly at user groups and SharePoint Saturdays.

@ThingsExpo Stories
Technology is enabling a new approach to collecting and using data. This approach, commonly referred to as the "Internet of Things" (IoT), enables businesses to use real-time data from all sorts of things including machines, devices and sensors to make better decisions, improve customer service, and lower the risk in the creation of new revenue opportunities. In his General Session at Internet of @ThingsExpo, Dave Wagstaff, Vice President and Chief Architect at BSQUARE Corporation, discuss the real benefits to focus on, how to understand the requirements of a successful solution, the flow of ...
"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

Focused on this fast-growing market’s needs, Vitesse Semiconductor Corporation (Nasdaq: VTSS), a leading provider of IC solutions to advance "Ethernet Everywhere" in Carrier, Enterprise and Internet of Things (IoT) networks, introduced its IStaX™ software (VSC6815SDK), a robust protocol stack to simplify deployment and management of Industrial-IoT network applications such as Industrial Ethernet switching, surveillance, video distribution, LCD signage, intelligent sensors, and metering equipment. Leveraging technologies proven in the Carrier and Enterprise markets, IStaX is designed to work ac...
"There is a natural synchronization between the business models, the IoT is there to support ,” explained Brendan O'Brien, Co-founder and Chief Architect of Aria Systems, in this SYS-CON.tv interview at the 15th International Cloud Expo®, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
C-Labs LLC, a leading provider of remote and mobile access for the Internet of Things (IoT), announced the appointment of John Traynor to the position of chief operating officer. Previously a strategic advisor to the firm, Mr. Traynor will now oversee sales, marketing, finance, and operations. Mr. Traynor is based out of the C-Labs office in Redmond, Washington. He reports to Chris Muench, Chief Executive Officer. Mr. Traynor brings valuable business leadership and technology industry expertise to C-Labs. With over 30 years' experience in the high-tech sector, John Traynor has held numerous...
Bit6 today issued a challenge to the technology community implementing Web Real Time Communication (WebRTC). To leap beyond WebRTC’s significant limitations and fully leverage its underlying value to accelerate innovation, application developers need to consider the entire communications ecosystem.
The 3rd International @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The Internet of Things (IoT) is the most profound change in personal and enterprise IT since the creation of the Worldwide Web more than 20 years ago. All major researchers estimate there will be tens of billions devices - computers, smartphones, tablets, and sensors - connected to the Internet by 2020. This number will continue to grow at a rapid pace for the next several decades.
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...
Almost everyone sees the potential of Internet of Things but how can businesses truly unlock that potential. The key will be in the ability to discover business insight in the midst of an ocean of Big Data generated from billions of embedded devices via Systems of Discover. Businesses will also need to ensure that they can sustain that insight by leveraging the cloud for global reach, scale and elasticity.
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
IoT is still a vague buzzword for many people. In his session at @ThingsExpo, Mike Kavis, Vice President & Principal Cloud Architect at Cloud Technology Partners, discussed the business value of IoT that goes far beyond the general public's perception that IoT is all about wearables and home consumer services. He also discussed how IoT is perceived by investors and how venture capitalist access this space. Other topics discussed were barriers to success, what is new, what is old, and what the future may hold. Mike Kavis is Vice President & Principal Cloud Architect at Cloud Technology Pa...
Cloud Expo 2014 TV commercials will feature @ThingsExpo, which was launched in June, 2014 at New York City's Javits Center as the largest 'Internet of Things' event in the world. The next @ThingsExpo will take place November 4-6, 2014, at the Santa Clara Convention Center, in Santa Clara, California. Since its launch in 2008, Cloud Expo TV commercials have been aired and CNBC, Fox News Network, and Bloomberg TV. Please enjoy our 2014 commercial.
From a software development perspective IoT is about programming "things," about connecting them with each other or integrating them with existing applications. In his session at @ThingsExpo, Yakov Fain, co-founder of Farata Systems and SuranceBay, will show you how small IoT-enabled devices from multiple manufacturers can be integrated into the workflow of an enterprise application. This is a practical demo of building a framework and components in HTML/Java/Mobile technologies to serve as a platform that can integrate new devices as they become available on the market.
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
Located in booth #314, the Bsquare team will present DataV demos and discuss how DataV will help customers put their data to work to improve business outcomes. DataV is unlocking new initiatives across a wide landscape of customers in industries such as industrial manufacturing, transportation, retail and mobile. The solution is designed to complement a new project start or help to enrich an existing machine investment.
The Physical Web incorporates beacons that can be put in any small retail store, for example, so that every store now has "an app" for its customers. In this Birds-of-a-Feather session at Internet of @ThingsExpo, Scott Jenson, Product Designer at Google, will discuss the Physical Web and how it is an open standard so any device can broadcast a URL wirelessly, so any phone/tablet/watch nearby can see, and rank those devices. When the user taps on one, they just go to that web page. It's really that simple. It's about thinking small, enabling micro-information (what is in my prescription bottle...
BSQUARE is a global leader of embedded software solutions. We enable smart connected systems at the device level and beyond that millions use every day and provide actionable data solutions for the growing Internet of Things (IoT) market. We empower our world-class customers with our products, services and solutions to achieve innovation and success. For more information, visit www.bsquare.com.