Need job

Looking for job in Europe. Please contact thru LinkedIn profile.

Monday, February 18, 2013

SPItemEventReceiver invoke source detection

How to detect who has update item? User from web browser or web service?
The solution is to store "Label" in thread data slot.
Sync receivers like Adding and Updating executes in the same thread as update code, in my case is web service.

Update Ready-to-use code
using System;
using System.Threading;

namespace Common
{
    public class Threading
    {
        public static void MarkThreadWith(string mark, object val)
        {
            LocalDataStoreSlot store = Thread.GetNamedDataSlot(mark);
            if (store == null)
            {
                store = Thread.AllocateNamedDataSlot(mark);
            }

            Thread.SetData(store, val);
        }

        public static bool CheckThreadFor(string mark, T val) where T : IEquatable
        {
            LocalDataStoreSlot store = Thread.GetNamedDataSlot(mark);
            if (store == null)
            {
                return false;
            }
            try
            {
                T newSlotData = (T)Thread.GetData(store);
                return newSlotData.Equals(val);
            }
            ///wrong thread
            catch (NullReferenceException)
            {
                return false;
            }
        }
    }
}

No comments:

Post a Comment