IT tutorials
 
Technology
 

Sharepoint 2013 : Overview of The Client-Side Object Model and Rest APIs - JAVASCRIPT (part 3) - Using the JavaScript Client-Side Object Model in a SharePoint-Hosted App Using Napa for Office 365

4/25/2014 3:41:56 AM
- Free product key for windows 10
- Free Product Key for Microsoft office 365
- Malwarebytes Premium 3.7.1 Serial Keys (LifeTime) 2019
Using the JavaScript Client-Side Object Model in a SharePoint-Hosted App Using Napa for Office 365

In this exercise you create a SharePoint application using only JavaScript and the Napa Office 365 development tools. You must have the Napa application installed from the Office 365 marketplace prior to starting this exercise. The full JavaScript source for this exercise is available in the code download in the JavaScriptCSOMApp.js file.

1. Ensure you have Napa Office 365 Development Tools installed in your development site in Office 365.

2. Click Site Contents in your site navigation to see a list of all apps installed in your site.

3. Locate Napa Office 365 Development Tools in the list and click it as shown in Figure 1.

FIGURE 1

image

4. Click Add New Project.

5. Select App for SharePoint and enter MyFirstJavaScriptApp in the Project name box. Click Create to continue. Napa creates a set of template files and folders for you. Explore the structure and get familiar with the layout of the application.

6. Open the Scripts folder and then open the App.js file. This is the default file that contains the JavaScript for your application.

7. At the bottom of the file add the following code:
function getParameterByName(name)
{
name = name.replace(/[[]/, "\[").replace(/[]]/, "\]");
var regexS = "[\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/+/g, " "));
}
8. Replace the sharePointReady() function with the following code. This gets the host URL for use later.
var hostUrl;

function sharePointReady() {
context = new SP.ClientContext.get_current();
web = context.get_web();
hostUrl = getParameterByName('SPHostUrl');
createList();
}
9. Directly after the sharePointReady() function insert the following code. This creates a new list.
var newList;

function createList() {
var hostContext = new SP.AppContextSite(context, hostUrl);
web = hostContext.get_web();

var newListInfo = new SP.ListCreationInformation();
newListInfo.set_title('My Sample List');
newListInfo.set_templateType(SP.ListTemplateType.genericList);

newList = web.get_lists().add(newListInfo);

context.load(newList);
context.executeQueryAsync(onCreateListSucceeded, onFailed);
}

function onCreateListSucceeded() {
alert('New list created: ' + newList.get_title());
}

// This function is executed if the above call fails
function onFailed(sender, args) {
alert('Failed. Error:' + args.get_message());
}
10. Click the Run Project button in the bottom left of the window to test out the application. When it completes, a message appears like the one shown in Figure 2.

FIGURE 2

image

11. Right-click the launch link and open your app in a new window to start your application.

12. A JavaScript alert message appears, stating, “Failed. Error: Access denied. You do not have permission to perform this action or access this resource.” This is supposed to happen. The reason is that you have not yet given your application permissions to create lists in the app’s host Web. Click OK to continue then close the window. Click Close in the Launch App dialog in Napa to get back to your code.

13. In the lower left of the window click the wrench icon to open the Property panel for your application, as shown in Figure 3.

FIGURE 3

image

14. Click into the Permissions tab and set the permissions for Web under Content to Full Control.

15. Run the project again using the Run Project button in the bottom left of the window. A permissions request window appears, asking you to grant the application full control of the site. Click Trust It.

16. An alert window appears, stating, “New list created: My Sample List.” Click OK.

17. Check that your list was created by clicking the link in the top left of the page to get to your developer site. Click Site Content and find the new list called My Sample List. Click it to open the list. Currently, no data is in it.

18. Within the sharePointReady function, change the createList(); call to createItems();.

19. After the sharePointReady function, add the following code:
function createItems()
{
var listContext = new SP.AppContextSite(context, hostUrl);
var list = listContext.get_web().get_lists().getByTitle('My Sample List');

for(var i=0; i < 10; i++)
{
var itemCreateInfo = new SP.ListItemCreationInformation();
var newListItem = list.addItem(itemCreateInfo);
newListItem.set_item('Title', 'Created via JS CSOM! - ' + i);
newListItem.update();
context.load(newListItem);
}
context.executeQueryAsync(onCreateListItemsSuccess,onFailed);
}

function onCreateListItemsSuccess() {
alert('New ListItems created');
}
20. Run and launch the app again using the Run Project button in the bottom left of the window. This time an alert appears stating, “New ListItems created.

21. Check the list in the SharePoint site to ensure the data has been created. You should see ten new items created in the list.

22. Within the sharePointReady function, change the createItems(); call to updateListItem();.

23. Directly after the sharePointReady function, insert the following code:
var updatedItem;

function updateListItem() {
var listContext = new SP.AppContextSite(context, hostUrl);
var list = listContext.get_web().get_lists().getByTitle('My Sample List');

var listItem = list.getItemById(1);
listItem.set_item('Title', 'Updated via JS CSOM');
listItem.update();

context.load(listItem);
context.executeQueryAsync(onUpdateItemSucceeded, onFailed);
}

function onUpdateItemSucceeded() {
alert('Updated item!');
}
24. Run and launch the app again. This time an alert appears stating, “Updated item!”. Again, check the SharePoint list to see that the first item in the list has been updated.

25. Within the sharePointReady function, change the updateListItem(); call to getItems();.

26. Directly after the sharePointReady function, insert the following code:
var items;

function getItems()
{
var listContext = new SP.AppContextSite(context, hostUrl);
var list = listContext.get_web().get_lists().getByTitle('My Sample List');

var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(
'<View><Query><Where><Eq><FieldRef Name=\'Title\'/>' +
'<Value Type=\'Text\'>Updated via JS CSOM</Value></Eq></Where></Query>' +
'<RowLimit>10</RowLimit></View>'
);
items = list.getItems(camlQuery);
context.load(items);
context.executeQueryAsync(onGetListItemsSuccess,onFailed);
}

function onGetListItemsSuccess() {
var listItemEnumerator = items.getEnumerator();

while (listItemEnumerator.moveNext()) {
var item = listItemEnumerator.get_current();
alert(item.get_item('Title'));
}
}
27. Run and launch the app again. An alert appears stating, “Updated via JS CSOM” indicating that the app was able to query the list for the item it previously updated.

How It Works
In this exercise you created a SharePoint-hosted app using the new Napa tools available in Office 365. These tools allow for lightweight application development within a browser environment without requiring any client-side installation. The app used the JavaScript CSOM and then created a new list using the SP.AppContextSite method to call into the host Web and create and manipulate data. This call is necessary to ensure SharePoint brokers the calls to the host Web. If you attempted to make the calls directly to the host Web the browser would stop you due to cross-site scripting security requirements because the two sites are on a different domain.
The app first created a brand-new list based on the generic list type (the same as creating a custom list via the Web UI) and then inserted 10 new list items into it. Finally, the app updated one of those list items and then queried the list for that newly updated item. The JS CSOM wraps the underlying API calls to SharePoint for you and provides convenient wrapper objects and methods.
When you ran the application Napa packaged the application into an application package (.app file) and then deployed and installed it in SharePoint for you.

Security and Cross-Domain Calls

JavaScript engines in modern browsers include security mechanisms that do not allow JavaScript to make calls across domains. This means that scripts can only get data from the domain where they were served. For example, if your page is served from http://www.myserver.com then JavaScript will not be allowed to make calls to http://www.someotherserver.com. This is to stop cross-site scripting attacks (XSS). Because of this limitation SharePoint also provides some mechanisms that let your SharePoint JS calls get at information in other domains including:

  • SP.AppContextSite
  • Web proxy

The SP.AppContextSite helper allows you to set up the CSOM ClientContext to make calls to other SharePoint sites. This site could be the host website or another site collection or server entirely. This helper proxies the calls you make via the SharePoint site on the domain where your JavaScript was served, thus getting around the cross-site scripting issues. You must use this technique if you are using Office 365 and your app is hosted on another domain, or if you are using app isolation for application deployment on premises. The latter option creates a subdomain just for your application. Your script will, therefore, need to call out beyond its own domain, and AppContextSite helps with that.

Additionally, you can use the Web proxy SharePoint to call other non-SharePoint endpoints. To use it you must create an SP.WebRequestInfo object and set up the URL and method for the call you want to make as follows:

var context = SP.ClientContext.get_current();

var crossDomainRequest = new SP.WebRequestInfo();

crossDomainRequest.set_url("http://looselytyped.net/feed/");
crossDomainRequest.set_method("GET");

var response = SP.WebProxy.invoke(context, crossDomainRequest);

This code proxies the call to the remote endpoint via SharePoint and returns the results. You can use this technique to call out to any HTTP/HTTPS-enabled endpoint; however, always remember the call goes through SharePoint and is therefore open to being viewed by someone with access to that server/service. HTTPS will not help because the call to SharePoint will be terminated and decrypted on the SharePoint Server prior to the request being made to the destination endpoint. However, this feature allows developers to get around many of the intricacies of cross-site scripting that are otherwise too complex to solve.

 
Others
 
- Sharepoint 2013 : Overview of The Client-Side Object Model and Rest APIs - JAVASCRIPT (part 2) - Querying
- Sharepoint 2013 : Overview of The Client-Side Object Model and Rest APIs - JAVASCRIPT (part 1) - Setup
- Active Directory 2008 Optimization and Reliability : Monitoring and Troubleshooting Active Directory Components (part 4) - The Event Viewer
- Active Directory 2008 Optimization and Reliability : Monitoring and Troubleshooting Active Directory Components (part 3) - The Network Monitor, The Task Manager
- Active Directory 2008 Optimization and Reliability : Monitoring and Troubleshooting Active Directory Components (part 2) - Monitoring Active Directory Performance with Performance Monitor
- Active Directory 2008 Optimization and Reliability : Monitoring and Troubleshooting Active Directory Components (part 1) - Monitoring Domain Controller Performance
- Sharepoint 2013 : Overview of The Client-Side Object Model and Rest APIs - MANAGED CODE (.NET)
- Sharepoint 2013 : Overview of The Client-Side Object Model and Rest APIs - CLIENT-SIDE OBJECT MODEL (CSOM) BASICS
- Windows Server 2012 : Managing virtual machines (part 5) - Monitoring virtual machines
- Windows Server 2012 : Managing virtual machines (part 4) - Managing snapshots
 
 
Top 10
 
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 2) - Wireframes,Legends
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Finding containers and lists in Visio (part 1) - Swimlanes
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Formatting and sizing lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Adding shapes to lists
- Microsoft Visio 2013 : Adding Structure to Your Diagrams - Sizing containers
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 3) - The Other Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 2) - The Data Properties of a Control
- Microsoft Access 2010 : Control Properties and Why to Use Them (part 1) - The Format Properties of a Control
- Microsoft Access 2010 : Form Properties and Why Should You Use Them - Working with the Properties Window
- Microsoft Visio 2013 : Using the Organization Chart Wizard with new data
Technology FAQ
- Is possible to just to use a wireless router to extend wireless access to wireless access points?
- Ruby - Insert Struct to MySql
- how to find my Symantec pcAnywhere serial number
- About direct X / Open GL issue
- How to determine eclipse version?
- What SAN cert Exchange 2010 for UM, OA?
- How do I populate a SQL Express table from Excel file?
- code for express check out with Paypal.
- Problem with Templated User Control
- ShellExecute SW_HIDE
programming4us programming4us