Quantcast
Channel: Vardhaman Deshpande
Viewing all articles
Browse latest Browse all 134

CSOM tip for making your code flexible

$
0
0
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!

Viewing all articles
Browse latest Browse all 134

Trending Articles