CHUVASH.eu

CHunky Universe of Vigouros Astonishing SHarepoint :)

Update multi-value lookup column values in SharePoint 2010 using managed CSOM

Anatoly Mironov:

Reblogging this useful code sample for updating multi-value lookup columns using CSOM in C# in SharePoint 2010, but also valid for SharePoint 2013.

Originally posted on Bin's Dev Notes:

I received a task that needs to update multi-value lookup column value in SharerePoint 2010 using C#.  While it is easy to set columns of simple data types, with lookup column it is a bit more complicated.  Searching Web gives me following link which is helpful. However, that only works with single value column.   After a bit trial and error, I worked out following code that is functioning.

1
public void UpdateLookup(string siteUrl, int id, string lookupColumnName,
List multiLookupValues, string listName, string lookupListName)
{
using (ClientContext ctx = new ClientContext(siteUrl))
{
ctx.Credentials = new NetworkCredential(_username, _password, _domain);
var list = ctx.Web.Lists.GetByTitle(listName);
var item = list.GetItemById(id);
var lookUpList = ctx.Web.Lists.GetByTitle(lookupListName);
CamlQuery query = new CamlQuery();
query.ViewXml = CreateCaml(multiLookupValues);
var items = lookUpList.GetItems(query);
ctx.Load(item, i => i[lookupColumnName]);
ctx.Load(items);
ctx.ExecuteQuery();
var lookupValues = new ArrayList();
FieldLookupValue[] values = item[lookupColumnName] as FieldLookupValue[];
foreach (ListItem listItem in items)
{
var lookupValue = new FieldLookupValue { LookupId = listItem.Id };
lookupValues.Add(lookupValue);
}
item.ParseAndSetFieldValue(lookupColumnName…

View original 49 more words

Bypass all custom jslink

bypasscustomjslink-001

Client Side Rendering (CSR) and jslink are great for customizing lists and forms in SharePoint. In my current project we use it a lot of it. A disadvantage of that path, although, is that it might occur javascript errors, during the development phase, but also in production. We do, of course, our best to leverage the best jslink code, but unfortunately we have to live with the fact that errors can occur, especially when we use it for NewForm, EditForm, DisplayForm and View (in list and grid).

If an error occurs, it won’t stop the rest of javascript (it is wrapped in try and catch by SharePoint), but the fields will still not function as intended. It can also be some “corrupt” or old data in the field value that will “break” the jslink code.

I would like to suggest one little fix, an idea I’ve come up to in my jslink-heavy project:

Use a custom url parameter to stop all custom jslink execution.

The query string parameter can be called bypasscustomjslink=true

In every custom jslink, start with this line of code:

That’s it. If you have this in place, you can just manually add this to your url in browser:

?bypasscustomjslink=true

or

&bypasscustomjslink=true

Then all the customized fields and views will be uncustomized until bypasscustomjslink=true is removed. While viewing and editing list items in this uncustomized mode, you can access and repair data as if you never had adjusted it with jslink.

Using this does not mean you can “relax” and start writing crappy code. You still have to produce good code and anticipate all possible errors. bypasscustomjslink is just a convenient “emergency exit” aimed for developers and support to quickly solve problems without needing to reset the JSLink property on fields and list views.

Client Side Rendering with Async dependencies

Yesterday I asked a question on SharePoint StackExchange:

I also asked Elio Struyf on Twitter:

Good idea, Elio Struyf! Now I want to try it out.

Preparations

In this case I’ll be using my example from my blog post yesterday:

Drag and Drop Image using Client Side Rendering

I have created a new list and added a lookup field to my previous list. What I get is a Title of the lookup item, but not my custom field called DragAndDrop. In my test I will try to load the DragAndDrop Image using an ajax call and rendering it after Client Side Rendering is done with my item.

To be complete, I want to show some screenshots for my lookup field:

csr-async-001csr-async-002

It will result in this OOTB rendering:
csr-async-003

Trying out CSR with async dependencies

While working with jslink, first of all I want to show a loading image instead of an empty html element, to show that something is loading:
csr-async-004

Here is the skeletton of the jslink file:

(function () {
    'use strict';

    var display = function (ctx, field) {
        var containerId = "tolle";
        var loadingImg = _spPageContextInfo.webAbsoluteUrl + "/_layouts/images/loadingcirclests16.gif";
        //unfortunately SP.Utilities.Utility is not defined at this stage
        //SP.Utilities.Utility.getImageUrl("loadingcirclests16.gif");       
        return ['<div id="', containerId, '"><img src="', loadingImg, '"/></div>'].join('');
    };

    var overrideContext = {};
    overrideContext.Templates = overrideContext.Templates || {};
    overrideContext.Templates = overrideContext.Templates || {};
    overrideContext.Templates.Fields = {
        'TolleLookup': {
            'DisplayForm': display
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
})();

Making an ajax call

Next step is to initiate an ajax call. I am trying to avoid the jQuery dependency. There is so much you can do with the built-in javascript functions. For making an ajax call I am using SP.RequestExecutor.js

Here is the result:

csr-async-005

The code should be quite self explaining:

(function () {
    'use strict';

    var onDataRetrieved = function(response) {
        console.log("yippie");
        var data = JSON.parse(response.body);
        var imgSrc = data.d.DragAndDropImage;
        var container = document.getElementById("tolle");
        container.innerHTML = ['<img src="', imgSrc, '"/>'].join('');
    }

    var onError = function(response) {
        console.error("failed", response);
    }
    var initiateAjaxCall = function(ctx) {
        var item = ctx.CurrentItem;
        var fieldName = ctx.CurrentFieldSchema.Name;
        var fieldValue = item[fieldName];
        
        var itemId = fieldValue.split(";#")[0];
        var lookupListId = ctx.ListSchema.Field[0].LookupListId;
        var url = [window._spPageContextInfo.webAbsoluteUrl,
            "/_api/web/lists/getbyid('",
            lookupListId,
            "')/Items(",
            itemId, ")?$select=DragAndDropImage"].join("");
        SP.SOD.registerSod('sp.requestexecutor.js', '/_layouts/15/sp.requestexecutor.js');
        SP.SOD.executeFunc("sp.requestexecutor.js", "SP.RequestExecutor", function () {
            var executor = new SP.RequestExecutor(window._spPageContextInfo.webAbsoluteUrl);
            executor.executeAsync(
                {
                    url: url,
                    method: "GET",
                    headers: { "Accept": "application/json; odata=verbose" },
                    success: onDataRetrieved,
                    error: onError
                }
            );
        });
    }
    var display = function (ctx, field) {
        if (!ctx.CurrentItem[ctx.CurrentFieldSchema.Name]) { //if there is no value
            return "";
        }
        var containerId = "tolle";
        var loadingImg = window._spPageContextInfo.webAbsoluteUrl + "/_layouts/images/loadingcirclests16.gif";
        initiateAjaxCall(ctx);
        //unfortunately SP.Utilities.Utility is not defined at this stage
        //SP.Utilities.Utility.getImageUrl("loadingcirclests16.gif");       
        return ['<div id="', containerId, '"><img src="', loadingImg, '"/></div>'].join('');
    };

    var overrideContext = {};
    overrideContext.Templates = overrideContext.Templates || {};
    overrideContext.Templates = overrideContext.Templates || {};
    overrideContext.Templates.Fields = {
        'TolleLookup': {
            'DisplayForm': display
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
})();

Next steps and further considerations

It seems to work, although I have some considerations:

  1. What happens if the data from the ajax call is retrieved before Client Side Rendering is done (then the container is not rendered yet). Even if the risk for that is low, it should be handled properly.
  2. It would be good to have a consistent look and feel in the Display form and in the list view. To make it possible, following should be done:
    1. We must create references to html elements (containers) with unique ids, need to implement logic for generating ids and keeping track of the right elements.
    2. Ajax calls should be bundled, otherwise it will hugely impact the performance, even in a list view with 30 items.

Drag and Drop Image using Client Side Rendering

I continue my series about Client Side Rendering (CSR) and jsgrid. Today I want to try a custom field where users can drag and drop images. The inspiration comes from:

What I want to achieve is:

  1. A custom field that is rendered with jslink
  2. Users can drag and drop small pictures (thumbnails) into the field
  3. A base64 image representation is saved as the field value
  4. Optionally implement pasting images using Clipboard API

Step 1 Create a field with a custom jslink

Create a field of type Note. I am using the PnP Core Extensions to make it quickier:

dnd-001

My jslink file is very simple to begin with:

(function () {
    'use strict';
    function view(ctx, field) {
        return "hello";
    }

    var overrideContext = {};

    overrideContext.Templates = overrideContext.Templates || {};
    overrideContext.Templates.Fields = {
        'DragAndDropImage': {
            'View': view,
            'DisplayForm': view
            //'EditForm': verySimpleNewAndEdit,
            //'NewForm': verySimpleNewAndEdit
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
})();

This will result in the following display form. Just outputting “hello” indicates that my field is jslink are registered correctly:

dnd-002

Step 2. Ensure base64 works in the field

Not all fields will work. I have tried many of them and found that the field type Note with Plain text works for saving base64 images.

First download some sample icons at flaticons.com

dnd-003

Convert an icon to a base64 image using dataurl.net:

dnd-004

Save the string into the Drag And Drop Image field:

dnd-005

Now update the view template in the CSR overrides:

//http://stackoverflow.com/a/822486/632117
//in display form we have to strip the html elements that are pasted in by SharePoint
function strip(html) {
    var tmp = document.createElement("DIV");
    tmp.innerHTML = html;
    return tmp.textContent || tmp.innerText || '';
}
function renderImage(fieldValue) {
    if (fieldValue) {
        return ['<img style="max-width:100px;" src="',
            strip(fieldValue), '"/>'].join('');
    }
    return '';
}

function view(ctx, field) {
    //disable editing in Quick Edit mode
    if (ctx.inGridMode) {
        field.AllowGridEditing = false;
    }
    var fieldValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
    return renderImage(fieldValue);
}

Well, it works:

dnd-006dnd-007

 Step 3. Implement drag and drop

Let’s start with the edit template:

function renderDropZone(fieldValue) {
    var img = renderImage(fieldValue);
    return ['<div id="drop_zone">', img, '</div>'].join('');
}

function edit(ctx, field) {
    var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
    formCtx.registerGetValueCallback(formCtx.fieldName, function () {
        //will implement the logic later
        return '';
    });
    var fieldValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
    return renderDropZone(fieldValue);
}

var overrideContext = {};
overrideContext.Templates = overrideContext.Templates || {};
overrideContext.Templates.Fields = {
    'DragAndDropImage': {
        'View': view,
        'DisplayForm': view,
        'EditForm': edit,
        'NewForm': edit
    }
};

I have wrapped the image element with a div (id=drop_zone). Now I need some css to show it:

var additionalStyle = [
    '<style>',
    '#drop_zone { height: 100px; width:100px; background: #efe}',
    '</style>'
].join('');
document.write(additionalStyle);

Now there is a clear “drop zone”:
dnd-008
To make it as simple as possible, let’s follow oroboto’s drag and drop code. Here we go:

var processFiles = function (event) {
    var element = event.target;
    event.stopPropagation();
    event.preventDefault();
    removeDropZoneClass(event);

    // FileList object of File objects
    var files = event.dataTransfer.files;
    for (var i = 0, f; f = files[i]; i++) {
        var reader = new FileReader();

        // closure to capture file info
        reader.onload = (function (file, index) {
            return function (e) {
                var dataUri = e.target.result;
                var img = renderImage(dataUri);
                element.innerHTML = img;
            };
        })(f, i);

        // read file as data URI
        reader.readAsDataURL(f);
    }

};

var highlightDropZone = function (e) {
    e.stopPropagation();
    e.preventDefault();
    document.getElementById('drop_zone').classList.add('highlight');
}

var removeDropZoneClass = function (e) {
    document.getElementById('drop_zone').classList.remove('highlight');
}

function prepareDropZone(ctx) {
    if (ctx.inGridMode) {
        return;
    }
    // add event listeners if File API is supported
    var dropZone = document.getElementById('drop_zone');
    if (window.File &amp;amp;&amp;amp; window.FileReader &amp;amp;&amp;amp; window.FileList &amp;amp;&amp;amp; window.Blob) {
        dropZone.addEventListener('drop', processFiles, false);
        dropZone.addEventListener('dragover', highlightDropZone, false);
        dropZone.addEventListener('dragenter', highlightDropZone, false);
        dropZone.addEventListener('dragleave', removeDropZoneClass, false);
    } else {
        dropZone.innerHTML = 'The File APIs are not fully supported in this browser.';
        dropZone.className = 'highlight';
    }

};

// ... code omitted for brevity

overrideContext.Templates.OnPostRender = prepareDropZone;

That’s not bad, not bad:

dnd-009

The last thing in this step is to save the base64 value

formCtx.registerGetValueCallback(formCtx.fieldName, function () {
    var dropZone = document.getElementById('drop_zone');
    var img = dropZone.getElementsByTagName('img');
    return img.length ? img[0].src : '';
});

Step 4 Support pasting images

Drag And Drop is cool. But what about pasting images. Wouldn’t it be nice? The functionality is called Clipboard API. You can check which browsers support this on caniuse.com. The simplest example I’ve found is on stackoverflow: How does onpaste work

The code I use is as follows:

document.onpaste = function (event) {
    var items = (event.clipboardData || event.originalEvent.clipboardData).items;
    console.log(JSON.stringify(items)); // will give you the mime types
    var blob = items[0].getAsFile();
    var reader = new FileReader();
    reader.onload = function (e) {
        var dataUri = e.target.result;
        var img = renderImage(dataUri);
        dropZone.innerHTML = img;
    }; // data url!
    reader.readAsDataURL(blob);
}

Here is how pasting works:
dnd-011

Step 5 Error handling (Not done yet)

I need to ensure that

  • only images are allowed
  • only small images are allowed, otherwise base64 will be to heavy
  • proper handling of old browsers, we don’t need to support them, but the users should get good information about what they need to make it work
  • a help icon is shown, when clicked a help callout is shown about how it works

Step 6 Support Quick Edit (Not done yet)

We need code that works in Quick Edit:

  • need to write code for jsgrid
  • need handling of multiple drop zones on the same page (unique ids and smart handling of pasting)

Summary

This post is about discovering what’s possible to do with client side rendering and using today’s technologies like html5 and new javascript apis. I hope you’ve got some inspiration how normal sharepoint fields combined with Client Side Rendering (CSR) api can create more value in your project, in Office 365 and in SharePoint On Premises. Please leave feedback in comments.

Fulll source code

And finally, here comes the most up-to-date full source code for this custom Drag And Drop Image field:

(function () {
    'use strict';
    var additionalStyle = [
        '<style>',
        '#drop_zone { height: 100px; width:100px; background: #efe}',
        '#drop_zone.highlight {background:#fee;}',
        '</style>'
    ].join('');
    document.write(additionalStyle);


    var processFiles = function (event) {
        var element = event.target;
        event.stopPropagation();
        event.preventDefault();
        removeDropZoneClass(event);

        // FileList object of File objects
        var files = event.dataTransfer.files;
        for (var i = 0, f; f = files[i]; i++) {
            var reader = new FileReader();

            // closure to capture file info
            reader.onload = (function (file, index) {
                return function (e) {
                    var dataUri = e.target.result;
                    var img = renderImage(dataUri);
                    element.innerHTML = img;
                };
            })(f, i);

            // read file as data URI
            reader.readAsDataURL(f);
        }

    };

    var highlightDropZone = function (e) {
        e.stopPropagation();
        e.preventDefault();
        document.getElementById('drop_zone').classList.add('highlight');
    }

    var removeDropZoneClass = function (e) {
        document.getElementById('drop_zone').classList.remove('highlight');
    }

    function prepareDropZone(ctx) {
        if (ctx.inGridMode) {
            return;
        }
        // add event listeners if File API is supported
        var dropZone = document.getElementById('drop_zone');
        if (window.File &amp;amp;&amp;amp; window.FileReader &amp;amp;&amp;amp; window.FileList &amp;amp;&amp;amp; window.Blob) {
            dropZone.addEventListener('drop', processFiles, false);
            dropZone.addEventListener('dragover', highlightDropZone, false);
            dropZone.addEventListener('dragenter', highlightDropZone, false);
            dropZone.addEventListener('dragleave', removeDropZoneClass, false);
        } else {
            dropZone.innerHTML = 'The File APIs are not fully supported in this browser.';
            dropZone.className = 'highlight';
        }

        document.onpaste = function (event) {
            var items = (event.clipboardData 
                 || event.originalEvent.clipboardData).items;
            console.log(JSON.stringify(items)); // will give you the mime types
            var blob = items[0].getAsFile();
            var reader = new FileReader();
            reader.onload = function (e) {
                var dataUri = e.target.result;
                var img = renderImage(dataUri);
                dropZone.innerHTML = img;
            }; // data url!
            reader.readAsDataURL(blob);
        }
       
    };

    //http://stackoverflow.com/a/822486/632117
    //in display form we have 
    //to strip the html elements that are pasted in by SharePoint
    function strip(html) {
        var tmp = document.createElement('DIV');
        tmp.innerHTML = html;
        return tmp.textContent || tmp.innerText || '';
    }
    function renderImage(fieldValue) {
        if (fieldValue) {
            return ['<img style="max-width:100px;" src="',
                strip(fieldValue), '"/>'].join('');
        }
        return '';
    }
    
    function view(ctx, field) {
        //disable editing in Quick Edit mode
        if (ctx.inGridMode) {
            field.AllowGridEditing = false;
        }
        var fieldValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
        return renderImage(fieldValue);
    }
    
    function renderDropZone(fieldValue) {
        var img = renderImage(fieldValue);
        return ['Drop files here<div id="drop_zone"', img, '</div>'].join('');
    }

    function edit(ctx, field) {
        var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
        formCtx.registerGetValueCallback(formCtx.fieldName, function () {
            var dropZone = document.getElementById('drop_zone');
            var img = dropZone.getElementsByTagName('img');
            return img.length ? img[0].src : '';
        });
        var fieldValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
        return renderDropZone(fieldValue);
    }

    var overrideContext = {};
    overrideContext.Templates = overrideContext.Templates || {};
    overrideContext.Templates.Fields = {
        'DragAndDropImage': {
            'View': view,
            'DisplayForm': view,
            'EditForm': edit,
            'NewForm': edit
        }
    };

    overrideContext.Templates.OnPostRender = prepareDropZone;

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
})();

Disabling a column in Quick Edit

jsgrid-015
In my project I have a column called Request Status. This column is not shown in any forms, meaning users should not edit, because it is controlled through the app. Nevertheless it is editable in the Quick Edit.

Yesterday I wrote about jsgrid in my blog. Now comes more. Today I’ll share a little practical solution how one can disable editing a field in Quick Edit.

The field is edited in jsgrid, but to disable it, we only have set the property called AllowGridEditing to false on our column (not even touching the heavy jsgrid api). We can do in the OnPreRender event in our Client Side Rendering (CSR) registration. Having the context object we have access to the Fields (ContextInfo.ListSchema.Field):

(function () {
    var overrideContext = {};
    overrideContext.Templates = overrideContext.Templates || {};
    overrideContext.Templates.OnPreRender = function(ctx) {
    	var statusField = ctx.ListSchema.Field.filter(function(f) {
    		return f.Name === 'Request_x0020_Status';
    	});
    	if (statusField) {
    		statusField[0].AllowGridEditing = false;
    	}
    }
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
})();

Another way is to implement the display form:

(function () {
    var view = function (ctx, field) {
        if (ctx.inGridMode) {
            field.AllowGridEditing = false;
        }
        return window.RenderFieldValueDefault(ctx);
    };
    var overrideContext = {};
    overrideContext.Templates = overrideContext.Templates || {};
    overrideContext.Templates.Fields = {
        'Request_x0020_Status': {
            'View': view
        }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
})();

JSGrid Basics

JSGrid is the javascript framework in SharePoint used in Quick Edit View (previously Datasheet View). There are a few very good blog posts on this topic (See below in “Sources”). Nevertheless the fact is that jsgrid and working with quick edit from a developer’s perspective is a huge undiscovered area. Articles I have seen are intended for advanced developers. The goal with my post today is to outline the very basics of working with JSGrid. When you know the basics you will be more comfortable to discover and try out more.

The example I want to show is a jsgrid code for a “VerySimpleColumn”. The source code can be found on gist.github.com: https://gist.github.com/mirontoli/838d60df76107fac56a0 To focus on jsgrid, I assume you have knowledge and some experience of working with jslink, which is related to jsgrid.

A word of caution before we start

JSGrid is an undocumented part of SharePoint javascript “ecosystem”, neither it is a part of the official SharePoint javascript api. So actually we should not use it. On the other hand JSGrid indicates something that is more like a full-fledged javascript api because:

  1. It seems to be carefully prepared (all possible situations are covered)
  2. The api is human-readable. The events and properties are called OnBeginEdit, OnEndEdit, Focus, BindToCell and so on (opposed to the properties in the SP.Microfeed.js like $v_1, $v_2)
  3. It follows many best-practices for handling the UI in javascript, eventhough some constructs are clumsy, e.g. using absolute-positioned overlays on top of original table cells while editing a cell value.

So to me it seems quite okay to use it in real applications, but we have to live with the risk that the jsgrid api will be changed without any notice to us developers.

Set up a site column with a custom jslink

The first step is to set up everything so we can start discovering jsgrid. It is just a walkthrough, not a detailed explanation. If you are eager to look at jsgrid, jump directly to that section. In this example we’ll apply a jslink to a custom site column. The very same jslink will be used in jsgrid, too.

First of all add a new Site Column, call it VerySimpleColumn. The type is Multiple lines of text:

jsgrid-001

Let us put it in a new group: Tolle Columns (beautiful, huh?)

jsgrid-002

 

Three lines of plain text. Nothing extravagant.

jsgrid-003

After that we can verify that the column exists. Fine.

jsgrid-004

 

Now we have to update the jslink property for the new column. Make it in an app:

jsgrid-005

Now add a custom list, call it “TolleList”:

jsgrid-006

 

In the List Settings add the new site column, then you’ll see this:

jsgrid-007

 

Now upload an empty js file to the Style Library, call it field.jslink.verysimplecolumn.js:

jsgrid-008

 

It goes so fast :) Now it is time to implement some jslink code

Writing jslink

I’ve been thinking a while. What example could I use for that jslink? I want it to be a very simple example, so we don’t need to concentrate on actual rendering logic. You can see sophisticated examples that I listed below in “Sources”. Here we will be using this example: We’ll append a text to the field value: “This field is fully controlled by jslink”. This text should be visible on all forms, but it is not a part of the actual field value. Well here it is:

jsgrid-009

The code should appear simple for us who have written at least some jslink code.

(function () {
    function verySimpleView(ctx, field) {
        var wrapper = 'This field is fully controlled by jslink<hr><span>{0}</span>';
        var value = ctx.CurrentItem[ctx.CurrentFieldSchema.Name] || "";
        return String.format(wrapper, value);
    }
    
    function verySimpleNewAndEdit(ctx) {
        var wrapper = 'This field is fully controlled by jslink<br><input type="text" id="{0}" value"{1}"/>';
        var id = 'tolle-' + new Date().getTime();
        var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
 
        formCtx.registerGetValueCallback(formCtx.fieldName, function () {
            var input = document.getElementById(id);
            return input.value;
        });
        var value = ctx.CurrentItem[ctx.CurrentFieldSchema.Name] || "";
        var html = String.format(wrapper, id, value);
        return html;
    }
    var overrideContext = {};
 
    overrideContext.Templates = overrideContext.Templates || {};
    overrideContext.Templates.Fields = {
        'VerySimpleColumn': {
            'View': verySimpleView,
            'DisplayForm': verySimpleView,
            'EditForm': verySimpleNewAndEdit,
            'NewForm': verySimpleNewAndEdit
        }
    };
 
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
})();

This is how it looks like in the DispForm:

jsgrid-010

JSGrid. First Step: Disable the field in Quick Edit

Now we are ready to handle the Quick Edit. What we’ll do first is to disable editing our column. Why? Let’s say we have some complicated logic for rendering and editing of our field, we don’t the quick edit override it. So before we start implementing the QuickEdit part of the field, we want to disable it. Here, perhaps, ends the implementation of Quick Edit for some business cases.

jsgrid-011

To determine the Quick Edit we can use the propery of ther Render Context called inGridMode. The Quick Edit list uses the “View” template:

function handleGridMode(ctx, field) {
    field.AllowGridEditing = false;
}
function verySimpleView(ctx, field) {
    var wrapper = 'This field is fully controlled by jslink<hr><span>{0}</span>';
    var value = ctx.CurrentItem[ctx.CurrentFieldSchema.Name] || "";
    if (ctx.inGridMode) {
        handleGridMode(ctx, field);
    }
    return String.format(wrapper, value);
}

Wiring up a jsgrid EditControl

When our code works in all forms and the values are not “damaged” in the Quick Edit View, then the next step is to create an Edit Control that is used by the jsgrid “engine”. The very minimal Edit Control object is as follows. It contains a few event listeners and properties:

{
    SupportedWriteMode: SP.JsGrid.EditActorWriteType.LocalizedOnly,
    SupportedReadMode: SP.JsGrid.EditActorReadType.LocalizedOnly,
    BindToCell: function () { console.log("tolle BindToCell"); },
    OnCellMove: function () { console.log("tolle OnCellMove"); },
    Focus: function () { console.log("tolle Focus"); },
    OnBeginEdit: function () { console.log("tolle OnBeginEdit"); },
    OnEndEdit: function () { console.log("tolle OnEndEdit"); },
    Unbind: function () { console.log("tolle Unbind"); },
    Dispose: function () { console.log("tolle Dispose"); }
}

This edit control is created and returned in a function that is called: createVerySimpleColumnGridEditControl.

var createVerySimpleColumnGridEditControl = function (gridContext, cellControl) {
    return {
        SupportedWriteMode: SP.JsGrid.EditActorWriteType.LocalizedOnly,
        SupportedReadMode: SP.JsGrid.EditActorReadType.LocalizedOnly,
        BindToCell: function () { console.log("tolle BindToCell"); },
        OnCellMove: function () { console.log("tolle OnCellMove"); },
        Focus: function () { console.log("tolle Focus"); },
        OnBeginEdit: function () { console.log("tolle OnBeginEdit"); },
        OnEndEdit: function () { console.log("tolle OnEndEdit"); },
        Unbind: function () { console.log("tolle Unbind"); },
        Dispose: function () { console.log("tolle Dispose"); }
    }
};

Now we have to register our Edit Control when jsgrid is ready. We have to write a callback function and invoke SP.GanttControl.WaitForGanttCreation. Inside the callback function we register our Edit Control for our field: SP.JsGrid.PropertyType.Utils.RegisterEditControl

function handleGridMode(ctx, field) {
    window.SP.SOD.executeOrDelayUntilScriptLoaded(function () {
        window.SP.GanttControl.WaitForGanttCreation(function (ganttChart) {
            var verySimpleColumn = null;
            var editId = "EDIT_TOLLE_VERYSIMPLEFIELD";
            var columns = ganttChart.get_Columns();

            for (var i = 0; i < columns.length; i++) {
                if (columns[i].columnKey == "VerySimpleColumn") {
                    verySimpleColumn = columns[i];
                    break;
                }
            }
            if (verySimpleColumn) {
                verySimpleColumn.fnGetEditControlName = function (record, fieldKey) {
                    return editId;
                };

                window.SP.JsGrid.PropertyType.Utils.RegisterEditControl(editId, function (gridContext, cellControl) {
                    return createVerySimpleColumnGridEditControl(gridContext, cellControl);
                }, []);
            }

        });
    }, "spgantt.js");
}

In our first version of the Edit Control we only log the event names to the web browser console. It works.

jsgrid-012

Implementing the actual editing

When working on this I did small changes to these events and tried it out in the web browser. I’d recommend it to you, too. Trying out is the best way of learning. Here comes the functions that we need to have to implement:

  • createVerySimpleColumnGridEditControl (“constructor”). Here we initialize the edit control
  • bindToCell. Here we get the cellContext that we save as a “private” variable on that Edit Control object. The cell context is needed to get and set the field value.
  • focus. Here we define what element should be focused. In this case we forward the focus event to the actual input
  • onBeginEdit. Here we show the Edit Control and make it editable.
  • onEndEdit. Here we save the field value and hide the edit control.

jsgrid-013

Some notes on the Edit Control and Events

The Edit Control has a “container” – a html element that contains the representation of the field in edit mode. The Edit Control Container is an overlay – an absolutely-positioned element that exists outside the actual listview. We must set the position and we are responsible for hiding it when the field is not edited:

container.style.cssText = 'visibility:hidden;position:absolute;top:0;left:0;background:#ffffff;';

We also need to set the dimensions of the edit control container. It is quite easy using the information from cellContext:

var bindToCell = function(ctx) {
    cellContext = ctx;
    //An input is put as an overlay. 
    //We have to set the width and height so that it takes the whole cell place
    container.style.minWidth = cellContext.cellWidth + 'px';
    container.style.width = cellContext.cellWidth + 'px';
    container.style.height = cellContext.cellHeight + 'px';
    console.log("tolle BindToCell");
};

In OnBeginEdit we have to show the container, and in OnEndEdit we have to hide it

//OnBeginEdit
cellContext.Show(container);
//OnEndEdit
cellContext.Hide(container);

We have to save the value using the cellContext.

var value = input.value;
cellContext.SetCurrentValue({
    localized: value
});

Final code

(function () {
    var editWrapper = '<span>This field is fully controlled by jslink</span><br><input type="text" id="{0}" value"{1}"/>';
    var createVerySimpleColumnGridEditControl = function (gridContext, gridTextInputElement) {
        var cellContext, inEdit, html, container, input, id;
        id = "tolle-" + new Date().getTime();
        html = String.format(editWrapper, id, "");
        container = document.createElement("div");
        container.innerHTML = html;
        input = container.getElementsByTagName("input")[0];
        container.style.cssText = 'visibility:hidden;position:absolute;top:0;left:0;background:#ffffff;';
        gridContext.parentNode.appendChild(container);
        var bindToCell = function(ctx) {
            cellContext = ctx;
            //An input is put as an overlay. We have to set the width and height so that it takes the whole cell place
            container.style.minWidth = cellContext.cellWidth + 'px';
            container.style.width = cellContext.cellWidth + 'px';
            container.style.height = cellContext.cellHeight + 'px';
            console.log("tolle BindToCell");
        };
        var onCellMove = function () { console.log("tolle OnCellMove"); };
        var focus = function(eventInfo) {
            input.focus();
            console.log("tolle Focus", eventInfo);
        };
        var onBeginEdit = function (eventInfo) {
            inEdit = true;
            var currentValue = cellContext.originalValue.localized;
            if (currentValue) {
                input.value = currentValue;
            }
            cellContext.Show(container);
            console.log("tolle OnBeginEdit");
            this.Focus(eventInfo);
        };
        var onEndEdit = function() {
            cellContext.Hide(container);
            inEdit = false;
            var value = input.value;
            cellContext.SetCurrentValue({
                localized: value
            });
            console.log("tolle OnEndEdit");
        };

        var unbind = function() { console.log("tolle Unbind"); };
        var dispose = function () { console.log("tolle Dispose"); }

        return {
            SupportedWriteMode: window.SP.JsGrid.EditActorWriteType.LocalizedOnly,
            SupportedReadMode: window.SP.JsGrid.EditActorReadType.LocalizedOnly,
            BindToCell: bindToCell,
            OnCellMove: onCellMove,
            Focus: focus,
            OnBeginEdit: onBeginEdit,
            OnEndEdit: onEndEdit,
            Unbind: unbind,
            Dispose: dispose
        }
    };

    function handleGridMode(ctx, field) {
        window.SP.SOD.executeOrDelayUntilScriptLoaded(function () {
            window.SP.GanttControl.WaitForGanttCreation(function (ganttChart) {
                var verySimpleColumn = null;
                var editId = "EDIT_TOLLE_VERYSIMPLEFIELD";
                var columns = ganttChart.get_Columns();

                for (var i = 0; i < columns.length; i++) {
                    if (columns[i].columnKey == "VerySimpleColumn") {
                        verySimpleColumn = columns[i];
                        break;
                    }
                }
                if (verySimpleColumn) {
                    verySimpleColumn.fnGetEditControlName = function (record, fieldKey) {
                        return editId;
                    };

                    window.SP.JsGrid.PropertyType.Utils.RegisterEditControl(editId, function (gridContext, cellControl) {
                        return createVerySimpleColumnGridEditControl(gridContext, cellControl);
                    }, []);
                }

            });
        }, "spgantt.js");
    }


    function verySimpleView(ctx, field) {
        var wrapper = 'This field is fully controlled by jslink<hr><span>{0}</span>';
        var value = ctx.CurrentItem[ctx.CurrentFieldSchema.Name] || "";
        if (ctx.inGridMode) {
            handleGridMode(ctx, field);
        }
        return String.format(wrapper, value);
    }
    
    function verySimpleNewAndEdit(ctx) {
        var id = 'tolle-' + new Date().getTime();
        var formCtx = window.SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

        formCtx.registerGetValueCallback(formCtx.fieldName, function () {
            var input = document.getElementById(id);
            return input.value;
        });
        var value = ctx.CurrentItem[ctx.CurrentFieldSchema.Name] || "";
        var html = String.format(editWrapper, id, value);
        return html;
    }
    var overrideContext = {};

    overrideContext.Templates = overrideContext.Templates || {};
    overrideContext.Templates.Fields = {
        'VerySimpleColumn': {
            'View': verySimpleView,
            'DisplayForm': verySimpleView,
            'EditForm': verySimpleNewAndEdit,
            'NewForm': verySimpleNewAndEdit
        }
    };

    window.SPClientTemplates.TemplateManager.RegisterTemplateOverrides(overrideContext);
})();


Summary

Well, jsgrid is quite complicated. I have tried to keep it as simple and minimalistic as possible. When we can these basics, we can move on and master advanced examples where we can deliver high value to business that loves Quick Edit :)

Sources

Interesting, Anton, Andrey and me are born in Sovyet and are interested in JSGrid. Coincidence? :)

Announcing web based SQL Max Memory calculator

sql-max-logo

Today I want to announce a tiny web application for calculating max memory in the SQL Server to improve the overall performance in you SharePoint environment:

SQL Max Memory Calculator.

One of the important actions to improve the performance in SharePoint is fine tuning of the SQL Databases. Regarding the databases one of the crucial settings is the Max Memory Setting. You can read more about database optimizations for SharePoint in a whitepaper written by SharePoint MVP Vlad Catrinescu. The document is available on the SharePoint Community Web Site:

Vlad Catrinescu also created a windows application for calculating the max memory for SQL which can be downloaded from codeplex (GPL v2):

This windows application has inspired me and my colleagues to create the web based application SQL Max. The goal of the SQL Max web app is to take Vlad’s idea a step further and make it available directly in your browser, on desktop at work, or on the go in your mobile. This mobile web app will also be available for offline access. Simply put, why should you dowload a zip file, extract and run the .exe file? Perhaps you cannot run executable files due restrictions, or perhaps you are not running Windows at all.

How it works

The web application is completely javascript-based. It is open source (MIT license) and the code is freely available at github:

The most important part of the solution is the formula. The original formula (C#) is provided by Vlad Catrinescu is as follows:

SQL Max Memory = TotalPhyMem – (NumOfSQLThreads * ThreadStackSize) – (1GB * CEILING(NumOfCores/4)) – OS Reserved
NumOfSQLThreads = 256 + (NumOfProcessors*- 4) * 8 (* If NumOfProcessors > 4, else 0)
ThreadStackSize = 2MB on x64 or 4 MB on 64-bit (IA64)
OS Reserved = 20% of total ram for under if system has 15GB. 12.5% for over 20GB

When you’ve filled in the values in the form, you’ll see the max memory in the blue box above:

sql-max-001

How to apply this setting in the SQL Server

To apply the max memory follow these steps, the instructions come originally from technet:

  1. In Object Explorer, right-click a server and selectProperties.
  2. Click the Memory node.
  3. Under Server Memory Options, enter the amount that you want for Minimum server memory and Maximum server memory.Use the default settings to allow SQL Server to change its memory requirements dynamically based on available system resources. The default setting for min server memory is 0, and the default setting for max server memory is 2147483647 megabytes (MB). The minimum amount of memory you can specify for max server memory is 16 MB.

Contributors

Export any web part from a SharePoint page

Almost all web parts can be exported from a SharePoint page. An exported web part  can be imported on another page or it can be used as a source in a module to provision pages. An exception is the XsltListViewWebPart, there you cannot enable exporting. I have used Glyn Clough’s method before which has worked although it is a complicated process. Now I have found another way for exporting any web part (even ListViewWebPart and XsltListViewWebPart) present on a page. A method that only involves a web browser.

How to export any web part

First, we need to find out the webpartid. To do so inspect the html markup with the web browser dev tools of your choice.

export-webpart-001

In SharePoint there is a hidden application page that exports web parts: /_vti_bin/exportwp.aspx. This page takes two query parameters:

  • pageurl. The absolute url of the page where the web part resides that you want to export
  • guidstring. The guid that is called webpartid in the markup on the page

So, suppose, you have this site: https://intranet.contoso.com and a web part (id: 0c3adfe9-8f5d-4432-918a-42410e4e324d) on a page https://intranet.contoso.com/Pages/default.aspx

This will be the resulting URL to export your webpart:

https://intranet.contoso.com/_vti_bin/exportwp.aspx?pageurl=https://intranet.contoso.com/Pages/default.aspx&guidstring=0c3adfe9-8f5d-4432-918a-42410e4e324d

Paste it into the web browser address bar and you’ll download an xml file with your web part definition. This method works in SharePoint 2010 and SharePoint 2013 and even in SharePoint Online (Office 365).

Sources

Natalia Tsymbalenko. Get the list view web part convertable

Maurice Prather. Exporting a ListViewWebPart

SharePoint StackExchange

I am glad to update my answer on SharePoint StackExchange site and provide a much easier way of exporting any web part from SharePoint.

Export SharePoint List Data To Xml through PowerShell

Today my colleague Johannes Milling wrote an awesome post:

Export SharePoint List Data To XML Directly from the GUI

He uses the old and forgotten RPC-based web service owssvr.dll (that has existed since SharePoint 2003). This url pattern is used to get the xml-formatted list data for a specific ListView:

http://<site_url>/_vti_bin/owssvr.dll?Cmd=Display&List=<list guid>&View=<view guid>&Query=*&XMLDATA=TRUE

To automate this I have written a PowerShell function. All the details are in the comments:

function Export-OIPSPListDataAsXml {
<#
.Synopsis
   Exports list items as xml
.DESCRIPTION
   This function uses a built-in hidden service owssvr.dll in SharePoint
.PARAMETER Web
   SPWeb or a url for the SPWeb object where the list resides
.PARAMETER ListName
   List Name (List Title)
.PARAMETER ViewName
   Name of the List View to export the data
.EXAMPLE
   Export-OIPSPListView -Web http://myawesomesite -ListName "Teddy Bears" -ViewName "All Items"
.EXAMPLE
   Export-OIPSPListView -Web $webInstance -ListName "Top Links" -ViewName "All Items"
.Notes
    Name: Export-OIPSPListDataAsXml
    Author: Anatoly Mironov
    Last Edit: 2014-09-11
    Keywords: SPList, SPWeb, SPListView, Xml
.Link

http://chuvash.eu

#>
    [CmdLetBinding()]
    param(
	[Parameter(Mandatory=$true)]
    [Microsoft.SharePoint.PowerShell.SPWebPipeBind]$Web,
    [Parameter(Mandatory=$true)]
    [string]$ListName,
    [Parameter(Mandatory=$true)]
    [string]$ViewName)

    $spWeb = $Web.Read()
    $list = $spWeb.Lists[$ListName]
    if (!$list) { throw "List $ListName on web $($spWeb.Url) could not be found" }
    $view = $list.Views[$ViewName]
    if (!$view) { throw "View $ViewName on web $ListName could not be found" }
    $url = "{0}/_vti_bin/owssvr.dll?Cmd=Display&List={1}&View={2}&Query=*&XMLDATA=TRUE" `
            -f $spWeb.Url, $list.ID, $view.ID
    $wc = New-Object Net.WebClient
    $wc.UseDefaultCredentials = $true
    $wc.DownloadString($url)
}

Improving the web performance of an intranet

overloaded-sharepoint-in-browser

All the “small” app parts, web parts, delegate controls, user controls, and other “packages” that “must” be delivered to the users on every page load of the Start Page of your Intranet.

Recently we made an investment to improve the performance of our intranet. We made many changes in different layers: SQL, Network, Browser upgrade and code. Here I want to tell about what code changes we did to improve the web browser performance. Please leave feedback if you find it useful. You can also share your suggestions. We measured the performance before our code changes and after them. We had amazing results. Unfortunately I can not share any numbers, but we improved the Time to First Byte, time to load event firing in the browser, memory consumption in the clients and, perhaps, the most important, we improved the perceived performance of the Intranet, the way how users experience the speed and UI responsiveness. To do this I got many ideas of my project colleagues and branch colleagues. Here is the list of changes we’ve implemented:

- Execute code on demand

Consider this scenario: on a page users can click on a button to download a vcard. Aggregating user information is a costly operation that requires getting data from the User Profile Service, getting the profile image from SharePoint. Don’t ever do this operation on page load. Move the code to the “onclick” action. In other words, work when it is needed. It is like cooking a lot of food, when you are not hungry. It is nothing new, unfortunately there were a couple of the “eager code” places.

- Cache results, investigate what parts can be cached and how fresh data needs to be

All data on your page doesn’t need to be fetched on every page load. In our project We listed all the “parts” of the start page and other often visited pages and went to the business and asked them to evaluate how fresh data should be. Some parts should be as fresh as possible (no cache), whereas it would be tolerated that the information could be dirty (cache up to one week or more).

- Reference javascript and css files from one location

Do you have jQuery in your SharePoint Intranet. How many copies do you have? What we did in our Intranet was that we partially implemented the CDN concept. Even though we don’t distribute our resource files geographically, we have 1-to-1 relation between a file and its absolute URL. In the whole intranet, we have only one jQuery url and only one our intranet.core.js url. We did by creating a dedicated CDN site collection. This alone makes a big difference. To evolve the idea we could provision resources outside SharePoint to remove the authorization overhead. We could also distribute it geographically by having files closer to the end users.

- Unify your framework and your dependencies

In our projects we had a couple of SharePoint-hosted apps developed by different teams. We had different approaches and different framework that solved almost the same problem: AngularJS and KnockoutJS. Eventhough apps are independent pieces of software, they were used within the same page (as app parts). It was too much http traffic. We agreed on Developer Guidelines and chose one framework.

- Do not hide controls on the page with CSS, remove them

On the start page in our intranet we didn’t show the left navigation, but it was still rendered in code behind. Instead hiding it with CSS, we just removed it by an empty ContenPlaceHolder in our Start Page Layout:


<asp:Content ContentPlaceholderId="PlaceHolderLeftNavBar" runat="server"/>

- Optimize jQuery Selectors

We reviewed all the jQuery code and improved the selectors. Optimizing the selectors will improve the overall performance in the browser, especially in older browsers. The worst example is using text selectors, like this one:

jQuery('#NoteBoardContainer*:contains("There are no notes posted yet. You can use notes to comment on a page"):last');

It will sink your IE8 browser.

- Minify javascript and CSS files

Minifying resource files like javascript and css is not hard. My recommendation is to use Web Essentials plugin in Visual Studio. Alternatively you can use the SharePoint Assets Minifier.

- Use the weakest selectors in CSS and in LESS

In our project we are using LESS. With LESS it is easier to write  readable CSS code. But be aware of the output. Do not make the selectors too strong: Use the weakest CSS Selectors. The weakest selectors will make it easier to maintain the CSS and it will minimize the amount of KB the server needs to send to your users’ browsers.

- Ensure javascript and CSS files are cached

JavaScript and CSS files should be cached. You should also avoid 304 responses where the Server answers “Not Modified”, because this has an impact on the performance. Configure the Blob Cache and put your resources into the Style Library.

- Remove all app parts from SharePoint-hosted Apps from the start page

There can be exceptions, but we encountered that client web parts (app parts) from SharePoint-hosted apps had a huge impact on the performance. The combination of a couple of app parts on often visited pages (like the start page on the intranet) led to long page load times. These are the reasons why you should not have SharePoint Hosted App Parts on your start page:

  1. App Parts are iframes. They are loaded simultaneously if you add client web parts (app parts) in a usual way. They hold up the whole page. Users cannot interact with the intranet page until all the content in all app parts has been loaded. This can be partially improved if you introduce a delay in the app part loading, by developing an own engine. See my blog post where I mention such a concept: AppLoader Concept for SharePoint apps.
  2. The content from a SharePoint AppWeb is not fully cached. If you examine the http traffic from the apps you’ll see a lot of 304 responses, meaning the browser requests when the server answers that there is no newer version. This has an impact on the performance. See more in Alik Levin’s blog: ASP.NET Performance: Get Rid of HTTP 401 and HTTP 304. In a SharePoint-hosted app you don’t have any control what so ever to adjust the the cache settings. This is not the case in the Provider-hosted apps.
  3. SharePoint-hosted apps can only use javascript. The code is executed on the client. Older browsers like IE9 or IE8 render the pages slower. The Start Page that is slower than the rest of the Intranet is not something that will engage your users.
  4. App Parts are iframes that do not know about their dimensions. App parts often need to update the height and the width  of the parent iframe. This causes irritating flickering. Perhaps OK on some pages, but I’d say totally unacceptable on the start page of your brand new intranet..

What did we do instead of App Parts on the Start Page? We converted them into Script Editor Web Parts, the app parts were only one-time parts, they only were used on the start page.

Do not get me wrong. What we did was not abandoning apps as a model, we just removed wrong apps, apps that cannot be reused, the SharePoint-hosted apps that had big performance issues. I am looking forward creating right apps, that are written with performance, reusability, scalability and good design in mind.

 

Discovering SharePoint

And having fun doing it

Bram de Jager's SharePoint blog

My view and thoughts on SharePoint.

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

The Zuul Cat Idea Brewery

Where ideas on software development and entrepreneurship brew.

Paul J. Swider

Inspire! Teach! Awe!

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Alexander Ahrens

MCPD | SharePoint | Web Development | JavaScript | .NET

Cameron Dwyer | SharePoint, Outlook, OnePlaceMail

OnePlaceMail, SharePoint, Outlook & 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.com

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

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode, ya mama

Treacle tarts for great justice

Follow

Get every new post delivered to your Inbox.

Join 245 other followers