Wednesday 25 March 2015

CSOM tip for making your code flexible

We all know that in CSOM, for any given object, we can specify certain properties to be brought back from the server. Something like this:

This will only bring back the Title property of the web thus reducing data traveling over the wire.

Now in this case, the second parameter of the clientContext.Load method is an object of type Expression<Func<Web, object>>[]

This is an array of Linq expressions which can be utilized to our benefit. We can convert that array into a parameter which can be passed to a "Utility" function. This function will only get the properties specified in that array. Like this:

Then, that function can be called with different parameters depending on the properties we want to fetch from the server for that particular instance. For example:

Only get the Title and Id of the Web:

Only get the MasterUrl and the CustomMasterUrl of the web:

For both the above calls, we are not changing the GetWebDetails function. It will always return a Web object with the specified properties filled in. It will also reduce data travelling over the wire, as only the specified properties will be fetched. Thus, making your code more flexible and performance friendly.

You can also have other utility functions for Lists, Users etc. Here is a similar function for Lists:

Hope you find this useful!


Rahul Dayal Blog said...

can we use this with JSOM.

Vardhaman Deshpande said...

Not as it is. But you could do something similar in JSOM.

JSOM uses syntax like: clientContext.load(web, "Include(Title,Id)");

You can send the "Include(Title,Id)" as a parameter to functions.

anil said...

Nice Info