Monday, January 23, 2012

SPLongOperation error for ItemAdding Event In SharePoint 2010



We recently upgrade one of our project from SharePoint 2007 to SharePoint 210. In that project we user event handler for list. In ItemAdding event we use to create new site which takes times for creation. So we use SPLongOperation to handle it  but in SharePoint 2010 its same code gives error for "Object reference null" for SPLongOperation being statement.
So we had following workaround for this problem.

Create Web Part with following Code and add this web part to publishing Page

protected override void CreateChildControls(){
 if (this.Page.Request.QueryString["Processid"] != null)
            {           

                using (SPLongOperation ctx = new SPLongOperation(this.Page))
                {
                    try
                    {
                        ctx.LeadingHTML = "Please wait while your operation is being executed.";
                        ctx.TrailingHTML = "Site is being created. Please wait....";
                        ctx.Begin();

                        System.Threading.Thread.Sleep(5000);
                        string eid = this.Page.Request.QueryString["Processid"].ToString();
                        int count = 1;
                        while (true)
                        {
                            using (SPWeb web = SPContext.Current.Site.OpenWeb(SPContext.Current.Web.ID))
                            {
                                if (web.Properties[eid].ToString() != "Completed" && count < 18)
                                {

                                    System.Threading.Thread.Sleep(5000);
                                    count++;
                                }
                                else
                                    break;
                            }
                        }
                        ctx.End(this.Page.Request.QueryString["h"].ToString());
                    }
                    catch (Exception ex)
                    {
                        this.lbl.Text = ex.Message.ToString() + Environment.NewLine + ex.StackTrace.ToString() ;
                    }
                }
            }
}

In event handler modify ItemAdding event as follows

 public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            string guid
                = string.Format("ProcessId{0}_{1}", DateTime.Now.ToString("MMddyyyy"), Guid.NewGuid().ToString());
            Thread thread = new Thread(() => FunctionName(properties,guid));
            thread .Start();

            properties.Status = SPEventReceiverStatus.CancelNoError;
            properties.Cancel = true;
            SPUtility.Redirect({Url of page on which out put above webpart}, SPRedirectFlags.Default, _currentContext,string.Format ("Processid={0}&h={1}",guid , properties.RelativeWebUrl));
        }

Hope this work for you also

No comments:

Post a Comment