Jaa


SPWebPartManager doesn't honour the WebPartCancelEventArgs.Cancel value while deleting the webpart

Some scenarios developers may want to restrict users from deleting webparts from  a page, the scenarios varies.
SPWebPartManager has got a event named ‘OnWebPartDeleting’.The issue here is, the deletion of the webpart cannot be
avoided by setting the WebPartCancelEventArgs.Cancel = true; within the   ‘OnWebPartDeleting’ event.
So the SPWebPartManager’s ‘OnWebPartDeleting’event is not going to help us in accomplishing our requirement, here I have a workaround, it may help you! 

 

 

……….
<script runat="server">
  protected void On_WebPartDeleting(object sender, WebPartCancelEventArgs e)
  {
      Page.Response.Write("Sorry! This webpart cannot be deleted!<br>");  
       e.Cancel = true;    
  }
</script>
  <form >

 
<WebPartPages:SPWebPartManager OnWebPartDeleting="On_WebPartDeleting"  id="m" runat="Server"/>

 

As a workaround your can implement this, not sure you like this approach:)

Develop a custom HttpModule to trace the WebPart delete events,  basically tracing the ‘__EVENTARGUMENT’ value.

See below the implementation.

    1: void application_PostAuthorizeRequest(object sender, EventArgs e)
    2: {
    3: HttpContext context = HttpContext.Current;
    4:  
    5: if (context != null && context.Request.Params["__EVENTARGUMENT"] != null && Convert.ToString(context.Request.Params["__EVENTARGUMENT"]).Length > 1)
    6: {
    7: string contextValue = context.Request.Params["__EVENTARGUMENT"];
    8:  
    9: if (contextValue.Contains("MSOMenu_Delete"))
   10: {
   11: try
   12: {
   13: string[] keyValue = contextValue.Split(new char[] { ';' });
   14: Guid guid = new Guid(keyValue[0]);
   15: SPWeb web = SPContext.Current.Web;
   16: SPLimitedWebPartManager manager = web.GetLimitedWebPartManager(context.Request.RawUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
   17: System.Web.UI.WebControls.WebParts.WebPart webpart = manager.WebParts[guid];
   18: context.Response.Write("<h5><font color=red>Sorry, you do not have the rights to delete this webpart. Please contact your admin.</font></h5><br><a href=" + context.Request.RawUrl+ ">Back</a>");
   19:  
   20: context.Response.Flush(); 
   21: context.Response.End();
   22: }
   23: catch (Exception ex)
   24: {
   25: }
   26: }
   27: }

 

This is a tricky workaround, however if you are looking for options to achieve this functionality then this would help.

Enjoy!