Imagine one requirement from customer: prevent user from attaching an attachment when creating a new item in a list. User can attach an attachment anytime from anywhere but just cannot do the same when creating a new item.
It’s simple if we can tell the difference between adding attachment when creating a new item and adding attachment from Ribbon after created, but it costs a few time to find. Of course we’ll handle attachment in event receiver “ItemAttachmentAdding”, I created event receivers and wrote test code like this:
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
}
public override void ItemAttachmentAdding(SPItemEventProperties properties)
{
base.ItemAttachmentAdding(properties);
if(IsAttachingInNewForm(properties.ListItem))
{
Properties.Cancel = true;
}
}
We’ll check if user is trying to attach an attachment in new form in function “IsAttachingInNewForm”. Actually it’s very simple:
bool result = false;
try
{
result = string.Equals(item["owshiddenversion"].ToString(), "1", StringComparison.OrdinalIgnoreCase);
}
catch{}
return result;
Here we check “owshiddenversion” field of item, if the item is newly created, the value of “owshiddenversion” is “1”, because when user creates a new item, attaches an attachment then click “Save”, code will run into ItemAttachmentAdding event receiver, now the item has been created, we can see the item ID is not 0, and the field “owshiddenversion” is assigned to “1”.
If we reopen a newly created item, or click Attach button in Ribbon and attach a file, the “owshiddenversion” will be changed to “2”.
Orginally, field “owshiddenversion” is used in Syncronization purpose, MSDN describes it as:
“Windows SharePoint Services 3.0 uses the owshiddenversion Field (in the Microsoft.SharePoint.SPBuiltInFieldId Class) to detect conflicts. If this field value is not supplied during the update process, the server will overwrite all changes. A client must always supply this field value during the update process, in order to prevent data loss. The field value is the number that the server returned most recently.
The owshiddenversion Field value allows the server to determine if you are updating an outdated copy of an item. For example, a client synchronizes an item and gets a value of “2” for this attribute. In the interim, someone changes the title of that item on the server, so the value changes to “3”. When the client sends a change with a value of “2” and the item has been modified since the client last requested it, the server returns a TP_E_VERSIONCONFLICT (0x81020015) error and a list of the current contents of the item.” From http://msdn.microsoft.com/en-au/library/cc264293.aspx