CHUVASH.eu

CHunky Universe of Vigourous Astonishing SHarepoint :)

Tag Archives: SPListItem

Delete all list items with jsom

Today I needed to “clean” a list, meaning to remove all list items. For some time ago I wrote a post about different ways of removing list items in bulk: Server Object Model, SPLinq and RPC.  This time I had only the web browser. So I tried the jsom way. By the way, the javascript documentation for jsom on msdn is getting really good. Don’t miss that: How to: Complete basic operations using JavaScript library code in SharePoint 2013.

Now here comes theworking code I used to remove all items in my list:

var ctx = SP.ClientContext.get_current(),
   list = ctx.get_web().get_lists().getByTitle('MyList'),
   query = new SP.CamlQuery(),
   items = list.getItems(query);
ctx.load(items, "Include(Id)");
ctx.executeQueryAsync(function () {
    var enumerator = items.getEnumerator(),
        simpleArray = [];
    while (enumerator.moveNext()) {
        simpleArray.push(enumerator.get_current());
    }
    for (var s in simpleArray) {
        simpleArray[s].deleteObject();
    }
    ctx.executeQueryAsync();
});

Enjoy

Advertisements

Paging with JSOM

If there are many list items you try retrieve with javascript object model,paging could be very useful. Today I came across a wonderful blog post series about javascript object model in SharePoint: The SharePoint javascript object model – Resources and Real World Examples posted by David Mann and published on Aptilon Blog.

There is an example how to achieve paging with JSOM. The key is items.get_listItemCollectionPosition() and query.set_listItemCollectionPosition()

I have refactored David’s example to avoid global variables and to put into a module. Here is it. If you have a Tasks list in your site with many items, just hit F12 to open the console and paste this and see the result:

(function(SP) {
   var 
      ctx = SP.ClientContext.get_current(),
      list = ctx.get_web().get_lists().getByTitle('Tasks'),
      position,
      enumerator,
      view = '<View><ViewFields><FieldRef Name="Title"/></ViewFields><RowLimit>10</RowLimit></View>',
      query = new SP.CamlQuery(),
      items,
      init = function() {
         query.set_viewXml(view);			
      },
      loadChunks = function() {
         query.set_listItemCollectionPosition(position);
         items = list.getItems(query);
         ctx.load(items);
         ctx.executeQueryAsync(success, error);
      },
      success = function() {
         console.log("\nFound Matching Items! ");
         enumerator = items.getEnumerator();
         while(enumerator.moveNext()) {
            console.log("Title: " + enumerator.get_current().get_item("Title") );
         }
         position = items.get_listItemCollectionPosition();
         //when there are no items position is null
         position && loadChunks();
      },
      error = function(sender, args) {
         console.log('Request failed. Error: ' + args.get_message() + '. StackTrace: ' + args.get_stackTrace());
      };

   init();
   loadChunks();
})(SP);

ListUrl on EventReceiver

When you create an eventreceiver, you get the ListTemplateId attribute.

It works fine. But if you want the eventreceiver to trigger on one particular list, just replace ListTemplateId attribute with ListUrl. For Pages you can use:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <Receivers ListUrl="$Resources:cmscore,List_Pages_UrlName;">
    <Receiver>
      <Name>NewsPageEventReceiverItemUpdated</Name>
      <Type>ItemUpdated</Type>
      <Assembly>$SharePoint.Project.AssemblyFullName$</Assembly>
      <Class>Contoso.EventReceivers.NewsPageEventReceiver.NewsPageEventReceiver</Class>
      <SequenceNumber>1000</SequenceNumber>
    </Receiver>
  </Receivers>
</Elements>

Server Relative Url of an SPListItem

The easiest way to get the server relative url of an SPListItem is to retrieve the property “ServerUrl”.

SPListItem item...
var url = item["ServerUrl"];

Se om det är en tråd eller inlägg i diskussionsforum

Diskussioner sparas i en vanlig lista. En ny tråd sparas som en folder. Alla svar sparas som SPListItem i den foldern. En folder är så klart också en SPListItem, fast har en annan typ.

För att se om det är en tråd, kan man jämföra ett fält som har ett guid som man kommer åt via SPBuiltInFieldId.FSObjType.

 

var item = properties.ListItem;
var type = Convert.ToInt32(item[SPBuiltInFieldId.FSObjType]);
var foldertype = (int) SPFileSystemObjectType.Folder;
if (type == foldertype)
{
	//Yes, this is the thread head
	var body = item["Body"].ToString();
}

 

 

AfterProperties kräver InternalName

AfterProperties kommer inte leda till Exception, men de kommer returnera bara null, om du använder DisplayName. Man måste ha InternalName. Här är ett litet exempel på hur man kan få ut värden före och efter uppdateringen. Exemplet har testats i ItemUpdated-eventreceiver.

var before = properties.BeforeProperties;
var after = properties.AfterProperties;
var contentDisplayName = "News Content";
var list = properties.List;
var contentInternalName = list.Fields[contentDisplayName].InternalName;
var contentBefore = before[contentInternalName];
var contentAfter = after[contentInternalName];

Interna fältnamn i SPList

Här är en väldigt bra lista över fältnamn, eller denna lista, till och med bättre i SPList, både Display Name, Internal Name och GUID.

En annan bra länk är förklaringen om hur interna fältnamn är uppbyggda av Marc Anderson.

För att se interna namnet kan man klicka på kolumnrubriken (för att sortera) så ser man det i URL:en.

 

EDIT: den här tyckte jag mycket om.

Komma åt Title-kolumnen i SPList

Vad gör man om man vill lägga till Title-kolumnen till en ny vy?

SPField fieldTitle = scheduleList.Fields["Title"];

Det kommer funka, men Title kommer vara bara text, utan en länk till SPListItem.

Kolla på den koden:

SPField fieldTitle = scheduleList.Fields[SPBuiltInFieldId.LinkTitle];

Här hämtar vi kolumnen som heter i Sharepoint “Title linked with item menu”. Det finns fler sådana “inbygda” kolumner.

Radera en specifik sida i en site

Om man vill radera någon specifik sida som finns på flera siter, så måste man loopa igenom alla SPList objekt som finns i ett SPWeb objekt.

På ett SPList som heter “Pages” ska man loopa igenom alla SPListItem och radera den som har Title som man är ute efter.

Jag raderar alla sidor som heter “schedule.aspx”:

private void DeleteScheduleAspx(SPWeb web)
{
    bool found = false;
    foreach (SPList list in web.Lists)
    {
        if (list.Title.Equals("Pages") 
            && list is SPDocumentLibrary)
        {
            foreach(SPListItem item in list.Items) 
            {
                if(item.Name.Equals("schedule.aspx")) 
                {
                    item.Delete();
                    list.Update();
                    found = true;
                    break;
                }
            }
        }
        if (found)
        {
            break;
        }
    }
}
Вула Чăвашла

VulaCV - Чăвашла вулаттаракан сайт

Discovering SharePoint

And going crazy doing it

Bram de Jager talking Office 365, SharePoint and Azure

My view and thoughts on Productivity and more.

My programming life

and everything in between

SharePoint Development Lab by @avishnyakov

It is a good place to share some SharePoint stories and development practices.

SharePoint Dragons

Nikander & Margriet on SharePoint

Paul J. Swider - RealActivity

RealActivity is a specialized healthcare services and solution advisory firm.

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Cameron Dwyer | Office 365, SharePoint, Outlook, OnePlace Solutions

Office 365, SharePoint, OnePlace Solutions & Life's Other Little Wonders

paul.tavares

Me and My doings!

Share SharePoint Points!!

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

SPJoel

SharePoint for everyone

SharePointRyan

Ryan Dennis is a SharePoint Solution Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint