The sort order for a list item in a links list is stored in the Xml property, in the attribute ows_Order. This however is not migrated with content deployment, hence the need for this event handler.
This ItemEventReceiver is activated as a web scoped feature, on all links lists by using the following in the elements.xml file:
<Receivers ListTemplateId="103">
The event handler code is here:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace MaskedSharePointer.Features.Receivers
{
public class LinksListReceiver : SPItemEventReceiver
{
private string _rankFieldName = "Rank";
private string _xmlAttributeName = "ows_Order";
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
SaveSortOrder(properties);
}
public override void ItemUpdated(SPItemEventProperties properties)
{
base.ItemUpdated(properties);
SaveSortOrder(properties);
}
private void SaveSortOrder(SPItemEventProperties properties)
{
this.DisableEventFiring();
try
{
using (SPWeb web = properties.OpenWeb())
{
SPList list = web.Lists[properties.ListTitle];
if (!list.Fields.ContainsField(_rankFieldName))
{
SPField newField = list.Fields.CreateNewField(SPFieldType.Number.ToString(), _rankFieldName);
newField.ReadOnlyField = true;
list.Fields.Add(newField);
}
foreach (SPListItem listItem in list.Items)
{
XElement element = XElement.Parse(listItem.Xml);
XAttribute attribute = element.Attribute(_xmlAttributeName);
decimal newRank = Convert.ToDecimal(attribute.Value);
if (newRank != Convert.ToDecimal(listItem[_rankFieldName]))
{
listItem[_rankFieldName] = newRank;
listItem.Update();
}
}
}
}
finally
{
this.EnableEventFiring();
}
}
}
}
No comments:
Post a Comment