Get before properties in ItemUpdated event via CSOM in a RER
-
29-09-2020 - |
Pergunta
Can I get the before properties in item updated? I need to check if a field changed its value, between the previous and the new value in a RER with CSOM.
The following code tell me the BeforeProperties
array is empty. Any idea?
Should I use ItemUpdating
instead of ItemUpdated
?
private void HandleItemUpdated(SPRemoteEventProperties properties)
{
using (ClientContext clientContext = TokenHelper.CreateRemoteEventReceiverClientContext(properties))
{
if (clientContext != null)
{
List requestList = clientContext.Web.Lists.GetById(properties.ItemEventProperties.ListId);
ListItem item = requestList.GetItemById(properties.ItemEventProperties.ListItemId);
clientContext.Load(item);
clientContext.ExecuteQuery();
try
{
string beforeTitle = properties.ItemEventProperties.BeforeProperties[Constants.Projects.ProjectTitle].ToString();
string afterTitle = item[Constants.Projects.ProjectTitle].ToString();
if(beforeTitle!=afterTitle)
{
string siteUrl = item[Constants.Projects.ProjectSite].ToString();
ClientContext subSiteContext = new ClientContext(siteUrl);
Web projectSubSite = subSiteContext.Web;
subSiteContext.Load(
projectSubSite,
website => website.Title,
website => website.Created);
projectSubSite.Title = afterTitle;
FieldUrlValue updatedSiteUrl = new FieldUrlValue();
updatedSiteUrl.Url = projectSubSite.Url;
updatedSiteUrl.Description = afterTitle + " Site";
item[Constants.Projects.ProjectSite] = siteUrl;
item.Update();
subSiteContext.ExecuteQuery();
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
When I tried associating ItemUpdating
, the event is never fired( but the event is the in SharePoint Manager.!
Solução
No, there are no before properties available in asynchronous events. Unfortunately, even in the syncronous event itemupdating there are no before properties. This is where remote event receivers behave different then server side event receivers.
Solution: use the synchronous event itemupdating, get current item and read it's properties.
var itemId = properties.ItemEventProperties.ListItemId;
var listTitle = properties.ItemEventProperties.ListTitle;
var list = clientContext.Web.GetListByTitle(dingoesList);
var item= list.GetItemById(currentDingoId);
clientContext.Load(item);
clientContext.ExecuteQuery();
var oldTitle = item["Title"].ToString();
var newTitle = properties.ItemEventProperties.AfterProperties["Title"].ToString();