Thursday, October 15, 2015

Creating, reading, updating, and deleting in the JavaScript client object model

Creating, reading, updating, and deleting in the JavaScript client object model


Creating, reading, updating, and deleting list items by using the JavaScript client object model is more complex than with the managed client object model. The additional complexity comes from not only the asynchronous calls, but also the need to properly encapsulate the JavaScript so that it’s separated from the global namespace. Example 12 shows the basic structure of a JavaScript library used to perform create, read, update, and delete (CRUD) operations on a contacts list contained in a SharePoint-hosted app.
Example 12. CSOM library structure
"use strict";

var Wingtip = window.Wingtip || {};
Wingtip.Contacts;
Wingtip.ContactList = function () {

    //private members
    createItem = function (lname, fname, wphone) {
    },
    readAll = function () {
    },
    readAllSuccess = function () {
    },
    updateItem = function (id, lname, fname, wphone) {
    },
    removeItem = function (id) {
    },
    success = function () {
        readAll();
    },
    error = function (sender, args) {
        alert(args.get_message());
    }

    //public interface
    return {
        createContact: createItem,
        updateContact: updateItem,
        deleteContact: removeItem
    }

}();

$(document).ready(function () {
    Wingtip.ContactList.createContact("Cox", "Brian", "555-555-5555");
    alert("Contact Created!");
    Wingtip.ContactList.updateContact(1, "Cox", "Brian", "111-111-1111");
    alert("Contact Updated!");
    Wingtip.ContactList.deleteContact(1);
    alert("Contact Deleted!");
});
Before examining the implementation details for the CRUD operations, take some time to study the structure of the library. Example 12 contains the definition of a namespace object and a self-invoking function. In this case, however, a new property named Wingtip.Contacts is also defined. This property is used to hold a reference to the list items between asynchronous calls to the SharePoint server. Within the self-invoking function, all of the CRUD operations are defined, but only the create, update, and delete functions are revealed through the public interface of the library. These functions are called from some example code contained in the ready event handler.
Creating new contacts is done in the createItem function. This function uses the SP.ListItemCreationInformation object to define a new list item. The first name, last name, and phone number are set on the new item, and it is added to the list. Note that in a contacts list, the “Title” field is actually the last name of the contact. Example 13 presents the code for adding a new item.
Example 13. Creating new items
createItem = function (lname, fname, wphone) {
    var ctx = new SP.ClientContext.get_current();
    var list = ctx.get_web().get_lists().getByTitle("Contacts");
    ctx.load(list);
    var listItemCreationInfo = new SP.ListItemCreationInformation();
    var newContact = list.addItem(listItemCreationInfo);
    newContact.set_item("Title", lname);
    newContact.set_item("FirstName", fname);
    newContact.set_item("WorkPhone", wphone);
    newContact.update();
    ctx.executeQueryAsync(success, error);
}
After each create, update, or delete operation, the list is read and redrawn. The readAll function reads every item in the list by using a CAML query and then creates an HTML table to hold the contacts. The HTML is rendered in a <div> via jQuery. Example 14 demonstrates how the list is read and drawn. Note the use of the Wingtip.Contacts property to reference the list data between asynchronous calls to the server.
Example 14. Rendering the list items
readAll = function () {
    var ctx = new SP.ClientContext.get_current();
    var query = "<View><Query><OrderBy><FieldRef Name='Title'/>" +
                "<FieldRef Name='FirstName'/></OrderBy></Query>" +
                "<ViewFields><FieldRef Name='ID'/><FieldRef Name='Title'/>" +
                "<FieldRef Name='FirstName'/><FieldRef Name='WorkPhone'/>
                   </ViewFields></View>";
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml(query);
    var list = ctx.get_web().get_lists().getByTitle("Contacts");
    ctx.load(list);
    Wingtip.Contacts = list.getItems(camlQuery);
    ctx.load(Wingtip.Contacts, 'Include(ID,Title,FirstName,WorkPhone)');
    ctx.executeQueryAsync(readAllSuccess, error);
},

readAllSuccess = function () {
    var html = [];
    html.push("<table><thead><tr><th>ID</th><th>First Name</th>");
    html.push("<th>Last Name</th><th>Title</th></tr></thead>");

    var listItemEnumerator = Wingtip.Contacts.getEnumerator();

    while (listItemEnumerator.moveNext()) {
        var listItem = listItemEnumerator.get_current();
        html.push("<tr><td>");
        html.push(listItem.get_item("ID"));
        html.push("</td><td>");
        html.push(listItem.get_item("FirstName"));
        html.push("</td><td>");
        html.push(listItem.get_item("Title"));
        html.push("</td><td>");
        html.push(listItem.get_item("WorkPhone"));
        html.push("</td><td>");
    }

    html.push("</table>");
    $('#displayDiv').html(html.join(''));
}
Updating list items is accomplished by using the updateItem function. This function retrieves the item to be updated by its ID in the list. The new values for the fields are applied to the list item and it is updated. After the roundtrip to the server, the table is redrawn with the new values for the list item visible. Example 15 shows the code for updating items.
Example 15. Updating list items
updateItem = function (id, lname, fname, wphone) {
    var ctx = new SP.ClientContext.get_current();
    var list = ctx.get_web().get_lists().getByTitle("Contacts");
    ctx.load(list);
    var listItem = list.getItemById(id);
    listItem.set_item("Title", lname);
    listItem.set_item("FirstName", fname);
    listItem.set_item("WorkPhone", wphone);
    listItem.update();
    ctx.executeQueryAsync(success, error);
}
Deleting list items is done by using the removeItem function. The function retrieves the item to delete by its ID. The DeleteObject method is then called to remove the designated item from the list. After the item is removed asynchronously, the table is redrawn with the remaining list items. Example 16 presents the code for deleting items.
Example 16. Deleting list items
removeItem = function (id) {
    var ctx = new SP.ClientContext.get_current();
    var list = ctx.get_web().get_lists().getByTitle("Contacts");
    ctx.load(list);
    var listItem = list.getItemById(id);
    listItem.deleteObject();
    ctx.executeQueryAsync(success, error);
}

Read more at http://tutorial.wmlcloud.com/windows_server/Sharepoint-2013---Working-with-the-CSOM-(part-6)---Working-with-the-JavaScript-client-object-model---Creating,-reading,-updating,-and-deleting-in-the-JavaScript-client-object-model.aspx#jHAreGQyxGCDMTb1.99

SharePoint 2013 website tasks

SharePoint 2013 website tasks

These examples show how to use the .NET Framework CSOM to complete website-related tasks.

Retrieve the properties of a website

Retrieve the title of a SharePoint website.
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

// We want to retrieve the web's properties.
context.Load(web); 

// Execute the query to the server.
context.ExecuteQuery(); 

// Now, the web's properties are available and we could display 
// web properties, such as title. 
label1.Text = web.Title;

Retrieve only selected properties of a website

Sometimes, the client is interested only in a few properties of an object. The SharePoint .NET Framework CSOM does not require you to get all properties from the object on a server—you can use anonymous methods, which can be lambda expressions, to specifically request property names. The client library will query only for those properties on the server, and the server will send only those properties to the client. This technique reduces unnecessary data transfer between the client and the server. It is also useful when the user does not have permission to one or more of the other, unused properties on an object. Note that you will need to add a using statement for System.Linq.
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

// We want to retrieve the web's title and description. 
context.Load(web, w => w.Title, w => w.Description); 

// Execute the query to server.
context.ExecuteQuery(); 

// Now, only the web's title and description are available. If you 
// try to print out other properties, the code will throw 
// an exception because other properties are not available. 
label1.Text = web.Title;
label1.Text = web. Description;

Note
If you try to access other properties, the code throws an exception because other properties are not available.

Write to website's properties

This example shows how to write to the website's properties.
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// The SharePoint web at the URL.
Web web = context.Web; 

web.Title = "New Title"; 
web.Description = "New Description"; 

// Note that the web.Update() does not trigger a request to the server
// because the client library until ExecuteQuery() is called. 
web.Update(); 

// Execute the query to server.
context.ExecuteQuery(); 

Create a new SharePoint website

This example shows how to create a new SharePoint site as a subsite of the current website. Use the WebCreationInformation class to create a new website. You will also need to add using statements for System.Collections.Generic and System.Text.
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

WebCreationInformation creation = new WebCreationInformation(); 
creation.Url = "web1"; 
creation.Title = "Hello web1"; 
Web newWeb = context.Web.Webs.Add(creation); 

// Retrieve the new web information. 
context.Load(newWeb, w => w.Title); 
context.ExecuteQuery(); 

label1.Text = newWeb.Title; 

SharePoint 2013 list item tasks


SharePoint 2013 list item tasks - CSOM operations

These examples demonstrate how to use the .NET Framework CSOM to complete tasks that are related to list items.

Retrieve items from a SharePoint list

This example retrieves the items in a SharePoint list. You will also need to add a using statement for Microsoft.SharePoint.Client.QueryExpression.
Note
You can use the FolderServerRelativeUrl property to further restrict the items that are returned to those in a specified folder.
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// Assume the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// This creates a CamlQuery that has a RowLimit of 100, and also specifies Scope="RecursiveAll" 
// so that it grabs all list items, regardless of the folder they are in. 
CamlQuery query = CamlQuery.CreateAllItemsQuery(100); 
ListItemCollection items = announcementsList.GetItems(query); 

// Retrieve all items in the ListItemCollection from List.GetItems(Query). 
context.Load(items); 
context.ExecuteQuery(); 
foreach (ListItem listItem in items) 
{ 
    // We have all the list item data. For example, Title. 
    label1.Text = label1.Text + ", " + listItem["Title"]; 
} 

Create a new list item

This example creates a new SharePoint list item using the ListItemCreationInformation class.
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// We are just creating a regular list item, so we don't need to 
// set any properties. If we wanted to create a new folder, for 
// example, we would have to set properties such as 
// UnderlyingObjectType to FileSystemObjectType.Folder. 
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); 
ListItem newItem = announcementsList.AddItem(itemCreateInfo); 
newItem["Title"] = "My New Item!"; 
newItem["Body"] = "Hello World!"; 
newItem.Update(); 

context.ExecuteQuery();  

Update a list item

This example updates a SharePoint list item.
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// Assume there is a list item with ID=1. 
ListItem listItem = announcementsList.Items.GetById(1); 

// Write a new value to the Body field of the Announcement item.
listItem["Body"] = "This is my new value!!"; 
listItem.Update(); 

context.ExecuteQuery();  

Delete a list item

This example deletes a SharePoint list item.
// Starting with ClientContext, the constructor requires a URL to the 
// server running SharePoint. 
ClientContext context = new ClientContext("http://SiteUrl"); 

// Assume that the web has a list named "Announcements". 
List announcementsList = context.Web.Lists.GetByTitle("Announcements"); 

// Assume that there is a list item with ID=2. 
ListItem listItem = announcementsList.GetItemById(2); 
listItem.DeleteObject(); 

context.ExecuteQuery(); } 

SharePoint’s JavaScript Object Model to retrieve the current logged in username

SharePoint’s JavaScript Object Model to retrieve the current logged in username

I have used SharePoint’s JavaScript Object Model to retrieve the current logged in username.Once you have executed the load and executeQueryAsync methods and the call to SharePoint was sucessful, then inside of the onQuerySucceeded method is where I display the username to the browser using the SP.Principal.get_loginName property. Try it out…you can host and run the code below inside of a content editor web part in SharePoint 2010.
<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(init,'sp.js');
var currentUser;
function init(){
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();
    this.clientContext.load(currentUser);
    this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));
}

function onQuerySucceeded() {
    document.getElementById('userLoginName').innerHTML = currentUser.get_loginName(); 
    document.getElementById('userId').innerHTML = currentUser.get_id();
    document.getElementById('userTitle').innerHTML = currentUser.get_title();
    document.getElementById('userEmail').innerHTML = currentUser.get_email();
}

function onQueryFailed(sender, args) {
    alert('Request failed. \nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
</script>
<div>Current Logged User:
    <span id="userLoginName"></span>
    <span id="userId"></span>
    <span id="userTitle"></span>
    <span id="userEmail"></span>
</div>

Understanding client object model fundamentals

Understanding client object model fundamentals

SharePoint 2010 introduced the CSOM as a way to program against a Windows Communication Foundation (WCF) endpoint in SharePoint by using a style that mimicked server-side API development. Prior to the introduction of CSOM, SharePoint developers had only a limited set of web services available for use from client-side code. With the introduction of CSOM, developers had a way to access a significant portion of core SharePoint functionality from C# (called the “managed” client object model), JavaScript, and Silverlight. 

Understanding client object model fundamentals

The managed and JavaScript client object models are maintained in separate libraries, which are located under the SharePoint system directory. The managed client object model is contained in the assemblies Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.ClientRuntime.dll, which can be found in the ISAPI folder. The JavaScript client object model is contained in the library sp.js, which is located in the LAYOUTS folder. Although each of the models provides a different programming interface, each interacts with SharePoint through a WCF service named Client.svc, which is located in the ISAPI directory. Figure 1 shows a basic architectural diagram for the client object models.
In SharePoint 2013, CSOM has been greatly expanded to include functionality from workloads outside of SharePoint Foundation. Using CSOM, app developers now have client-side access to Enterprise Search, Business Connectivity Services, Managed Metadata, Social, and much more. This additional functionality is made available through separate assemblies and libraries that can be referenced in your apps.
image: http://tutorial.programming4.us/image/1411/Working%20with%20the%20CSOM_1.jpg
The client object model provides a programmatic interface to make web service calls against SharePoint by passing in an XML request and receiving a JSON response.
Figure 1. The client object model provides a programmatic interface to make web service calls against SharePoint by passing in an XML request and receiving a JSON response.
Each of the object models presents an object interface in front of a service proxy. Developers write client-side code using the object model, but the operations are batched and sent as a single XML request to the Client.svc service. When the XML request is received, the Client.svc service makes calls to the server-side object model on behalf of the client. The results of the server-side calls are then sent back to the calling client in the form of a JavaScript Object Notation (JSON) object.

Understanding contexts

Much like the standard code you write against the server-side object model, CSOM requires a starting point in the form of a context object. The context object provides an entry point into the associated API that can be used to gain access to other objects. Once you have access to the objects, you can interact with the scalar properties of the object freely (for example, Name, Title, Url, and so on). Example 1 shows how to create a context in each of the models and return an object representing a site collection. After the site collection object is returned, the Url property is examined.
Example . Creating contexts
//Managed Client Object Model
string appWebUrl = Page.Request["SPAppWebUrl"];
using (ClientContext ctx = new ClientContext(appWebUrl))
{
    Site siteCollection = ctx.Site;
    ctx.Load(siteCollection);
    ctx.ExecuteQuery();
    string url = siteCollection.Url;
}

//JavaScript Client Object Model
var siteCollection;
var ctx = new SP.ClientContext.get_current();
siteCollection = ctx.get_site();
ctx.load(site);
ctx.executeQueryAsync(success, failure);

function success() {
    string url = siteCollection.get_url();
}
function failure() {
    alert("Failure!");
}
The ClientContext class in the managed object model inherits from the ClientContextRuntime class. Using the ClientContext class, you can get a valid runtime context by passing in the URL of a site. In Example 1, the URL of the app web is retrieved from the SPAppWebUrl query string parameter. This URL is always available to the remote web and can be used to create a client context for scenarios in which the SharePoint app is using the “internal” security principal.
The SP.ClientContext object in the JavaScript client object model inherits from the SP.ClientContext Runtime object and provides equivalent functionality to the ClientContext class found in the managed client object model. Like the managed model, you can get a runtime context in the JavaScript model by using the SP.ClientContext class and passing a URL. In Example 1, the context is created by using the get_current method, which returns a client context for the app web.

Loading and executing operations

The ClientContextRuntime class used by the managed client defines two methods for loading objects: Load and LoadQuery. You use these load methods to designate objects that should be retrieved from the server. The Load method specifies an object or collection to retrieve, whereas you use the Load Query method to return collections of objects by using a Language-Integrated Query (LINQ) request.
Executing the Load or LoadQuery method does not cause the client to communicate with the server. Instead, it adds the load operation to a batch that will be executed on the server. In fact, you can execute multiple load methods (as well as other operations) before calling the server. Each operation is batched waiting for your code to initiate communication with server. To execute the batched operations, your code must call the ExecuteQuery method in managed code or the Execute QueryAsync method in JavaScript. The ExecuteQuery method creates an XML request and passes it to the Client.svc service synchronously. The ExecuteQueryAsync method sends the request asynchronously. Designated success and failure callback methods receive notification when the asynchronous batch operation is complete.
The sample code in Example 1 uses the Load method to request an object representing the current site collection. After an object is returned, you can generally access any of the scalar properties associated with the object. In cases for which you do not want to return all of the scalar properties for a given object, you can designate the properties to return. In the managed object, properties are designated by providing a series of lambda expressions. In the JavaScript object model, properties are designated by name. This technique helps to minimize the amount of data sent between the client and server. The following code shows how to request only the Title and ServerRelativeUrl properties for a site collection object:
//Managed CSOM references properties via lambda expressions
ctx.Load(site, s=>s.Title, s=>s.ServerRelativeUrl);

//JavaScript CSOM references properties by name
ctx.Load(site, "Title", "ServerRelativeUrl");

Read more at http://tutorial.wmlcloud.com/windows_server/sharepoint-2013---working-with-the-csom-(part-1)---understanding-client-object-model-fundamentals.aspx#FHgS2tvTXDctHk8z.99

Sharepoint 2013 : Working with the CSOM

Sharepoint 2013 : Working with the CSOM (part 3) - Working with the managed client object model - Creating, reading, updating, and deleting

Creating, reading, updating, and deleting

In the conditional scope shown in Example 4, a new list is created if the user has the appropriate permissions. Creating new lists and items using the managed client object model is done with the creation information objects. Using the ListCreationInformation and ListItemCreationInformation objects, you can define all of the necessary values for a list or item and then send that data with the batch back to the server. Example 5 shows how to use these objects to create a new list and list item.
Example 5. Creating a list and list item
string appWebUrl = Page.Request["SPAppWebUrl"];
using (ClientContext ctx = new ClientContext(appWebUrl))
{
    //Create a new list
    ListCreationInformation listCI = new ListCreationInformation();
    listCI.Title = "My List";
    listCI.Description += "A list for use with the Client OM";
    listCI.TemplateType = (int)ListTemplateType.GenericList;
    listCI.QuickLaunchOption = Microsoft.SharePoint.Client.QuickLaunchOptions.On;
    List list = ctx.Web.Lists.Add(listCI);
    ctx.ExecuteQuery();

    //Create a new list item
    ListItemCreationInformation listItemCI = new ListItemCreationInformation();
    ListItem item = list.AddItem(listItemCI);
    item["Title"] = "New Item";
    item.Update();
    ctx.ExecuteQuery();
}
If you would like to return items from a list by using CSOM, you must write Collaborative Application Markup Language (CAML) queries. CAML queries are created for the managed client object model via the CamlQuery object. This object has a ViewXml property that accepts a CAML query designating the items to return. Example 6 demonstrates running a CAML query against a list.
Example 6. Using CAML to return list items
string appWebUrl = Page.Request["SPAppWebUrl"];
using (ClientContext ctx = new ClientContext(appWebUrl))
{
    //Read the Site, List, and Items
    ctx.Load(ctx.Web);

    List myList = ctx.Web.Lists.GetByTitle("My List");
    ctx.Load(myList);

    StringBuilder caml = new StringBuilder();
    caml.Append("<View><Query>");
    caml.Append("<Where><Eq><FieldRef Name='Title'/>");
    caml.Append("<Value Type='Text'>New Item</Value></Eq></Where>");
    caml.Append("</Query><RowLimit>100</RowLimit></View>");

    CamlQuery query = new CamlQuery();
    query.ViewXml = caml.ToString();
    ListItemCollection myItems = myList.GetItems(query);
    ctx.Load(myItems);

    ctx.ExecuteQuery();
    Response.Write("<p>Site: " + ctx.Web.Title + "</p>");
    Response.Write("<p>List: " + myList.Title + "</p>");
    Response.Write("<p>Item Count: " + myItems.Count.ToString() + "</p>");
}
Updating through the managed client object model is straightforward. In most cases, you will simply set the value of a property and then call the appropriate Update method. Example 7 presents samples of updating a site, list, and list item.
Example 7. Update operations
//Update the Site, List, and Items
ctx.Web.Description = "Client OM samples";
ctx.Web.Update();

myList.Description = "Client OM data";
myList.Update();

foreach (ListItem myItem in myItems)
{
    myItem["Title"] = "Updated";
    myItem.Update();
}

ctx.ExecuteQuery();
Response.Write("<p>Site: " + ctx.Web.Description + "</p>");
Response.Write("<p>List: " + myList.Description + "</p>");
Response.Write("<p>Item Count: " + myItems.Count.ToString()+ "</p>");
Deleting objects with the managed client object model involves calling the DeleteObject method. This method is the same across most objects that can be deleted. The following code shows how to delete the list created earlier:
myList.DeleteObject();
ctx.ExecuteQuery();
Along with lists, you’ll also want to work with libraries. Document libraries are handled in the managed client object model similarly to lists. Of course, the major difference is handling documents. Fortunately, uploading documents to libraries by using the managed client object model is very similar to using the server object model; you must upload the document using the URL of the folder in which you want to store the document. Example 8 shows a full set of create, read, update, and delete operations around a file and a document library.
Example 8. Working with document libraries
string appWebUrl = Page.Request["SPAppWebUrl"];
using (ClientContext ctx = new ClientContext(appWebUrl))
{
    //Get site
    Web site = ctx.Web;
    ctx.Load(site);
    ctx.ExecuteQuery();

    //Create a new library
    ListCreationInformation listCI = new ListCreationInformation();
    listCI.Title = "My Docs";
    listCI.Description = "A library for use with Client OM";
    listCI.TemplateType = (int)ListTemplateType.DocumentLibrary;
    listCI.QuickLaunchOption = Microsoft.SharePoint.Client.QuickLaunchOptions.On;
    List list =site.Lists.Add(listCI);
    ctx.ExecuteQuery();

    //Create a document
    MemoryStream m = new MemoryStream();
    StreamWriter w = new StreamWriter(m);
    w.Write("Some content for the document.");
    w.Flush();

    //Add it to the library
    FileCreationInformation fileCI = new FileCreationInformation();
    fileCI.Content = m.ToArray();
    fileCI.Overwrite = true;
    fileCI.Url = appWebAppUrl + "/My%20Docs/MyFile.txt";
    Folder rootFolder = site.GetFolderByServerRelativeUrl("My%20Docs");
    ctx.Load(rootFolder);
    Microsoft.SharePoint.Client.File newFile = rootFolder.Files.Add(fileCI);
    ctx.ExecuteQuery();

    //Edit Properties
    ListItem newItem = newFile.ListItemAllFields;
    ctx.Load(newItem);
    newItem["Title"] = "My new file";
    newItem.Update();
    ctx.ExecuteQuery();

    //Delete file
    newItem.DeleteObject();
    ctx.ExecuteQuery();
}

Read more at http://tutorial.wmlcloud.com/windows_server/Sharepoint-2013---Working-with-the-CSOM-(part-3)---Working-with-the-managed-client-object-model---Creating,-reading,-updating,-and-deleting.aspx#6WMToYbtzTHKbZxb.99

SharePoint 2013 Hosted Apps - 3

SharePoint 2013 Hosted Apps - 3

we made changes to our SharePoint 2013 Hosted App, to use the REST API to get list items that were selected from a list. When you clicked on the Ribbon button it sent the selected items to the “default.aspx” page of the App Web and rendered them accordingly. The code we used for rendering the selected items was not ideal as we just asked the REST service to give me everything and then filter out the ones that are not in the query string. As you can imagine not the most performing code you could write.

To make this better and faster one of the new features of the REST API is to pass filters directly to the call. Firstly let’s look at the syntax, we can use. We can test this by using the following URL against our Office 365 site.
This will let you call the REST API directly and see an RSS feed type result come back. Some basic examples would be to specify the fields that come back. To do this the URL would need to be the following:
When this is ran you should see the following:
This does not really help us as we would like to see the core XML, I use Fiddler for this, so when you call the URL you are able to inspect the response. You will see a get request similar to this:
If you select that line and then select the “Headers” tab on the right and choose “XML” from the bottom you should see the returned XML response.
This just helps me see that the right XML is being returned. Using the “$select” parameter we can specify as many fields as we wish or simply remove it to show all fields.
Now back to the original issue, we want to only retrieve the selected items form the REST API call, not all of them and filter. So we can now use another parameter “$filter“. As a simple example let’s retrieve one of the items from our “Announcements” list.
This URL will render the following:
And out Fiddler trace shows the following:
So what if we wanted to filter on multiple values, so in our example let’s say we had selected items 3 and 2. Our new filter URL would be the following:
Our fiddler trace will now return the following:
So to tie this all together we need to change out code in the “App.js” to be the following so it only returns the selected items. Firstly we need to modify the following code:
This creates a new variable to contain a dynamic query. We then modify the core document ready code to not run and simply show us an alert box saying the “selectedids” variable is not populated, in the real world you would change this behavior of course. We then wrap a call to the “getSelectedItemIDs” and the rest of the core code to ensure it does not run when nothing has been selected. Now we need to modify the core method “getSelectedList” to contain a filtering option.
We also need to remove the last code we used in the “getListSuccess” method as we are no longer getting all the items and filtering through the loop process.
Lastly we need to create the new method “getSelectedItemIDs” which simply splits the query string that contains the selected IDs from the list, loops through them and creates an output that renders like this:
Now when we run the code, we are able to select values and when we click the ribbon button will render only those, by using the REST API query to just get those items.
So to recap we have looked at using the selected items query string, passing it into the REST API call after dynamically create the filter clause then rendering the values out on the page. In the next post we will look at creating the rest of the user interface such as the grid for the specific fields we want to show